command.go 12 KB

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