setting.go 17 KB

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