setting.go 17 KB

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