You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

314 lines
8.8 KiB

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