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.

setting.go 20KB

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