setting.go 16 KB

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