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