setting.go 21 KB

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