setting.go 15 KB

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