setting.go 16 KB

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