setting.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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/go-macaron/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. PluginsPath string
  44. // Log settings.
  45. LogModes []string
  46. LogConfigs []util.DynMap
  47. // Http server options
  48. Protocol Scheme
  49. Domain string
  50. HttpAddr, HttpPort string
  51. SshPort int
  52. CertFile, KeyFile string
  53. RouterLogging bool
  54. StaticRootPath string
  55. EnableGzip bool
  56. EnforceDomain bool
  57. // Security settings.
  58. SecretKey string
  59. LogInRememberDays int
  60. CookieUserName string
  61. CookieRememberName string
  62. DisableGravatar bool
  63. EmailCodeValidMinutes int
  64. DataProxyWhiteList map[string]bool
  65. // Snapshots
  66. ExternalSnapshotUrl string
  67. ExternalSnapshotName string
  68. ExternalEnabled bool
  69. // User settings
  70. AllowUserSignUp bool
  71. AllowUserOrgCreate bool
  72. AutoAssignOrg bool
  73. AutoAssignOrgRole string
  74. VerifyEmailEnabled bool
  75. LoginHint string
  76. // Http auth
  77. AdminUser string
  78. AdminPassword string
  79. AnonymousEnabled bool
  80. AnonymousOrgName string
  81. AnonymousOrgRole string
  82. // Auth proxy settings
  83. AuthProxyEnabled bool
  84. AuthProxyHeaderName string
  85. AuthProxyHeaderProperty string
  86. AuthProxyAutoSignUp bool
  87. // Basic Auth
  88. BasicAuthEnabled bool
  89. // Session settings.
  90. SessionOptions session.Options
  91. // Global setting objects.
  92. Cfg *ini.File
  93. ConfRootPath string
  94. IsWindows bool
  95. // PhantomJs Rendering
  96. ImagesDir string
  97. PhantomDir string
  98. // for logging purposes
  99. configFiles []string
  100. appliedCommandLineProperties []string
  101. appliedEnvOverrides []string
  102. ReportingEnabled bool
  103. CheckForUpdates bool
  104. GoogleAnalyticsId string
  105. GoogleTagManagerId string
  106. // LDAP
  107. LdapEnabled bool
  108. LdapConfigFile string
  109. // SMTP email settings
  110. Smtp SmtpSettings
  111. // QUOTA
  112. Quota QuotaSettings
  113. // Alerting
  114. AlertingEnabled bool
  115. )
  116. type CommandLineArgs struct {
  117. Config string
  118. HomePath string
  119. Args []string
  120. }
  121. func init() {
  122. IsWindows = runtime.GOOS == "windows"
  123. log.NewLogger(0, "console", `{"level": 0, "formatting":true}`)
  124. }
  125. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  126. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  127. if appUrl[len(appUrl)-1] != '/' {
  128. appUrl += "/"
  129. }
  130. // Check if has app suburl.
  131. url, err := url.Parse(appUrl)
  132. if err != nil {
  133. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  134. }
  135. appSubUrl := strings.TrimSuffix(url.Path, "/")
  136. return appUrl, appSubUrl
  137. }
  138. func ToAbsUrl(relativeUrl string) string {
  139. return AppUrl + relativeUrl
  140. }
  141. func shouldRedactKey(s string) bool {
  142. uppercased := strings.ToUpper(s)
  143. return strings.Contains(uppercased, "PASSWORD") || strings.Contains(uppercased, "SECRET")
  144. }
  145. func applyEnvVariableOverrides() {
  146. appliedEnvOverrides = make([]string, 0)
  147. for _, section := range Cfg.Sections() {
  148. for _, key := range section.Keys() {
  149. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  150. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  151. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  152. envValue := os.Getenv(envKey)
  153. if len(envValue) > 0 {
  154. key.SetValue(envValue)
  155. if shouldRedactKey(envKey) {
  156. envValue = "*********"
  157. }
  158. appliedEnvOverrides = append(appliedEnvOverrides, fmt.Sprintf("%s=%s", envKey, envValue))
  159. }
  160. }
  161. }
  162. }
  163. func applyCommandLineDefaultProperties(props map[string]string) {
  164. appliedCommandLineProperties = make([]string, 0)
  165. for _, section := range Cfg.Sections() {
  166. for _, key := range section.Keys() {
  167. keyString := fmt.Sprintf("default.%s.%s", section.Name(), key.Name())
  168. value, exists := props[keyString]
  169. if exists {
  170. key.SetValue(value)
  171. if shouldRedactKey(keyString) {
  172. value = "*********"
  173. }
  174. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  175. }
  176. }
  177. }
  178. }
  179. func applyCommandLineProperties(props map[string]string) {
  180. for _, section := range Cfg.Sections() {
  181. for _, key := range section.Keys() {
  182. keyString := fmt.Sprintf("%s.%s", section.Name(), key.Name())
  183. value, exists := props[keyString]
  184. if exists {
  185. key.SetValue(value)
  186. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  187. }
  188. }
  189. }
  190. }
  191. func getCommandLineProperties(args []string) map[string]string {
  192. props := make(map[string]string)
  193. for _, arg := range args {
  194. if !strings.HasPrefix(arg, "cfg:") {
  195. continue
  196. }
  197. trimmed := strings.TrimPrefix(arg, "cfg:")
  198. parts := strings.Split(trimmed, "=")
  199. if len(parts) != 2 {
  200. log.Fatal(3, "Invalid command line argument", arg)
  201. return nil
  202. }
  203. props[parts[0]] = parts[1]
  204. }
  205. return props
  206. }
  207. func makeAbsolute(path string, root string) string {
  208. if filepath.IsAbs(path) {
  209. return path
  210. }
  211. return filepath.Join(root, path)
  212. }
  213. func evalEnvVarExpression(value string) string {
  214. regex := regexp.MustCompile(`\${(\w+)}`)
  215. return regex.ReplaceAllStringFunc(value, func(envVar string) string {
  216. envVar = strings.TrimPrefix(envVar, "${")
  217. envVar = strings.TrimSuffix(envVar, "}")
  218. envValue := os.Getenv(envVar)
  219. return envValue
  220. })
  221. }
  222. func evalConfigValues() {
  223. for _, section := range Cfg.Sections() {
  224. for _, key := range section.Keys() {
  225. key.SetValue(evalEnvVarExpression(key.Value()))
  226. }
  227. }
  228. }
  229. func loadSpecifedConfigFile(configFile string) {
  230. if configFile == "" {
  231. configFile = filepath.Join(HomePath, "conf/custom.ini")
  232. // return without error if custom file does not exist
  233. if !pathExists(configFile) {
  234. return
  235. }
  236. }
  237. userConfig, err := ini.Load(configFile)
  238. userConfig.BlockMode = false
  239. if err != nil {
  240. log.Fatal(3, "Failed to parse %v, %v", configFile, err)
  241. }
  242. for _, section := range userConfig.Sections() {
  243. for _, key := range section.Keys() {
  244. if key.Value() == "" {
  245. continue
  246. }
  247. defaultSec, err := Cfg.GetSection(section.Name())
  248. if err != nil {
  249. defaultSec, _ = Cfg.NewSection(section.Name())
  250. }
  251. defaultKey, err := defaultSec.GetKey(key.Name())
  252. if err != nil {
  253. defaultKey, _ = defaultSec.NewKey(key.Name(), key.Value())
  254. }
  255. defaultKey.SetValue(key.Value())
  256. }
  257. }
  258. configFiles = append(configFiles, configFile)
  259. }
  260. func loadConfiguration(args *CommandLineArgs) {
  261. var err error
  262. // load config defaults
  263. defaultConfigFile := path.Join(HomePath, "conf/defaults.ini")
  264. configFiles = append(configFiles, defaultConfigFile)
  265. Cfg, err = ini.Load(defaultConfigFile)
  266. Cfg.BlockMode = false
  267. if err != nil {
  268. log.Fatal(3, "Failed to parse defaults.ini, %v", err)
  269. }
  270. // command line props
  271. commandLineProps := getCommandLineProperties(args.Args)
  272. // load default overrides
  273. applyCommandLineDefaultProperties(commandLineProps)
  274. // init logging before specific config so we can log errors from here on
  275. DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath)
  276. initLogging(args)
  277. // load specified config file
  278. loadSpecifedConfigFile(args.Config)
  279. // apply environment overrides
  280. applyEnvVariableOverrides()
  281. // apply command line overrides
  282. applyCommandLineProperties(commandLineProps)
  283. // evaluate config values containing environment variables
  284. evalConfigValues()
  285. // update data path and logging config
  286. DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath)
  287. initLogging(args)
  288. }
  289. func pathExists(path string) bool {
  290. _, err := os.Stat(path)
  291. if err == nil {
  292. return true
  293. }
  294. if os.IsNotExist(err) {
  295. return false
  296. }
  297. return false
  298. }
  299. func setHomePath(args *CommandLineArgs) {
  300. if args.HomePath != "" {
  301. HomePath = args.HomePath
  302. return
  303. }
  304. HomePath, _ = filepath.Abs(".")
  305. // check if homepath is correct
  306. if pathExists(filepath.Join(HomePath, "conf/defaults.ini")) {
  307. return
  308. }
  309. // try down one path
  310. if pathExists(filepath.Join(HomePath, "../conf/defaults.ini")) {
  311. HomePath = filepath.Join(HomePath, "../")
  312. }
  313. }
  314. var skipStaticRootValidation bool = false
  315. func validateStaticRootPath() error {
  316. if skipStaticRootValidation {
  317. return nil
  318. }
  319. if _, err := os.Stat(path.Join(StaticRootPath, "css")); err == nil {
  320. return nil
  321. }
  322. if _, err := os.Stat(StaticRootPath + "_gen/css"); err == nil {
  323. StaticRootPath = StaticRootPath + "_gen"
  324. return nil
  325. }
  326. return fmt.Errorf("Failed to detect generated css or javascript files in static root (%s), have you executed default grunt task?", StaticRootPath)
  327. }
  328. func NewConfigContext(args *CommandLineArgs) error {
  329. setHomePath(args)
  330. loadConfiguration(args)
  331. Env = Cfg.Section("").Key("app_mode").MustString("development")
  332. PluginsPath = Cfg.Section("paths").Key("plugins").String()
  333. server := Cfg.Section("server")
  334. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  335. Protocol = HTTP
  336. if server.Key("protocol").MustString("http") == "https" {
  337. Protocol = HTTPS
  338. CertFile = server.Key("cert_file").String()
  339. KeyFile = server.Key("cert_key").String()
  340. }
  341. Domain = server.Key("domain").MustString("localhost")
  342. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  343. HttpPort = server.Key("http_port").MustString("3000")
  344. RouterLogging = server.Key("router_logging").MustBool(false)
  345. EnableGzip = server.Key("enable_gzip").MustBool(false)
  346. EnforceDomain = server.Key("enforce_domain").MustBool(false)
  347. StaticRootPath = makeAbsolute(server.Key("static_root_path").String(), HomePath)
  348. if err := validateStaticRootPath(); err != nil {
  349. return err
  350. }
  351. // read security settings
  352. security := Cfg.Section("security")
  353. SecretKey = security.Key("secret_key").String()
  354. LogInRememberDays = security.Key("login_remember_days").MustInt()
  355. CookieUserName = security.Key("cookie_username").String()
  356. CookieRememberName = security.Key("cookie_remember_name").String()
  357. DisableGravatar = security.Key("disable_gravatar").MustBool(true)
  358. // read snapshots settings
  359. snapshots := Cfg.Section("snapshots")
  360. ExternalSnapshotUrl = snapshots.Key("external_snapshot_url").String()
  361. ExternalSnapshotName = snapshots.Key("external_snapshot_name").String()
  362. ExternalEnabled = snapshots.Key("external_enabled").MustBool(true)
  363. // read data source proxy white list
  364. DataProxyWhiteList = make(map[string]bool)
  365. for _, hostAndIp := range security.Key("data_source_proxy_whitelist").Strings(" ") {
  366. DataProxyWhiteList[hostAndIp] = true
  367. }
  368. // admin
  369. AdminUser = security.Key("admin_user").String()
  370. AdminPassword = security.Key("admin_password").String()
  371. users := Cfg.Section("users")
  372. AllowUserSignUp = users.Key("allow_sign_up").MustBool(true)
  373. AllowUserOrgCreate = users.Key("allow_org_create").MustBool(true)
  374. AutoAssignOrg = users.Key("auto_assign_org").MustBool(true)
  375. AutoAssignOrgRole = users.Key("auto_assign_org_role").In("Editor", []string{"Editor", "Admin", "Read Only Editor", "Viewer"})
  376. VerifyEmailEnabled = users.Key("verify_email_enabled").MustBool(false)
  377. LoginHint = users.Key("login_hint").String()
  378. // anonymous access
  379. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  380. AnonymousOrgName = Cfg.Section("auth.anonymous").Key("org_name").String()
  381. AnonymousOrgRole = Cfg.Section("auth.anonymous").Key("org_role").String()
  382. // auth proxy
  383. authProxy := Cfg.Section("auth.proxy")
  384. AuthProxyEnabled = authProxy.Key("enabled").MustBool(false)
  385. AuthProxyHeaderName = authProxy.Key("header_name").String()
  386. AuthProxyHeaderProperty = authProxy.Key("header_property").String()
  387. AuthProxyAutoSignUp = authProxy.Key("auto_sign_up").MustBool(true)
  388. authBasic := Cfg.Section("auth.basic")
  389. BasicAuthEnabled = authBasic.Key("enabled").MustBool(true)
  390. // PhantomJS rendering
  391. ImagesDir = filepath.Join(DataPath, "png")
  392. PhantomDir = filepath.Join(HomePath, "vendor/phantomjs")
  393. analytics := Cfg.Section("analytics")
  394. ReportingEnabled = analytics.Key("reporting_enabled").MustBool(true)
  395. CheckForUpdates = analytics.Key("check_for_updates").MustBool(true)
  396. GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
  397. GoogleTagManagerId = analytics.Key("google_tag_manager_id").String()
  398. ldapSec := Cfg.Section("auth.ldap")
  399. LdapEnabled = ldapSec.Key("enabled").MustBool(false)
  400. LdapConfigFile = ldapSec.Key("config_file").String()
  401. alerting := Cfg.Section("alerting")
  402. AlertingEnabled = alerting.Key("enabled").MustBool(false)
  403. readSessionConfig()
  404. readSmtpSettings()
  405. readQuotaSettings()
  406. if VerifyEmailEnabled && !Smtp.Enabled {
  407. log.Warn("require_email_validation is enabled but smpt is disabled")
  408. }
  409. return nil
  410. }
  411. func readSessionConfig() {
  412. sec := Cfg.Section("session")
  413. SessionOptions = session.Options{}
  414. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres", "memcache"})
  415. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  416. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  417. SessionOptions.CookiePath = AppSubUrl
  418. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  419. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  420. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  421. SessionOptions.IDLength = 16
  422. if SessionOptions.Provider == "file" {
  423. SessionOptions.ProviderConfig = makeAbsolute(SessionOptions.ProviderConfig, DataPath)
  424. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  425. }
  426. if SessionOptions.CookiePath == "" {
  427. SessionOptions.CookiePath = "/"
  428. }
  429. }
  430. var logLevels = map[string]int{
  431. "Trace": 0,
  432. "Debug": 1,
  433. "Info": 2,
  434. "Warn": 3,
  435. "Error": 4,
  436. "Critical": 5,
  437. }
  438. func initLogging(args *CommandLineArgs) {
  439. //close any existing log handlers.
  440. log.Close()
  441. // Get and check log mode.
  442. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",")
  443. LogsPath = makeAbsolute(Cfg.Section("paths").Key("logs").String(), HomePath)
  444. LogConfigs = make([]util.DynMap, len(LogModes))
  445. for i, mode := range LogModes {
  446. mode = strings.TrimSpace(mode)
  447. sec, err := Cfg.GetSection("log." + mode)
  448. if err != nil {
  449. log.Fatal(4, "Unknown log mode: %s", mode)
  450. }
  451. // Log level.
  452. levelName := Cfg.Section("log."+mode).Key("level").In("Trace",
  453. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  454. level, ok := logLevels[levelName]
  455. if !ok {
  456. log.Fatal(4, "Unknown log level: %s", levelName)
  457. }
  458. // Generate log configuration.
  459. switch mode {
  460. case "console":
  461. formatting := sec.Key("formatting").MustBool(true)
  462. LogConfigs[i] = util.DynMap{
  463. "level": level,
  464. "formatting": formatting,
  465. }
  466. case "file":
  467. logPath := sec.Key("file_name").MustString(filepath.Join(LogsPath, "grafana.log"))
  468. os.MkdirAll(filepath.Dir(logPath), os.ModePerm)
  469. LogConfigs[i] = util.DynMap{
  470. "level": level,
  471. "filename": logPath,
  472. "rotate": sec.Key("log_rotate").MustBool(true),
  473. "maxlines": sec.Key("max_lines").MustInt(1000000),
  474. "maxsize": 1 << uint(sec.Key("max_size_shift").MustInt(28)),
  475. "daily": sec.Key("daily_rotate").MustBool(true),
  476. "maxdays": sec.Key("max_days").MustInt(7),
  477. }
  478. case "conn":
  479. LogConfigs[i] = util.DynMap{
  480. "level": level,
  481. "reconnectOnMsg": sec.Key("reconnect_on_msg").MustBool(),
  482. "reconnect": sec.Key("reconnect").MustBool(),
  483. "net": sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}),
  484. "addr": sec.Key("addr").MustString(":7020"),
  485. }
  486. case "smtp":
  487. LogConfigs[i] = util.DynMap{
  488. "level": level,
  489. "user": sec.Key("user").MustString("example@example.com"),
  490. "passwd": sec.Key("passwd").MustString("******"),
  491. "host": sec.Key("host").MustString("127.0.0.1:25"),
  492. "receivers": sec.Key("receivers").MustString("[]"),
  493. "subject": sec.Key("subject").MustString("Diagnostic message from serve"),
  494. }
  495. case "database":
  496. LogConfigs[i] = util.DynMap{
  497. "level": level,
  498. "driver": sec.Key("driver").String(),
  499. "conn": sec.Key("conn").String(),
  500. }
  501. case "syslog":
  502. LogConfigs[i] = util.DynMap{
  503. "level": level,
  504. "network": sec.Key("network").MustString(""),
  505. "address": sec.Key("address").MustString(""),
  506. "facility": sec.Key("facility").MustString("local7"),
  507. "tag": sec.Key("tag").MustString(""),
  508. }
  509. }
  510. cfgJsonBytes, _ := json.Marshal(LogConfigs[i])
  511. log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, string(cfgJsonBytes))
  512. }
  513. }
  514. func LogConfigurationInfo() {
  515. var text bytes.Buffer
  516. text.WriteString("Configuration Info\n")
  517. text.WriteString("Config files:\n")
  518. for i, file := range configFiles {
  519. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, file))
  520. }
  521. if len(appliedCommandLineProperties) > 0 {
  522. text.WriteString("Command lines overrides:\n")
  523. for i, prop := range appliedCommandLineProperties {
  524. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  525. }
  526. }
  527. if len(appliedEnvOverrides) > 0 {
  528. text.WriteString("\tEnvironment variables used:\n")
  529. for i, prop := range appliedEnvOverrides {
  530. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  531. }
  532. }
  533. text.WriteString("Paths:\n")
  534. text.WriteString(fmt.Sprintf(" home: %s\n", HomePath))
  535. text.WriteString(fmt.Sprintf(" data: %s\n", DataPath))
  536. text.WriteString(fmt.Sprintf(" logs: %s\n", LogsPath))
  537. text.WriteString(fmt.Sprintf(" plugins: %s\n", PluginsPath))
  538. log.Info(text.String())
  539. }