setting.go 16 KB

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