command.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. package commands
  2. import (
  3. "encoding/gob"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "encoding/json"
  13. "github.com/astaxie/beego"
  14. beegoCache "github.com/astaxie/beego/cache"
  15. _ "github.com/astaxie/beego/cache/memcache"
  16. _ "github.com/astaxie/beego/cache/redis"
  17. "github.com/astaxie/beego/logs"
  18. "github.com/astaxie/beego/orm"
  19. "github.com/lifei6671/gocaptcha"
  20. "github.com/lifei6671/mindoc/cache"
  21. "github.com/lifei6671/mindoc/conf"
  22. "github.com/lifei6671/mindoc/models"
  23. "github.com/lifei6671/mindoc/utils/filetil"
  24. "github.com/astaxie/beego/cache/redis"
  25. )
  26. // RegisterDataBase 注册数据库
  27. func RegisterDataBase() {
  28. beego.Info("正在初始化数据库配置.")
  29. adapter := beego.AppConfig.String("db_adapter")
  30. orm.DefaultTimeLoc = time.Local
  31. if strings.EqualFold(adapter, "mysql") {
  32. host := beego.AppConfig.String("db_host")
  33. database := beego.AppConfig.String("db_database")
  34. username := beego.AppConfig.String("db_username")
  35. password := beego.AppConfig.String("db_password")
  36. timezone := beego.AppConfig.String("timezone")
  37. location, err := time.LoadLocation(timezone)
  38. if err == nil {
  39. orm.DefaultTimeLoc = location
  40. } else {
  41. beego.Error("加载时区配置信息失败,请检查是否存在 ZONEINFO 环境变量->", err)
  42. }
  43. port := beego.AppConfig.String("db_port")
  44. dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=%s", username, password, host, port, database, url.QueryEscape(timezone))
  45. if err := orm.RegisterDataBase("default", "mysql", dataSource); err != nil {
  46. beego.Error("注册默认数据库失败->", err)
  47. os.Exit(1)
  48. }
  49. } else if strings.EqualFold(adapter, "sqlite3") {
  50. database := beego.AppConfig.String("db_database")
  51. if strings.HasPrefix(database, "./") {
  52. database = filepath.Join(conf.WorkingDirectory, string(database[1:]))
  53. }
  54. if p,err := filepath.Abs(database); err == nil {
  55. database = p
  56. }
  57. dbPath := filepath.Dir(database)
  58. if _,err := os.Stat(dbPath); err != nil && os.IsNotExist(err) {
  59. os.MkdirAll(dbPath, 0777)
  60. }
  61. err := orm.RegisterDataBase("default", "sqlite3", database)
  62. if err != nil {
  63. beego.Error("注册默认数据库失败->", err)
  64. }
  65. } else {
  66. beego.Error("不支持的数据库类型.")
  67. os.Exit(1)
  68. }
  69. beego.Info("数据库初始化完成.")
  70. }
  71. // RegisterModel 注册Model
  72. func RegisterModel() {
  73. orm.RegisterModelWithPrefix(conf.GetDatabasePrefix(),
  74. new(models.Member),
  75. new(models.Book),
  76. new(models.Relationship),
  77. new(models.Option),
  78. new(models.Document),
  79. new(models.Attachment),
  80. new(models.Logger),
  81. new(models.MemberToken),
  82. new(models.DocumentHistory),
  83. new(models.Migration),
  84. new(models.Label),
  85. new(models.Blog),
  86. new(models.Template),
  87. )
  88. gob.Register(models.Blog{})
  89. gob.Register(models.Document{})
  90. gob.Register(models.Template{})
  91. //migrate.RegisterMigration()
  92. }
  93. // RegisterLogger 注册日志
  94. func RegisterLogger(log string) {
  95. logs.SetLogFuncCall(true)
  96. logs.SetLogger("console")
  97. logs.EnableFuncCallDepth(true)
  98. if beego.AppConfig.DefaultBool("log_is_async", true) {
  99. logs.Async(1e3)
  100. }
  101. if log == "" {
  102. logPath,err := filepath.Abs(beego.AppConfig.DefaultString("log_path",conf.WorkingDir("runtime","logs")))
  103. if err == nil {
  104. log = logPath
  105. }else{
  106. log = conf.WorkingDir("runtime","logs")
  107. }
  108. }
  109. logPath := filepath.Join(log, "log.log")
  110. if _, err := os.Stat(log); os.IsNotExist(err) {
  111. os.MkdirAll(log, 0777)
  112. }
  113. config := make(map[string]interface{}, 1)
  114. config["filename"] = logPath
  115. config["perm"] = "0755"
  116. config["rotate"] = true
  117. if maxLines := beego.AppConfig.DefaultInt("log_maxlines", 1000000); maxLines > 0 {
  118. config["maxLines"] = maxLines
  119. }
  120. if maxSize := beego.AppConfig.DefaultInt("log_maxsize", 1<<28); maxSize > 0 {
  121. config["maxsize"] = maxSize
  122. }
  123. if !beego.AppConfig.DefaultBool("log_daily", true) {
  124. config["daily"] = false
  125. }
  126. if maxDays := beego.AppConfig.DefaultInt("log_maxdays", 7); maxDays > 0 {
  127. config["maxdays"] = maxDays
  128. }
  129. if level := beego.AppConfig.DefaultString("log_level", "Trace"); level != "" {
  130. switch level {
  131. case "Emergency":
  132. config["level"] = beego.LevelEmergency;break
  133. case "Alert":
  134. config["level"] = beego.LevelAlert;break
  135. case "Critical":
  136. config["level"] = beego.LevelCritical;break
  137. case "Error":
  138. config["level"] = beego.LevelError; break
  139. case "Warning":
  140. config["level"] = beego.LevelWarning; break
  141. case "Notice":
  142. config["level"] = beego.LevelNotice; break
  143. case "Informational":
  144. config["level"] = beego.LevelInformational;break
  145. case "Debug":
  146. config["level"] = beego.LevelDebug;break
  147. }
  148. }
  149. b, err := json.Marshal(config);
  150. if err != nil {
  151. beego.Error("初始化文件日志时出错 ->",err)
  152. beego.SetLogger("file", `{"filename":"`+ logPath + `"}`)
  153. }else{
  154. beego.SetLogger(logs.AdapterFile, string(b))
  155. }
  156. beego.SetLogFuncCall(true)
  157. }
  158. // RunCommand 注册orm命令行工具
  159. func RegisterCommand() {
  160. if len(os.Args) >= 2 && os.Args[1] == "install" {
  161. ResolveCommand(os.Args[2:])
  162. Install()
  163. } else if len(os.Args) >= 2 && os.Args[1] == "version" {
  164. CheckUpdate()
  165. os.Exit(0)
  166. }
  167. }
  168. //注册模板函数
  169. func RegisterFunction() {
  170. beego.AddFuncMap("config", models.GetOptionValue)
  171. beego.AddFuncMap("cdn", func(p string) string {
  172. cdn := beego.AppConfig.DefaultString("cdn", "")
  173. if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
  174. return p
  175. }
  176. //如果没有设置cdn,则使用baseURL拼接
  177. if cdn == "" {
  178. baseUrl := beego.AppConfig.DefaultString("baseurl", "")
  179. if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
  180. return baseUrl + p[1:]
  181. }
  182. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(baseUrl, "/") {
  183. return baseUrl + "/" + p
  184. }
  185. return baseUrl + p
  186. }
  187. if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
  188. return cdn + string(p[1:])
  189. }
  190. if !strings.HasPrefix(p, "/") && !strings.HasSuffix(cdn, "/") {
  191. return cdn + "/" + p
  192. }
  193. return cdn + p
  194. })
  195. beego.AddFuncMap("cdnjs", conf.URLForWithCdnJs)
  196. beego.AddFuncMap("cdncss", conf.URLForWithCdnCss)
  197. beego.AddFuncMap("cdnimg", conf.URLForWithCdnImage)
  198. //重写url生成,支持配置域名以及域名前缀
  199. beego.AddFuncMap("urlfor", conf.URLFor)
  200. beego.AddFuncMap("date_format", func(t time.Time, format string) string {
  201. return t.Local().Format(format)
  202. })
  203. }
  204. //解析命令
  205. func ResolveCommand(args []string) {
  206. flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
  207. flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
  208. flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
  209. flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
  210. flagSet.Parse(args)
  211. if conf.WorkingDirectory == "" {
  212. if p, err := filepath.Abs(os.Args[0]); err == nil {
  213. conf.WorkingDirectory = filepath.Dir(p)
  214. }
  215. }
  216. if conf.ConfigurationFile == "" {
  217. conf.ConfigurationFile = conf.WorkingDir( "conf", "app.conf")
  218. config := conf.WorkingDir("conf", "app.conf.example")
  219. if !filetil.FileExists(conf.ConfigurationFile) && filetil.FileExists(config) {
  220. filetil.CopyFile(conf.ConfigurationFile, config)
  221. }
  222. }
  223. if err := gocaptcha.ReadFonts(conf.WorkingDir( "static", "fonts"), ".ttf");err != nil {
  224. log.Fatal("读取字体文件时出错 -> ",err)
  225. }
  226. if err := beego.LoadAppConfig("ini", conf.ConfigurationFile);err != nil {
  227. log.Fatal("An error occurred:", err)
  228. }
  229. if conf.LogFile == "" {
  230. logPath,err := filepath.Abs(beego.AppConfig.DefaultString("log_path",conf.WorkingDir("runtime","logs")))
  231. if err == nil {
  232. conf.LogFile = logPath
  233. }else{
  234. conf.LogFile = conf.WorkingDir("runtime","logs")
  235. }
  236. }
  237. conf.AutoLoadDelay = beego.AppConfig.DefaultInt("config_auto_delay",0)
  238. uploads := conf.WorkingDir("uploads")
  239. os.MkdirAll(uploads, 0666)
  240. beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
  241. beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
  242. beego.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views")
  243. fonts := conf.WorkingDir("static", "fonts")
  244. if !filetil.FileExists(fonts) {
  245. log.Fatal("Font path not exist.")
  246. }
  247. gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
  248. RegisterDataBase()
  249. RegisterCache()
  250. RegisterModel()
  251. RegisterLogger(conf.LogFile)
  252. ModifyPassword()
  253. }
  254. //注册缓存管道
  255. func RegisterCache() {
  256. isOpenCache := beego.AppConfig.DefaultBool("cache", false)
  257. if !isOpenCache {
  258. cache.Init(&cache.NullCache{})
  259. return
  260. }
  261. beego.Info("正常初始化缓存配置.")
  262. cacheProvider := beego.AppConfig.String("cache_provider")
  263. if cacheProvider == "file" {
  264. cacheFilePath := beego.AppConfig.DefaultString("cache_file_path", "./runtime/cache/")
  265. if strings.HasPrefix(cacheFilePath, "./") {
  266. cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:]))
  267. }
  268. fileCache := beegoCache.NewFileCache()
  269. fileConfig := make(map[string]string, 0)
  270. fileConfig["CachePath"] = cacheFilePath
  271. fileConfig["DirectoryLevel"] = beego.AppConfig.DefaultString("cache_file_dir_level", "2")
  272. fileConfig["EmbedExpiry"] = beego.AppConfig.DefaultString("cache_file_expiry", "120")
  273. fileConfig["FileSuffix"] = beego.AppConfig.DefaultString("cache_file_suffix", ".bin")
  274. bc, err := json.Marshal(&fileConfig)
  275. if err != nil {
  276. beego.Error("初始化file缓存失败:", err)
  277. os.Exit(1)
  278. }
  279. fileCache.StartAndGC(string(bc))
  280. cache.Init(fileCache)
  281. } else if cacheProvider == "memory" {
  282. cacheInterval := beego.AppConfig.DefaultInt("cache_memory_interval", 60)
  283. memory := beegoCache.NewMemoryCache()
  284. beegoCache.DefaultEvery = cacheInterval
  285. cache.Init(memory)
  286. } else if cacheProvider == "redis" {
  287. //设置Redis前缀
  288. if key := beego.AppConfig.DefaultString("cache_redis_prefix",""); key != "" {
  289. redis.DefaultKey = key
  290. }
  291. var redisConfig struct {
  292. Conn string `json:"conn"`
  293. Password string `json:"password"`
  294. DbNum int `json:"dbNum"`
  295. }
  296. redisConfig.DbNum = 0
  297. redisConfig.Conn = beego.AppConfig.DefaultString("cache_redis_host", "")
  298. if pwd := beego.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" {
  299. redisConfig.Password = pwd
  300. }
  301. if dbNum := beego.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 {
  302. redisConfig.DbNum = dbNum
  303. }
  304. bc, err := json.Marshal(&redisConfig)
  305. if err != nil {
  306. beego.Error("初始化Redis缓存失败:", err)
  307. os.Exit(1)
  308. }
  309. redisCache, err := beegoCache.NewCache("redis", string(bc))
  310. if err != nil {
  311. beego.Error("初始化Redis缓存失败:", err)
  312. os.Exit(1)
  313. }
  314. cache.Init(redisCache)
  315. } else if cacheProvider == "memcache" {
  316. var memcacheConfig struct {
  317. Conn string `json:"conn"`
  318. }
  319. memcacheConfig.Conn = beego.AppConfig.DefaultString("cache_memcache_host", "")
  320. bc, err := json.Marshal(&memcacheConfig)
  321. if err != nil {
  322. beego.Error("初始化 Memcache 缓存失败 ->", err)
  323. os.Exit(1)
  324. }
  325. memcache, err := beegoCache.NewCache("memcache", string(bc))
  326. if err != nil {
  327. beego.Error("初始化 Memcache 缓存失败 ->", err)
  328. os.Exit(1)
  329. }
  330. cache.Init(memcache)
  331. } else {
  332. cache.Init(&cache.NullCache{})
  333. beego.Warn("不支持的缓存管道,缓存将禁用 ->" ,cacheProvider)
  334. return
  335. }
  336. beego.Info("缓存初始化完成.")
  337. }
  338. //自动加载配置文件.修改了监听端口号和数据库配置无法自动生效.
  339. func RegisterAutoLoadConfig() {
  340. if conf.AutoLoadDelay > 0 {
  341. ticker := time.NewTicker(time.Second * time.Duration(conf.AutoLoadDelay))
  342. go func() {
  343. f,err := os.Stat(conf.ConfigurationFile)
  344. if err != nil {
  345. beego.Error("读取配置文件时出错 ->",err)
  346. return
  347. }
  348. modTime := f.ModTime()
  349. for {
  350. select {
  351. case <-ticker.C:
  352. f,err := os.Stat(conf.ConfigurationFile)
  353. if err != nil {
  354. beego.Error("读取配置文件时出错 ->",err)
  355. break
  356. }
  357. if modTime != f.ModTime() {
  358. if err := beego.LoadAppConfig("ini", conf.ConfigurationFile); err != nil {
  359. beego.Error("An error occurred ->", err)
  360. break
  361. }
  362. modTime = f.ModTime()
  363. RegisterCache()
  364. RegisterLogger("")
  365. beego.Info("配置文件已加载")
  366. }
  367. }
  368. }
  369. }()
  370. }
  371. }
  372. func init() {
  373. if configPath, err := filepath.Abs(conf.ConfigurationFile); err == nil {
  374. conf.ConfigurationFile = configPath
  375. }
  376. gocaptcha.ReadFonts(conf.WorkingDir("static","fonts"), ".ttf")
  377. gob.Register(models.Member{})
  378. if p, err := filepath.Abs(os.Args[0]); err == nil {
  379. conf.WorkingDirectory = filepath.Dir(p)
  380. }
  381. }