setting.go 20 KB

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