setting.go 15 KB

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