setting.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. "net/url"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. _ "github.com/go-macaron/cache/memcache"
  17. _ "github.com/go-macaron/cache/redis"
  18. "github.com/go-macaron/session"
  19. _ "github.com/go-macaron/session/redis"
  20. "gopkg.in/ini.v1"
  21. "github.com/gogits/gogs/modules/bindata"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/user"
  24. )
  25. type Scheme string
  26. const (
  27. HTTP Scheme = "http"
  28. HTTPS Scheme = "https"
  29. FCGI Scheme = "fcgi"
  30. )
  31. type LandingPage string
  32. const (
  33. LANDING_PAGE_HOME LandingPage = "/"
  34. LANDING_PAGE_EXPLORE LandingPage = "/explore"
  35. )
  36. var (
  37. // Build information
  38. BuildTime string
  39. BuildGitHash string
  40. // App settings
  41. AppVer string
  42. AppName string
  43. AppUrl string
  44. AppSubUrl string
  45. AppSubUrlDepth int // Number of slashes
  46. AppPath string
  47. AppDataPath = "data"
  48. // Server settings
  49. Protocol Scheme
  50. Domain string
  51. HttpAddr, HttpPort string
  52. LocalURL string
  53. OfflineMode bool
  54. DisableRouterLog bool
  55. CertFile, KeyFile string
  56. StaticRootPath string
  57. EnableGzip bool
  58. LandingPageUrl LandingPage
  59. SSH struct {
  60. Disabled bool `ini:"DISABLE_SSH"`
  61. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  62. Domain string `ini:"SSH_DOMAIN"`
  63. Port int `ini:"SSH_PORT"`
  64. ListenPort int `ini:"SSH_LISTEN_PORT"`
  65. RootPath string `ini:"SSH_ROOT_PATH"`
  66. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  67. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  68. MinimumKeySizeCheck bool `ini:"-"`
  69. MinimumKeySizes map[string]int `ini:"-"`
  70. }
  71. // Security settings
  72. InstallLock bool
  73. SecretKey string
  74. LogInRememberDays int
  75. CookieUserName string
  76. CookieRememberName string
  77. ReverseProxyAuthUser string
  78. // Database settings
  79. UseSQLite3 bool
  80. UseMySQL bool
  81. UsePostgreSQL bool
  82. UseTiDB bool
  83. // Webhook settings
  84. Webhook struct {
  85. QueueLength int
  86. DeliverTimeout int
  87. SkipTLSVerify bool
  88. Types []string
  89. PagingNum int
  90. }
  91. // Repository settings
  92. Repository struct {
  93. AnsiCharset string
  94. ForcePrivate bool
  95. MaxCreationLimit int
  96. PullRequestQueueLength int
  97. }
  98. RepoRootPath string
  99. ScriptType string
  100. // UI settings
  101. ExplorePagingNum int
  102. IssuePagingNum int
  103. FeedMaxCommitNum int
  104. AdminUserPagingNum int
  105. AdminRepoPagingNum int
  106. AdminNoticePagingNum int
  107. AdminOrgPagingNum int
  108. ThemeColorMetaTag string
  109. // Markdown sttings
  110. Markdown struct {
  111. EnableHardLineBreak bool
  112. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  113. }
  114. // Picture settings
  115. PictureService string
  116. AvatarUploadPath string
  117. GravatarSource string
  118. DisableGravatar bool
  119. // Log settings
  120. LogRootPath string
  121. LogModes []string
  122. LogConfigs []string
  123. // Attachment settings
  124. AttachmentPath string
  125. AttachmentAllowedTypes string
  126. AttachmentMaxSize int64
  127. AttachmentMaxFiles int
  128. AttachmentEnabled bool
  129. // Time settings
  130. TimeFormat string
  131. // Cache settings
  132. CacheAdapter string
  133. CacheInternal int
  134. CacheConn string
  135. // Session settings
  136. SessionConfig session.Options
  137. // Git settings
  138. Git struct {
  139. MaxGitDiffLines int
  140. GcArgs []string `delim:" "`
  141. Timeout struct {
  142. Migrate int
  143. Mirror int
  144. Clone int
  145. Pull int
  146. } `ini:"git.timeout"`
  147. }
  148. // Cron tasks
  149. Cron struct {
  150. UpdateMirror struct {
  151. Enabled bool
  152. RunAtStart bool
  153. Schedule string
  154. } `ini:"cron.update_mirrors"`
  155. RepoHealthCheck struct {
  156. Enabled bool
  157. RunAtStart bool
  158. Schedule string
  159. Timeout time.Duration
  160. Args []string `delim:" "`
  161. } `ini:"cron.repo_health_check"`
  162. CheckRepoStats struct {
  163. Enabled bool
  164. RunAtStart bool
  165. Schedule string
  166. } `ini:"cron.check_repo_stats"`
  167. }
  168. // I18n settings
  169. Langs, Names []string
  170. dateLangs map[string]string
  171. // Highlight settings are loaded in modules/template/hightlight.go
  172. // Other settings
  173. ShowFooterBranding bool
  174. ShowFooterVersion bool
  175. SupportMiniWinService bool
  176. // Global setting objects
  177. Cfg *ini.File
  178. CustomPath string // Custom directory path
  179. CustomConf string
  180. ProdMode bool
  181. RunUser string
  182. IsWindows bool
  183. HasRobotsTxt bool
  184. )
  185. func DateLang(lang string) string {
  186. name, ok := dateLangs[lang]
  187. if ok {
  188. return name
  189. }
  190. return "en"
  191. }
  192. // execPath returns the executable path.
  193. func execPath() (string, error) {
  194. file, err := exec.LookPath(os.Args[0])
  195. if err != nil {
  196. return "", err
  197. }
  198. return filepath.Abs(file)
  199. }
  200. func init() {
  201. IsWindows = runtime.GOOS == "windows"
  202. log.NewLogger(0, "console", `{"level": 0}`)
  203. var err error
  204. if AppPath, err = execPath(); err != nil {
  205. log.Fatal(4, "fail to get app path: %v\n", err)
  206. }
  207. // Note: we don't use path.Dir here because it does not handle case
  208. // which path starts with two "/" in Windows: "//psf/Home/..."
  209. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  210. }
  211. // WorkDir returns absolute path of work directory.
  212. func WorkDir() (string, error) {
  213. wd := os.Getenv("GOGS_WORK_DIR")
  214. if len(wd) > 0 {
  215. return wd, nil
  216. }
  217. i := strings.LastIndex(AppPath, "/")
  218. if i == -1 {
  219. return AppPath, nil
  220. }
  221. return AppPath[:i], nil
  222. }
  223. func forcePathSeparator(path string) {
  224. if strings.Contains(path, "\\") {
  225. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  226. }
  227. }
  228. // NewContext initializes configuration context.
  229. // NOTE: do not print any log except error.
  230. func NewContext() {
  231. workDir, err := WorkDir()
  232. if err != nil {
  233. log.Fatal(4, "Fail to get work directory: %v", err)
  234. }
  235. Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
  236. if err != nil {
  237. log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
  238. }
  239. CustomPath = os.Getenv("GOGS_CUSTOM")
  240. if len(CustomPath) == 0 {
  241. CustomPath = workDir + "/custom"
  242. }
  243. if len(CustomConf) == 0 {
  244. CustomConf = CustomPath + "/conf/app.ini"
  245. }
  246. if com.IsFile(CustomConf) {
  247. if err = Cfg.Append(CustomConf); err != nil {
  248. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  249. }
  250. } else {
  251. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  252. }
  253. Cfg.NameMapper = ini.AllCapsUnderscore
  254. homeDir, err := com.HomeDir()
  255. if err != nil {
  256. log.Fatal(4, "Fail to get home directory: %v", err)
  257. }
  258. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  259. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  260. forcePathSeparator(LogRootPath)
  261. sec := Cfg.Section("server")
  262. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
  263. AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  264. if AppUrl[len(AppUrl)-1] != '/' {
  265. AppUrl += "/"
  266. }
  267. // Check if has app suburl.
  268. url, err := url.Parse(AppUrl)
  269. if err != nil {
  270. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppUrl, err)
  271. }
  272. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  273. AppSubUrl = strings.TrimSuffix(url.Path, "/")
  274. AppSubUrlDepth = strings.Count(AppSubUrl, "/")
  275. Protocol = HTTP
  276. if sec.Key("PROTOCOL").String() == "https" {
  277. Protocol = HTTPS
  278. CertFile = sec.Key("CERT_FILE").String()
  279. KeyFile = sec.Key("KEY_FILE").String()
  280. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  281. Protocol = FCGI
  282. }
  283. Domain = sec.Key("DOMAIN").MustString("localhost")
  284. HttpAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  285. HttpPort = sec.Key("HTTP_PORT").MustString("3000")
  286. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString("http://localhost:" + HttpPort + "/")
  287. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  288. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  289. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  290. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  291. switch sec.Key("LANDING_PAGE").MustString("home") {
  292. case "explore":
  293. LandingPageUrl = LANDING_PAGE_EXPLORE
  294. default:
  295. LandingPageUrl = LANDING_PAGE_HOME
  296. }
  297. SSH.RootPath = path.Join(homeDir, ".ssh")
  298. SSH.KeyTestPath = os.TempDir()
  299. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  300. log.Fatal(4, "Fail to map SSH settings: %v", err)
  301. }
  302. // When disable SSH, start builtin server value is ignored.
  303. if SSH.Disabled {
  304. SSH.StartBuiltinServer = false
  305. }
  306. if !SSH.Disabled && !SSH.StartBuiltinServer {
  307. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  308. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  309. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  310. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  311. }
  312. if !filepath.IsAbs(SSH.KeygenPath) {
  313. if _, err := exec.LookPath(SSH.KeygenPath); err != nil {
  314. log.Fatal(4, "Fail to test '%s' command: %v (forgotten install?)", SSH.KeygenPath, err)
  315. }
  316. }
  317. }
  318. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  319. SSH.MinimumKeySizes = map[string]int{}
  320. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  321. for _, key := range minimumKeySizes {
  322. if key.MustInt() != -1 {
  323. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  324. }
  325. }
  326. sec = Cfg.Section("security")
  327. InstallLock = sec.Key("INSTALL_LOCK").MustBool()
  328. SecretKey = sec.Key("SECRET_KEY").String()
  329. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
  330. CookieUserName = sec.Key("COOKIE_USERNAME").String()
  331. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
  332. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  333. sec = Cfg.Section("attachment")
  334. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  335. if !filepath.IsAbs(AttachmentPath) {
  336. AttachmentPath = path.Join(workDir, AttachmentPath)
  337. }
  338. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  339. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  340. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  341. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  342. TimeFormat = map[string]string{
  343. "ANSIC": time.ANSIC,
  344. "UnixDate": time.UnixDate,
  345. "RubyDate": time.RubyDate,
  346. "RFC822": time.RFC822,
  347. "RFC822Z": time.RFC822Z,
  348. "RFC850": time.RFC850,
  349. "RFC1123": time.RFC1123,
  350. "RFC1123Z": time.RFC1123Z,
  351. "RFC3339": time.RFC3339,
  352. "RFC3339Nano": time.RFC3339Nano,
  353. "Kitchen": time.Kitchen,
  354. "Stamp": time.Stamp,
  355. "StampMilli": time.StampMilli,
  356. "StampMicro": time.StampMicro,
  357. "StampNano": time.StampNano,
  358. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  359. RunUser = Cfg.Section("").Key("RUN_USER").String()
  360. curUser := user.CurrentUsername()
  361. // Does not check run user when the install lock is off.
  362. if InstallLock && RunUser != curUser {
  363. log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
  364. }
  365. // Determine and create root git repository path.
  366. sec = Cfg.Section("repository")
  367. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
  368. forcePathSeparator(RepoRootPath)
  369. if !filepath.IsAbs(RepoRootPath) {
  370. RepoRootPath = path.Join(workDir, RepoRootPath)
  371. } else {
  372. RepoRootPath = path.Clean(RepoRootPath)
  373. }
  374. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  375. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  376. log.Fatal(4, "Fail to map Repository settings: %v", err)
  377. }
  378. // UI settings.
  379. sec = Cfg.Section("ui")
  380. ExplorePagingNum = sec.Key("EXPLORE_PAGING_NUM").MustInt(20)
  381. IssuePagingNum = sec.Key("ISSUE_PAGING_NUM").MustInt(10)
  382. FeedMaxCommitNum = sec.Key("FEED_MAX_COMMIT_NUM").MustInt(5)
  383. sec = Cfg.Section("ui.admin")
  384. AdminUserPagingNum = sec.Key("USER_PAGING_NUM").MustInt(50)
  385. AdminRepoPagingNum = sec.Key("REPO_PAGING_NUM").MustInt(50)
  386. AdminNoticePagingNum = sec.Key("NOTICE_PAGING_NUM").MustInt(50)
  387. AdminOrgPagingNum = sec.Key("ORG_PAGING_NUM").MustInt(50)
  388. ThemeColorMetaTag = sec.Key("THEME_COLOR_META_TAG").MustString("#ff5343")
  389. sec = Cfg.Section("picture")
  390. PictureService = sec.Key("SERVICE").In("server", []string{"server"})
  391. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  392. forcePathSeparator(AvatarUploadPath)
  393. if !filepath.IsAbs(AvatarUploadPath) {
  394. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  395. }
  396. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  397. case "duoshuo":
  398. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  399. case "gravatar":
  400. GravatarSource = "https://secure.gravatar.com/avatar/"
  401. default:
  402. GravatarSource = source
  403. }
  404. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  405. if OfflineMode {
  406. DisableGravatar = true
  407. }
  408. if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  409. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  410. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  411. log.Fatal(4, "Fail to map Git settings: %v", err)
  412. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  413. log.Fatal(4, "Fail to map Cron settings: %v", err)
  414. }
  415. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  416. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  417. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  418. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
  419. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
  420. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  421. }
  422. var Service struct {
  423. ActiveCodeLives int
  424. ResetPwdCodeLives int
  425. RegisterEmailConfirm bool
  426. DisableRegistration bool
  427. ShowRegistrationButton bool
  428. RequireSignInView bool
  429. EnableNotifyMail bool
  430. EnableReverseProxyAuth bool
  431. EnableReverseProxyAutoRegister bool
  432. EnableCaptcha bool
  433. }
  434. func newService() {
  435. sec := Cfg.Section("service")
  436. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  437. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  438. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  439. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  440. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  441. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  442. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  443. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  444. }
  445. var logLevels = map[string]string{
  446. "Trace": "0",
  447. "Debug": "1",
  448. "Info": "2",
  449. "Warn": "3",
  450. "Error": "4",
  451. "Critical": "5",
  452. }
  453. func newLogService() {
  454. log.Info("%s %s", AppName, AppVer)
  455. if len(BuildTime) > 0 {
  456. log.Info("Build Time: %s", BuildTime)
  457. log.Info("Build Git Hash: %s", BuildGitHash)
  458. }
  459. // Get and check log mode.
  460. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  461. LogConfigs = make([]string, len(LogModes))
  462. for i, mode := range LogModes {
  463. mode = strings.TrimSpace(mode)
  464. sec, err := Cfg.GetSection("log." + mode)
  465. if err != nil {
  466. log.Fatal(4, "Unknown log mode: %s", mode)
  467. }
  468. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  469. // Log level.
  470. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  471. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  472. validLevels)
  473. level, ok := logLevels[levelName]
  474. if !ok {
  475. log.Fatal(4, "Unknown log level: %s", levelName)
  476. }
  477. // Generate log configuration.
  478. switch mode {
  479. case "console":
  480. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  481. case "file":
  482. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  483. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  484. panic(err.Error())
  485. }
  486. LogConfigs[i] = fmt.Sprintf(
  487. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  488. logPath,
  489. sec.Key("LOG_ROTATE").MustBool(true),
  490. sec.Key("MAX_LINES").MustInt(1000000),
  491. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  492. sec.Key("DAILY_ROTATE").MustBool(true),
  493. sec.Key("MAX_DAYS").MustInt(7))
  494. case "conn":
  495. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  496. sec.Key("RECONNECT_ON_MSG").MustBool(),
  497. sec.Key("RECONNECT").MustBool(),
  498. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  499. sec.Key("ADDR").MustString(":7020"))
  500. case "smtp":
  501. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  502. sec.Key("USER").MustString("[email protected]"),
  503. sec.Key("PASSWD").MustString("******"),
  504. sec.Key("HOST").MustString("127.0.0.1:25"),
  505. sec.Key("RECEIVERS").MustString("[]"),
  506. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  507. case "database":
  508. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  509. sec.Key("DRIVER").String(),
  510. sec.Key("CONN").String())
  511. }
  512. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  513. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  514. }
  515. }
  516. func newCacheService() {
  517. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  518. switch CacheAdapter {
  519. case "memory":
  520. CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  521. case "redis", "memcache":
  522. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  523. default:
  524. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  525. }
  526. log.Info("Cache Service Enabled")
  527. }
  528. func newSessionService() {
  529. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  530. []string{"memory", "file", "redis", "mysql"})
  531. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  532. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
  533. SessionConfig.CookiePath = AppSubUrl
  534. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
  535. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  536. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  537. log.Info("Session Service Enabled")
  538. }
  539. // Mailer represents mail service.
  540. type Mailer struct {
  541. QueueLength int
  542. Name string
  543. Host string
  544. From string
  545. User, Passwd string
  546. DisableHelo bool
  547. HeloHostname string
  548. SkipVerify bool
  549. UseCertificate bool
  550. CertFile, KeyFile string
  551. }
  552. var (
  553. MailService *Mailer
  554. )
  555. func newMailService() {
  556. sec := Cfg.Section("mailer")
  557. // Check mailer setting.
  558. if !sec.Key("ENABLED").MustBool() {
  559. return
  560. }
  561. MailService = &Mailer{
  562. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  563. Name: sec.Key("NAME").MustString(AppName),
  564. Host: sec.Key("HOST").String(),
  565. User: sec.Key("USER").String(),
  566. Passwd: sec.Key("PASSWD").String(),
  567. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  568. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  569. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  570. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  571. CertFile: sec.Key("CERT_FILE").String(),
  572. KeyFile: sec.Key("KEY_FILE").String(),
  573. }
  574. MailService.From = sec.Key("FROM").MustString(MailService.User)
  575. log.Info("Mail Service Enabled")
  576. }
  577. func newRegisterMailService() {
  578. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  579. return
  580. } else if MailService == nil {
  581. log.Warn("Register Mail Service: Mail Service is not enabled")
  582. return
  583. }
  584. Service.RegisterEmailConfirm = true
  585. log.Info("Register Mail Service Enabled")
  586. }
  587. func newNotifyMailService() {
  588. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  589. return
  590. } else if MailService == nil {
  591. log.Warn("Notify Mail Service: Mail Service is not enabled")
  592. return
  593. }
  594. Service.EnableNotifyMail = true
  595. log.Info("Notify Mail Service Enabled")
  596. }
  597. func newWebhookService() {
  598. sec := Cfg.Section("webhook")
  599. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  600. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  601. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  602. Webhook.Types = []string{"gogs", "slack"}
  603. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  604. }
  605. func NewServices() {
  606. newService()
  607. newLogService()
  608. newCacheService()
  609. newSessionService()
  610. newMailService()
  611. newRegisterMailService()
  612. newNotifyMailService()
  613. newWebhookService()
  614. }