setting.go 19 KB

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