command.go 12 KB

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