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

setting.go 12 kB

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