conf.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package base
  5. import (
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/Unknwon/goconfig"
  14. "github.com/gogits/cache"
  15. "github.com/gogits/session"
  16. "github.com/gogits/gogs/modules/log"
  17. )
  18. // Mailer represents a mail service.
  19. type Mailer struct {
  20. Name string
  21. Host string
  22. User, Passwd string
  23. }
  24. var (
  25. AppVer string
  26. AppName string
  27. AppLogo string
  28. AppUrl string
  29. Domain string
  30. SecretKey string
  31. RunUser string
  32. RepoRootPath string
  33. InstallLock bool
  34. EnableHttpsClone bool
  35. LogInRememberDays int
  36. CookieUserName string
  37. CookieRememberName string
  38. Cfg *goconfig.ConfigFile
  39. MailService *Mailer
  40. LogMode string
  41. LogConfig string
  42. Cache cache.Cache
  43. CacheAdapter string
  44. CacheConfig string
  45. SessionProvider string
  46. SessionConfig *session.Config
  47. SessionManager *session.Manager
  48. PictureService string
  49. )
  50. var Service struct {
  51. RegisterEmailConfirm bool
  52. DisenableRegisteration bool
  53. RequireSignInView bool
  54. EnableCacheAvatar bool
  55. NotifyMail bool
  56. ActiveCodeLives int
  57. ResetPwdCodeLives int
  58. }
  59. func ExecDir() (string, error) {
  60. file, err := exec.LookPath(os.Args[0])
  61. if err != nil {
  62. return "", err
  63. }
  64. p, err := filepath.Abs(file)
  65. if err != nil {
  66. return "", err
  67. }
  68. return path.Dir(strings.Replace(p, "\\", "/", -1)), nil
  69. }
  70. var logLevels = map[string]string{
  71. "Trace": "0",
  72. "Debug": "1",
  73. "Info": "2",
  74. "Warn": "3",
  75. "Error": "4",
  76. "Critical": "5",
  77. }
  78. func newService() {
  79. Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180)
  80. Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180)
  81. Service.DisenableRegisteration = Cfg.MustBool("service", "DISENABLE_REGISTERATION", false)
  82. Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW", false)
  83. Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR", false)
  84. }
  85. func newLogService() {
  86. // Get and check log mode.
  87. LogMode = Cfg.MustValue("log", "MODE", "console")
  88. modeSec := "log." + LogMode
  89. if _, err := Cfg.GetSection(modeSec); err != nil {
  90. fmt.Printf("Unknown log mode: %s\n", LogMode)
  91. os.Exit(2)
  92. }
  93. // Log level.
  94. levelName := Cfg.MustValue("log."+LogMode, "LEVEL", "Trace")
  95. level, ok := logLevels[levelName]
  96. if !ok {
  97. fmt.Printf("Unknown log level: %s\n", levelName)
  98. os.Exit(2)
  99. }
  100. // Generate log configuration.
  101. switch LogMode {
  102. case "console":
  103. LogConfig = fmt.Sprintf(`{"level":%s}`, level)
  104. case "file":
  105. logPath := Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log")
  106. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  107. LogConfig = fmt.Sprintf(
  108. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  109. logPath,
  110. Cfg.MustBool(modeSec, "LOG_ROTATE", true),
  111. Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
  112. 1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
  113. Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
  114. Cfg.MustInt(modeSec, "MAX_DAYS", 7))
  115. case "conn":
  116. LogConfig = fmt.Sprintf(`{"level":"%s","reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  117. Cfg.MustBool(modeSec, "RECONNECT_ON_MSG", false),
  118. Cfg.MustBool(modeSec, "RECONNECT", false),
  119. Cfg.MustValue(modeSec, "PROTOCOL", "tcp"),
  120. Cfg.MustValue(modeSec, "ADDR", ":7020"))
  121. case "smtp":
  122. LogConfig = fmt.Sprintf(`{"level":"%s","username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  123. Cfg.MustValue(modeSec, "USER", "example@example.com"),
  124. Cfg.MustValue(modeSec, "PASSWD", "******"),
  125. Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
  126. Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
  127. Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
  128. case "database":
  129. LogConfig = fmt.Sprintf(`{"level":"%s","driver":"%s","conn":"%s"}`, level,
  130. Cfg.MustValue(modeSec, "Driver"),
  131. Cfg.MustValue(modeSec, "CONN"))
  132. }
  133. log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), LogMode, LogConfig)
  134. log.Info("Log Mode: %s(%s)", strings.Title(LogMode), levelName)
  135. }
  136. func newCacheService() {
  137. CacheAdapter = Cfg.MustValue("cache", "ADAPTER", "memory")
  138. switch CacheAdapter {
  139. case "memory":
  140. CacheConfig = fmt.Sprintf(`{"interval":%d}`, Cfg.MustInt("cache", "INTERVAL", 60))
  141. case "redis", "memcache":
  142. CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
  143. default:
  144. fmt.Printf("Unknown cache adapter: %s\n", CacheAdapter)
  145. os.Exit(2)
  146. }
  147. var err error
  148. Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
  149. if err != nil {
  150. fmt.Printf("Init cache system failed, adapter: %s, config: %s, %v\n",
  151. CacheAdapter, CacheConfig, err)
  152. os.Exit(2)
  153. }
  154. log.Info("Cache Service Enabled")
  155. }
  156. func newSessionService() {
  157. SessionProvider = Cfg.MustValue("session", "PROVIDER", "memory")
  158. SessionConfig = new(session.Config)
  159. SessionConfig.ProviderConfig = Cfg.MustValue("session", "PROVIDER_CONFIG")
  160. SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits")
  161. SessionConfig.CookieSecure = Cfg.MustBool("session", "COOKIE_SECURE")
  162. SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
  163. SessionConfig.GcIntervalTime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
  164. SessionConfig.SessionLifeTime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
  165. SessionConfig.SessionIDHashFunc = Cfg.MustValue("session", "SESSION_ID_HASHFUNC", "sha1")
  166. SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY")
  167. if SessionProvider == "file" {
  168. os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
  169. }
  170. var err error
  171. SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
  172. if err != nil {
  173. fmt.Printf("Init session system failed, provider: %s, %v\n",
  174. SessionProvider, err)
  175. os.Exit(2)
  176. }
  177. log.Info("Session Service Enabled")
  178. }
  179. func newMailService() {
  180. // Check mailer setting.
  181. if Cfg.MustBool("mailer", "ENABLED") {
  182. MailService = &Mailer{
  183. Name: Cfg.MustValue("mailer", "NAME", AppName),
  184. Host: Cfg.MustValue("mailer", "HOST", "127.0.0.1:25"),
  185. User: Cfg.MustValue("mailer", "USER", "example@example.com"),
  186. Passwd: Cfg.MustValue("mailer", "PASSWD", "******"),
  187. }
  188. log.Info("Mail Service Enabled")
  189. }
  190. }
  191. func newRegisterMailService() {
  192. if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
  193. return
  194. } else if MailService == nil {
  195. log.Warn("Register Mail Service: Mail Service is not enabled")
  196. return
  197. }
  198. Service.RegisterEmailConfirm = true
  199. log.Info("Register Mail Service Enabled")
  200. }
  201. func newNotifyMailService() {
  202. if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") {
  203. return
  204. } else if MailService == nil {
  205. log.Warn("Notify Mail Service: Mail Service is not enabled")
  206. return
  207. }
  208. Service.NotifyMail = true
  209. log.Info("Notify Mail Service Enabled")
  210. }
  211. func NewConfigContext() {
  212. //var err error
  213. workDir, err := ExecDir()
  214. if err != nil {
  215. fmt.Printf("Fail to get work directory: %s\n", err)
  216. os.Exit(2)
  217. }
  218. cfgPath := filepath.Join(workDir, "conf/app.ini")
  219. Cfg, err = goconfig.LoadConfigFile(cfgPath)
  220. if err != nil {
  221. fmt.Printf("Cannot load config file '%s'\n", cfgPath)
  222. os.Exit(2)
  223. }
  224. Cfg.BlockMode = false
  225. cfgPath = filepath.Join(workDir, "custom/conf/app.ini")
  226. if com.IsFile(cfgPath) {
  227. if err = Cfg.AppendFiles(cfgPath); err != nil {
  228. fmt.Printf("Cannot load config file '%s'\n", cfgPath)
  229. os.Exit(2)
  230. }
  231. }
  232. AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
  233. AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
  234. AppUrl = Cfg.MustValue("server", "ROOT_URL")
  235. Domain = Cfg.MustValue("server", "DOMAIN")
  236. SecretKey = Cfg.MustValue("security", "SECRET_KEY")
  237. RunUser = Cfg.MustValue("", "RUN_USER")
  238. curUser := os.Getenv("USERNAME")
  239. if len(curUser) == 0 {
  240. curUser = os.Getenv("USER")
  241. }
  242. if RunUser != curUser {
  243. fmt.Printf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
  244. os.Exit(2)
  245. }
  246. InstallLock = Cfg.MustBool("security", "INSTALL_LOCK", false)
  247. EnableHttpsClone = Cfg.MustBool("security", "ENABLE_HTTPS_CLONE", false)
  248. LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
  249. CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
  250. CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")
  251. PictureService = Cfg.MustValue("picture", "SERVICE")
  252. // Determine and create root git reposiroty path.
  253. RepoRootPath = Cfg.MustValue("repository", "ROOT")
  254. if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
  255. fmt.Printf("models.init(fail to create RepoRootPath(%s)): %v\n", RepoRootPath, err)
  256. os.Exit(2)
  257. }
  258. }
  259. func NewServices() {
  260. newService()
  261. newLogService()
  262. newCacheService()
  263. newSessionService()
  264. newMailService()
  265. newRegisterMailService()
  266. newNotifyMailService()
  267. }