setting.go 16 KB

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