command.go 12 KB

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