setting.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // Copyright 2014 Unknwon
  2. // Copyright 2014 Torkel Ödegaard
  3. package setting
  4. import (
  5. "fmt"
  6. "net/url"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/macaron-contrib/session"
  14. "gopkg.in/ini.v1"
  15. "github.com/grafana/grafana/pkg/log"
  16. )
  17. type Scheme string
  18. const (
  19. HTTP Scheme = "http"
  20. HTTPS Scheme = "https"
  21. )
  22. const (
  23. DEV string = "development"
  24. PROD string = "production"
  25. TEST string = "test"
  26. )
  27. var (
  28. // App settings.
  29. Env string = DEV
  30. AppName string
  31. AppUrl string
  32. AppSubUrl string
  33. // build
  34. BuildVersion string
  35. BuildCommit string
  36. BuildStamp int64
  37. // Log settings.
  38. LogRootPath string
  39. LogModes []string
  40. LogConfigs []string
  41. // Http server options
  42. Protocol Scheme
  43. Domain string
  44. HttpAddr, HttpPort string
  45. SshPort int
  46. CertFile, KeyFile string
  47. RouterLogging bool
  48. StaticRootPath string
  49. EnableGzip bool
  50. // Security settings.
  51. SecretKey string
  52. LogInRememberDays int
  53. CookieUserName string
  54. CookieRememberName string
  55. // User settings
  56. AllowUserSignUp bool
  57. AllowUserOrgCreate bool
  58. AutoAssignOrg bool
  59. AutoAssignOrgRole string
  60. // Http auth
  61. AdminUser string
  62. AdminPassword string
  63. AnonymousEnabled bool
  64. AnonymousOrgName string
  65. AnonymousOrgRole string
  66. // Session settings.
  67. SessionOptions session.Options
  68. // Global setting objects.
  69. WorkDir string
  70. Cfg *ini.File
  71. ConfRootPath string
  72. CustomPath string // Custom directory path.
  73. ProdMode bool
  74. RunUser string
  75. IsWindows bool
  76. // PhantomJs Rendering
  77. ImagesDir string
  78. PhantomDir string
  79. configFiles []string
  80. ReportingEnabled bool
  81. GoogleAnalyticsId string
  82. )
  83. func init() {
  84. IsWindows = runtime.GOOS == "windows"
  85. log.NewLogger(0, "console", `{"level": 0}`)
  86. WorkDir, _ = filepath.Abs(".")
  87. }
  88. func findConfigFiles(customConfigFile string) {
  89. ConfRootPath = path.Join(WorkDir, "conf")
  90. configFiles = make([]string, 0)
  91. configFile := path.Join(ConfRootPath, "defaults.ini")
  92. if com.IsFile(configFile) {
  93. configFiles = append(configFiles, configFile)
  94. }
  95. configFile = path.Join(ConfRootPath, "dev.ini")
  96. if com.IsFile(configFile) {
  97. configFiles = append(configFiles, configFile)
  98. }
  99. configFile = path.Join(ConfRootPath, "custom.ini")
  100. if com.IsFile(configFile) {
  101. configFiles = append(configFiles, configFile)
  102. }
  103. if customConfigFile != "" {
  104. configFiles = append(configFiles, customConfigFile)
  105. }
  106. if len(configFiles) == 0 {
  107. log.Fatal(3, "Could not find any config file")
  108. }
  109. }
  110. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  111. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  112. if appUrl[len(appUrl)-1] != '/' {
  113. appUrl += "/"
  114. }
  115. // Check if has app suburl.
  116. url, err := url.Parse(appUrl)
  117. if err != nil {
  118. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  119. }
  120. appSubUrl := strings.TrimSuffix(url.Path, "/")
  121. return appUrl, appSubUrl
  122. }
  123. func ToAbsUrl(relativeUrl string) string {
  124. return AppUrl + relativeUrl
  125. }
  126. func loadEnvVariableOverrides() {
  127. for _, section := range Cfg.Sections() {
  128. for _, key := range section.Keys() {
  129. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  130. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  131. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  132. envValue := os.Getenv(envKey)
  133. if len(envValue) > 0 {
  134. log.Info("Setting: ENV override found: %s", envKey)
  135. key.SetValue(envValue)
  136. }
  137. }
  138. }
  139. }
  140. func NewConfigContext(config string) {
  141. findConfigFiles(config)
  142. var err error
  143. for i, file := range configFiles {
  144. if i == 0 {
  145. Cfg, err = ini.Load(configFiles[i])
  146. Cfg.BlockMode = false
  147. } else {
  148. err = Cfg.Append(configFiles[i])
  149. }
  150. if err != nil {
  151. log.Fatal(4, "Fail to parse config file: %v, error: %v", file, err)
  152. }
  153. }
  154. loadEnvVariableOverrides()
  155. initLogging()
  156. AppName = Cfg.Section("").Key("app_name").MustString("Grafana")
  157. Env = Cfg.Section("").Key("app_mode").MustString("development")
  158. server := Cfg.Section("server")
  159. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  160. Protocol = HTTP
  161. if server.Key("protocol").MustString("http") == "https" {
  162. Protocol = HTTPS
  163. CertFile = server.Key("cert_file").String()
  164. KeyFile = server.Key("cert_key").String()
  165. }
  166. Domain = server.Key("domain").MustString("localhost")
  167. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  168. HttpPort = server.Key("http_port").MustString("3000")
  169. StaticRootPath = server.Key("static_root_path").MustString(path.Join(WorkDir, "webapp"))
  170. RouterLogging = server.Key("router_logging").MustBool(false)
  171. EnableGzip = server.Key("enable_gzip").MustBool(false)
  172. security := Cfg.Section("security")
  173. SecretKey = security.Key("secret_key").String()
  174. LogInRememberDays = security.Key("login_remember_days").MustInt()
  175. CookieUserName = security.Key("cookie_username").String()
  176. CookieRememberName = security.Key("cookie_remember_name").String()
  177. // admin
  178. AdminUser = security.Key("admin_user").String()
  179. AdminPassword = security.Key("admin_password").String()
  180. users := Cfg.Section("users")
  181. AllowUserSignUp = users.Key("allow_sign_up").MustBool(true)
  182. AllowUserOrgCreate = users.Key("allow_org_create").MustBool(true)
  183. AutoAssignOrg = users.Key("auto_assign_org").MustBool(true)
  184. AutoAssignOrgRole = users.Key("auto_assign_org_role").In("Editor", []string{"Editor", "Admin", "Viewer"})
  185. // anonymous access
  186. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  187. AnonymousOrgName = Cfg.Section("auth.anonymous").Key("org_name").String()
  188. AnonymousOrgRole = Cfg.Section("auth.anonymous").Key("org_role").String()
  189. // PhantomJS rendering
  190. ImagesDir = "data/png"
  191. PhantomDir = "vendor/phantomjs"
  192. analytics := Cfg.Section("analytics")
  193. ReportingEnabled = analytics.Key("reporting_enabled").MustBool(true)
  194. GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
  195. readSessionConfig()
  196. }
  197. func readSessionConfig() {
  198. sec := Cfg.Section("session")
  199. SessionOptions = session.Options{}
  200. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres"})
  201. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  202. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  203. SessionOptions.CookiePath = AppSubUrl
  204. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  205. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  206. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  207. SessionOptions.IDLength = 16
  208. if SessionOptions.Provider == "file" {
  209. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  210. }
  211. if SessionOptions.CookiePath == "" {
  212. SessionOptions.CookiePath = "/"
  213. }
  214. }
  215. var logLevels = map[string]string{
  216. "Trace": "0",
  217. "Debug": "1",
  218. "Info": "2",
  219. "Warn": "3",
  220. "Error": "4",
  221. "Critical": "5",
  222. }
  223. func initLogging() {
  224. // Get and check log mode.
  225. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",")
  226. LogRootPath = Cfg.Section("log").Key("root_path").MustString(path.Join(WorkDir, "/data/log"))
  227. LogConfigs = make([]string, len(LogModes))
  228. for i, mode := range LogModes {
  229. mode = strings.TrimSpace(mode)
  230. sec, err := Cfg.GetSection("log." + mode)
  231. if err != nil {
  232. log.Fatal(4, "Unknown log mode: %s", mode)
  233. }
  234. // Log level.
  235. levelName := Cfg.Section("log."+mode).Key("level").In("Trace",
  236. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  237. level, ok := logLevels[levelName]
  238. if !ok {
  239. log.Fatal(4, "Unknown log level: %s", levelName)
  240. }
  241. // Generate log configuration.
  242. switch mode {
  243. case "console":
  244. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  245. case "file":
  246. logPath := sec.Key("file_name").MustString(path.Join(LogRootPath, "grafana.log"))
  247. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  248. LogConfigs[i] = fmt.Sprintf(
  249. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  250. logPath,
  251. sec.Key("log_rotate").MustBool(true),
  252. sec.Key("max_lines").MustInt(1000000),
  253. 1<<uint(sec.Key("max_size_shift").MustInt(28)),
  254. sec.Key("daily_rotate").MustBool(true),
  255. sec.Key("max_days").MustInt(7))
  256. case "conn":
  257. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  258. sec.Key("reconnect_on_msg").MustBool(),
  259. sec.Key("reconnect").MustBool(),
  260. sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}),
  261. sec.Key("addr").MustString(":7020"))
  262. case "smtp":
  263. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  264. sec.Key("user").MustString("example@example.com"),
  265. sec.Key("passwd").MustString("******"),
  266. sec.Key("host").MustString("127.0.0.1:25"),
  267. sec.Key("receivers").MustString("[]"),
  268. sec.Key("subject").MustString("Diagnostic message from serve"))
  269. case "database":
  270. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  271. sec.Key("driver").String(),
  272. sec.Key("conn").String())
  273. }
  274. log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, LogConfigs[i])
  275. }
  276. }
  277. func LogLoadedConfigFiles() {
  278. for _, file := range configFiles {
  279. log.Info("Config: Loaded from %s", file)
  280. }
  281. }