setting.go 17 KB

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