setting.go 16 KB

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