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.

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