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.

663 lines
19 KiB

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