setting.go 16 KB

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