setting.go 17 KB

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