command.go 13 KB

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