setting.go 21 KB

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