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.

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