setting.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. // Copyright 2014 Unknwon
  2. // Copyright 2014 Torkel Ödegaard
  3. package setting
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "net/url"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "regexp"
  13. "runtime"
  14. "strings"
  15. "github.com/macaron-contrib/session"
  16. "gopkg.in/ini.v1"
  17. "github.com/grafana/grafana/pkg/log"
  18. "github.com/grafana/grafana/pkg/util"
  19. )
  20. type Scheme string
  21. const (
  22. HTTP Scheme = "http"
  23. HTTPS Scheme = "https"
  24. )
  25. const (
  26. DEV string = "development"
  27. PROD string = "production"
  28. TEST string = "test"
  29. )
  30. var (
  31. // App settings.
  32. Env string = DEV
  33. AppUrl string
  34. AppSubUrl string
  35. // build
  36. BuildVersion string
  37. BuildCommit string
  38. BuildStamp int64
  39. // Paths
  40. LogsPath string
  41. HomePath string
  42. DataPath string
  43. // Log settings.
  44. LogModes []string
  45. LogConfigs []util.DynMap
  46. // Http server options
  47. Protocol Scheme
  48. Domain string
  49. HttpAddr, HttpPort string
  50. SshPort int
  51. CertFile, KeyFile string
  52. RouterLogging bool
  53. StaticRootPath string
  54. EnableGzip bool
  55. EnforceDomain bool
  56. // Security settings.
  57. SecretKey string
  58. LogInRememberDays int
  59. CookieUserName string
  60. CookieRememberName string
  61. DisableGravatar bool
  62. EmailCodeValidMinutes int
  63. // User settings
  64. AllowUserSignUp bool
  65. AllowUserOrgCreate bool
  66. AutoAssignOrg bool
  67. AutoAssignOrgRole string
  68. // Http auth
  69. AdminUser string
  70. AdminPassword string
  71. AnonymousEnabled bool
  72. AnonymousOrgName string
  73. AnonymousOrgRole string
  74. // Auth proxy settings
  75. AuthProxyEnabled bool
  76. AuthProxyHeaderName string
  77. AuthProxyHeaderProperty string
  78. AuthProxyAutoSignUp bool
  79. // Session settings.
  80. SessionOptions session.Options
  81. // Global setting objects.
  82. Cfg *ini.File
  83. ConfRootPath string
  84. IsWindows bool
  85. // PhantomJs Rendering
  86. ImagesDir string
  87. PhantomDir string
  88. // for logging purposes
  89. configFiles []string
  90. appliedCommandLineProperties []string
  91. appliedEnvOverrides []string
  92. ReportingEnabled bool
  93. GoogleAnalyticsId string
  94. // SMTP email settings
  95. Smtp SmtpSettings
  96. )
  97. type CommandLineArgs struct {
  98. Config string
  99. HomePath string
  100. Args []string
  101. }
  102. func init() {
  103. IsWindows = runtime.GOOS == "windows"
  104. log.NewLogger(0, "console", `{"level": 0}`)
  105. }
  106. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  107. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  108. if appUrl[len(appUrl)-1] != '/' {
  109. appUrl += "/"
  110. }
  111. // Check if has app suburl.
  112. url, err := url.Parse(appUrl)
  113. if err != nil {
  114. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  115. }
  116. appSubUrl := strings.TrimSuffix(url.Path, "/")
  117. return appUrl, appSubUrl
  118. }
  119. func ToAbsUrl(relativeUrl string) string {
  120. return AppUrl + relativeUrl
  121. }
  122. func applyEnvVariableOverrides() {
  123. appliedEnvOverrides = make([]string, 0)
  124. for _, section := range Cfg.Sections() {
  125. for _, key := range section.Keys() {
  126. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  127. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  128. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  129. envValue := os.Getenv(envKey)
  130. if len(envValue) > 0 {
  131. key.SetValue(envValue)
  132. appliedEnvOverrides = append(appliedEnvOverrides, fmt.Sprintf("%s=%s", envKey, envValue))
  133. }
  134. }
  135. }
  136. }
  137. func applyCommandLineDefaultProperties(props map[string]string) {
  138. appliedCommandLineProperties = make([]string, 0)
  139. for _, section := range Cfg.Sections() {
  140. for _, key := range section.Keys() {
  141. keyString := fmt.Sprintf("default.%s.%s", section.Name(), key.Name())
  142. value, exists := props[keyString]
  143. if exists {
  144. key.SetValue(value)
  145. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  146. }
  147. }
  148. }
  149. }
  150. func applyCommandLineProperties(props map[string]string) {
  151. for _, section := range Cfg.Sections() {
  152. for _, key := range section.Keys() {
  153. keyString := fmt.Sprintf("%s.%s", section.Name(), key.Name())
  154. value, exists := props[keyString]
  155. if exists {
  156. key.SetValue(value)
  157. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  158. }
  159. }
  160. }
  161. }
  162. func getCommandLineProperties(args []string) map[string]string {
  163. props := make(map[string]string)
  164. for _, arg := range args {
  165. if !strings.HasPrefix(arg, "cfg:") {
  166. continue
  167. }
  168. trimmed := strings.TrimPrefix(arg, "cfg:")
  169. parts := strings.Split(trimmed, "=")
  170. if len(parts) != 2 {
  171. log.Fatal(3, "Invalid command line argument", arg)
  172. return nil
  173. }
  174. props[parts[0]] = parts[1]
  175. }
  176. return props
  177. }
  178. func makeAbsolute(path string, root string) string {
  179. if filepath.IsAbs(path) {
  180. return path
  181. }
  182. return filepath.Join(root, path)
  183. }
  184. func evalEnvVarExpression(value string) string {
  185. regex := regexp.MustCompile(`\${(\w+)}`)
  186. return regex.ReplaceAllStringFunc(value, func(envVar string) string {
  187. envVar = strings.TrimPrefix(envVar, "${")
  188. envVar = strings.TrimSuffix(envVar, "}")
  189. envValue := os.Getenv(envVar)
  190. return envValue
  191. })
  192. }
  193. func evalConfigValues() {
  194. for _, section := range Cfg.Sections() {
  195. for _, key := range section.Keys() {
  196. key.SetValue(evalEnvVarExpression(key.Value()))
  197. }
  198. }
  199. }
  200. func loadSpecifedConfigFile(configFile string) {
  201. if configFile == "" {
  202. configFile = filepath.Join(HomePath, "conf/custom.ini")
  203. // return without error if custom file does not exist
  204. if !pathExists(configFile) {
  205. return
  206. }
  207. }
  208. userConfig, err := ini.Load(configFile)
  209. userConfig.BlockMode = false
  210. if err != nil {
  211. log.Fatal(3, "Failed to parse %v, %v", configFile, err)
  212. }
  213. for _, section := range userConfig.Sections() {
  214. for _, key := range section.Keys() {
  215. if key.Value() == "" {
  216. continue
  217. }
  218. defaultSec, err := Cfg.GetSection(section.Name())
  219. if err != nil {
  220. log.Error(3, "Unknown config section %s defined in %s", section.Name(), configFile)
  221. continue
  222. }
  223. defaultKey, err := defaultSec.GetKey(key.Name())
  224. if err != nil {
  225. log.Error(3, "Unknown config key %s defined in section %s, in file", key.Name(), section.Name(), configFile)
  226. continue
  227. }
  228. defaultKey.SetValue(key.Value())
  229. }
  230. }
  231. configFiles = append(configFiles, configFile)
  232. }
  233. func loadConfiguration(args *CommandLineArgs) {
  234. var err error
  235. // load config defaults
  236. defaultConfigFile := path.Join(HomePath, "conf/defaults.ini")
  237. configFiles = append(configFiles, defaultConfigFile)
  238. Cfg, err = ini.Load(defaultConfigFile)
  239. Cfg.BlockMode = false
  240. if err != nil {
  241. log.Fatal(3, "Failed to parse defaults.ini, %v", err)
  242. }
  243. // command line props
  244. commandLineProps := getCommandLineProperties(args.Args)
  245. // load default overrides
  246. applyCommandLineDefaultProperties(commandLineProps)
  247. // init logging before specific config so we can log errors from here on
  248. DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath)
  249. initLogging(args)
  250. // load specified config file
  251. loadSpecifedConfigFile(args.Config)
  252. // apply environment overrides
  253. applyEnvVariableOverrides()
  254. // apply command line overrides
  255. applyCommandLineProperties(commandLineProps)
  256. // evaluate config values containing environment variables
  257. evalConfigValues()
  258. // update data path and logging config
  259. DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath)
  260. initLogging(args)
  261. }
  262. func pathExists(path string) bool {
  263. _, err := os.Stat(path)
  264. if err == nil {
  265. return true
  266. }
  267. if os.IsNotExist(err) {
  268. return false
  269. }
  270. return false
  271. }
  272. func setHomePath(args *CommandLineArgs) {
  273. if args.HomePath != "" {
  274. HomePath = args.HomePath
  275. return
  276. }
  277. HomePath, _ = filepath.Abs(".")
  278. // check if homepath is correct
  279. if pathExists(filepath.Join(HomePath, "conf/defaults.ini")) {
  280. return
  281. }
  282. // try down one path
  283. if pathExists(filepath.Join(HomePath, "../conf/defaults.ini")) {
  284. HomePath = filepath.Join(HomePath, "../")
  285. }
  286. }
  287. func NewConfigContext(args *CommandLineArgs) {
  288. setHomePath(args)
  289. loadConfiguration(args)
  290. Env = Cfg.Section("").Key("app_mode").MustString("development")
  291. server := Cfg.Section("server")
  292. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  293. Protocol = HTTP
  294. if server.Key("protocol").MustString("http") == "https" {
  295. Protocol = HTTPS
  296. CertFile = server.Key("cert_file").String()
  297. KeyFile = server.Key("cert_key").String()
  298. }
  299. Domain = server.Key("domain").MustString("localhost")
  300. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  301. HttpPort = server.Key("http_port").MustString("3000")
  302. StaticRootPath = makeAbsolute(server.Key("static_root_path").String(), HomePath)
  303. RouterLogging = server.Key("router_logging").MustBool(false)
  304. EnableGzip = server.Key("enable_gzip").MustBool(false)
  305. EnforceDomain = server.Key("enforce_domain").MustBool(false)
  306. security := Cfg.Section("security")
  307. SecretKey = security.Key("secret_key").String()
  308. LogInRememberDays = security.Key("login_remember_days").MustInt()
  309. CookieUserName = security.Key("cookie_username").String()
  310. CookieRememberName = security.Key("cookie_remember_name").String()
  311. DisableGravatar = security.Key("disable_gravatar").MustBool(true)
  312. // admin
  313. AdminUser = security.Key("admin_user").String()
  314. AdminPassword = security.Key("admin_password").String()
  315. users := Cfg.Section("users")
  316. AllowUserSignUp = users.Key("allow_sign_up").MustBool(true)
  317. AllowUserOrgCreate = users.Key("allow_org_create").MustBool(true)
  318. AutoAssignOrg = users.Key("auto_assign_org").MustBool(true)
  319. AutoAssignOrgRole = users.Key("auto_assign_org_role").In("Editor", []string{"Editor", "Admin", "Viewer"})
  320. // anonymous access
  321. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  322. AnonymousOrgName = Cfg.Section("auth.anonymous").Key("org_name").String()
  323. AnonymousOrgRole = Cfg.Section("auth.anonymous").Key("org_role").String()
  324. // auth proxy
  325. authProxy := Cfg.Section("auth.proxy")
  326. AuthProxyEnabled = authProxy.Key("enabled").MustBool(false)
  327. AuthProxyHeaderName = authProxy.Key("header_name").String()
  328. AuthProxyHeaderProperty = authProxy.Key("header_property").String()
  329. AuthProxyAutoSignUp = authProxy.Key("auto_sign_up").MustBool(true)
  330. // PhantomJS rendering
  331. ImagesDir = filepath.Join(DataPath, "png")
  332. PhantomDir = filepath.Join(HomePath, "vendor/phantomjs")
  333. analytics := Cfg.Section("analytics")
  334. ReportingEnabled = analytics.Key("reporting_enabled").MustBool(true)
  335. GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
  336. readSessionConfig()
  337. readSmtpSettings()
  338. }
  339. func readSessionConfig() {
  340. sec := Cfg.Section("session")
  341. SessionOptions = session.Options{}
  342. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres"})
  343. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  344. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  345. SessionOptions.CookiePath = AppSubUrl
  346. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  347. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  348. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  349. SessionOptions.IDLength = 16
  350. if SessionOptions.Provider == "file" {
  351. SessionOptions.ProviderConfig = makeAbsolute(SessionOptions.ProviderConfig, DataPath)
  352. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  353. }
  354. if SessionOptions.CookiePath == "" {
  355. SessionOptions.CookiePath = "/"
  356. }
  357. }
  358. var logLevels = map[string]int{
  359. "Trace": 0,
  360. "Debug": 1,
  361. "Info": 2,
  362. "Warn": 3,
  363. "Error": 4,
  364. "Critical": 5,
  365. }
  366. func initLogging(args *CommandLineArgs) {
  367. // Get and check log mode.
  368. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",")
  369. LogsPath = makeAbsolute(Cfg.Section("paths").Key("logs").String(), HomePath)
  370. LogConfigs = make([]util.DynMap, len(LogModes))
  371. for i, mode := range LogModes {
  372. mode = strings.TrimSpace(mode)
  373. sec, err := Cfg.GetSection("log." + mode)
  374. if err != nil {
  375. log.Fatal(4, "Unknown log mode: %s", mode)
  376. }
  377. // Log level.
  378. levelName := Cfg.Section("log."+mode).Key("level").In("Trace",
  379. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  380. level, ok := logLevels[levelName]
  381. if !ok {
  382. log.Fatal(4, "Unknown log level: %s", levelName)
  383. }
  384. // Generate log configuration.
  385. switch mode {
  386. case "console":
  387. LogConfigs[i] = util.DynMap{"level": level}
  388. case "file":
  389. logPath := sec.Key("file_name").MustString(filepath.Join(LogsPath, "grafana.log"))
  390. os.MkdirAll(filepath.Dir(logPath), os.ModePerm)
  391. LogConfigs[i] = util.DynMap{
  392. "level": level,
  393. "filename": logPath,
  394. "rotate": sec.Key("log_rotate").MustBool(true),
  395. "maxlines": sec.Key("max_lines").MustInt(1000000),
  396. "maxsize": 1 << uint(sec.Key("max_size_shift").MustInt(28)),
  397. "daily": sec.Key("daily_rotate").MustBool(true),
  398. "maxdays": sec.Key("max_days").MustInt(7),
  399. }
  400. case "conn":
  401. LogConfigs[i] = util.DynMap{
  402. "level": level,
  403. "reconnectOnMsg": sec.Key("reconnect_on_msg").MustBool(),
  404. "reconnect": sec.Key("reconnect").MustBool(),
  405. "net": sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}),
  406. "addr": sec.Key("addr").MustString(":7020"),
  407. }
  408. case "smtp":
  409. LogConfigs[i] = util.DynMap{
  410. "level": level,
  411. "user": sec.Key("user").MustString("example@example.com"),
  412. "passwd": sec.Key("passwd").MustString("******"),
  413. "host": sec.Key("host").MustString("127.0.0.1:25"),
  414. "receivers": sec.Key("receivers").MustString("[]"),
  415. "subject": sec.Key("subject").MustString("Diagnostic message from serve"),
  416. }
  417. case "database":
  418. LogConfigs[i] = util.DynMap{
  419. "level": level,
  420. "driver": sec.Key("driver").String(),
  421. "conn": sec.Key("conn").String(),
  422. }
  423. }
  424. cfgJsonBytes, _ := json.Marshal(LogConfigs[i])
  425. log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, string(cfgJsonBytes))
  426. }
  427. }
  428. func LogConfigurationInfo() {
  429. var text bytes.Buffer
  430. text.WriteString("Configuration Info\n")
  431. text.WriteString("Config files:\n")
  432. for i, file := range configFiles {
  433. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, file))
  434. }
  435. if len(appliedCommandLineProperties) > 0 {
  436. text.WriteString("Command lines overrides:\n")
  437. for i, prop := range appliedCommandLineProperties {
  438. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  439. }
  440. }
  441. if len(appliedEnvOverrides) > 0 {
  442. text.WriteString("\tEnvironment variables used:\n")
  443. for i, prop := range appliedCommandLineProperties {
  444. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  445. }
  446. }
  447. text.WriteString("Paths:\n")
  448. text.WriteString(fmt.Sprintf(" home: %s\n", HomePath))
  449. text.WriteString(fmt.Sprintf(" data: %s\n", DataPath))
  450. text.WriteString(fmt.Sprintf(" logs: %s\n", LogsPath))
  451. log.Info(text.String())
  452. }