setting.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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. "gopkg.in/ini.v1"
  15. "github.com/go-macaron/session"
  16. "time"
  17. "github.com/grafana/grafana/pkg/log"
  18. "github.com/grafana/grafana/pkg/util"
  19. )
  20. type Scheme string
  21. const (
  22. HTTP Scheme = "http"
  23. HTTPS Scheme = "https"
  24. SOCKET Scheme = "socket"
  25. DEFAULT_HTTP_ADDR string = "0.0.0.0"
  26. )
  27. const (
  28. DEV string = "development"
  29. PROD string = "production"
  30. TEST string = "test"
  31. )
  32. var (
  33. // App settings.
  34. Env = DEV
  35. AppUrl string
  36. AppSubUrl string
  37. InstanceName string
  38. // build
  39. BuildVersion string
  40. BuildCommit string
  41. BuildStamp int64
  42. IsEnterprise bool
  43. ApplicationName string
  44. // Paths
  45. HomePath string
  46. PluginsPath string
  47. CustomInitPath = "conf/custom.ini"
  48. // Log settings.
  49. LogModes []string
  50. LogConfigs []util.DynMap
  51. // Http server options
  52. Protocol Scheme
  53. Domain string
  54. HttpAddr, HttpPort string
  55. SshPort int
  56. CertFile, KeyFile string
  57. SocketPath string
  58. RouterLogging bool
  59. DataProxyLogging bool
  60. StaticRootPath string
  61. EnableGzip bool
  62. EnforceDomain bool
  63. // Security settings.
  64. SecretKey string
  65. LogInRememberDays int
  66. CookieUserName string
  67. CookieRememberName string
  68. DisableGravatar bool
  69. EmailCodeValidMinutes int
  70. DataProxyWhiteList map[string]bool
  71. DisableBruteForceLoginProtection bool
  72. // Snapshots
  73. ExternalSnapshotUrl string
  74. ExternalSnapshotName string
  75. ExternalEnabled bool
  76. SnapShotRemoveExpired bool
  77. // Dashboard history
  78. DashboardVersionsToKeep int
  79. // User settings
  80. AllowUserSignUp bool
  81. AllowUserOrgCreate bool
  82. AutoAssignOrg bool
  83. AutoAssignOrgId int
  84. AutoAssignOrgRole string
  85. VerifyEmailEnabled bool
  86. LoginHint string
  87. DefaultTheme string
  88. DisableLoginForm bool
  89. DisableSignoutMenu bool
  90. SignoutRedirectUrl string
  91. ExternalUserMngLinkUrl string
  92. ExternalUserMngLinkName string
  93. ExternalUserMngInfo string
  94. ViewersCanEdit bool
  95. // Http auth
  96. AdminUser string
  97. AdminPassword string
  98. AnonymousEnabled bool
  99. AnonymousOrgName string
  100. AnonymousOrgRole string
  101. // Auth proxy settings
  102. AuthProxyEnabled bool
  103. AuthProxyHeaderName string
  104. AuthProxyHeaderProperty string
  105. AuthProxyAutoSignUp bool
  106. AuthProxyLdapSyncTtl int
  107. AuthProxyWhitelist string
  108. AuthProxyHeaders map[string]string
  109. // Basic Auth
  110. BasicAuthEnabled bool
  111. // Plugin settings
  112. PluginAppsSkipVerifyTLS bool
  113. // Session settings.
  114. SessionOptions session.Options
  115. SessionConnMaxLifetime int64
  116. // Global setting objects.
  117. Raw *ini.File
  118. ConfRootPath string
  119. IsWindows bool
  120. // for logging purposes
  121. configFiles []string
  122. appliedCommandLineProperties []string
  123. appliedEnvOverrides []string
  124. ReportingEnabled bool
  125. CheckForUpdates bool
  126. GoogleAnalyticsId string
  127. GoogleTagManagerId string
  128. // LDAP
  129. LdapEnabled bool
  130. LdapConfigFile string
  131. LdapAllowSignup = true
  132. // QUOTA
  133. Quota QuotaSettings
  134. // Alerting
  135. AlertingEnabled bool
  136. ExecuteAlerts bool
  137. AlertingRenderLimit int
  138. AlertingErrorOrTimeout string
  139. AlertingNoDataOrNullValues string
  140. // Explore UI
  141. ExploreEnabled bool
  142. // logger
  143. logger log.Logger
  144. // Grafana.NET URL
  145. GrafanaComUrl string
  146. // S3 temp image store
  147. S3TempImageStoreBucketUrl string
  148. S3TempImageStoreAccessKey string
  149. S3TempImageStoreSecretKey string
  150. ImageUploadProvider string
  151. )
  152. // TODO move all global vars to this struct
  153. type Cfg struct {
  154. Raw *ini.File
  155. // HTTP Server Settings
  156. AppUrl string
  157. AppSubUrl string
  158. // Paths
  159. ProvisioningPath string
  160. DataPath string
  161. LogsPath string
  162. // SMTP email settings
  163. Smtp SmtpSettings
  164. // Rendering
  165. ImagesDir string
  166. PhantomDir string
  167. RendererUrl string
  168. RendererCallbackUrl string
  169. RendererLimit int
  170. RendererLimitAlerting int
  171. DisableBruteForceLoginProtection bool
  172. TempDataLifetime time.Duration
  173. MetricsEndpointEnabled bool
  174. }
  175. type CommandLineArgs struct {
  176. Config string
  177. HomePath string
  178. Args []string
  179. }
  180. func init() {
  181. IsWindows = runtime.GOOS == "windows"
  182. logger = log.New("settings")
  183. }
  184. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  185. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  186. if appUrl[len(appUrl)-1] != '/' {
  187. appUrl += "/"
  188. }
  189. // Check if has app suburl.
  190. url, err := url.Parse(appUrl)
  191. if err != nil {
  192. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  193. }
  194. appSubUrl := strings.TrimSuffix(url.Path, "/")
  195. return appUrl, appSubUrl
  196. }
  197. func ToAbsUrl(relativeUrl string) string {
  198. return AppUrl + relativeUrl
  199. }
  200. func shouldRedactKey(s string) bool {
  201. uppercased := strings.ToUpper(s)
  202. return strings.Contains(uppercased, "PASSWORD") || strings.Contains(uppercased, "SECRET") || strings.Contains(uppercased, "PROVIDER_CONFIG")
  203. }
  204. func shouldRedactURLKey(s string) bool {
  205. uppercased := strings.ToUpper(s)
  206. return strings.Contains(uppercased, "DATABASE_URL")
  207. }
  208. func applyEnvVariableOverrides(file *ini.File) error {
  209. appliedEnvOverrides = make([]string, 0)
  210. for _, section := range file.Sections() {
  211. for _, key := range section.Keys() {
  212. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  213. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  214. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  215. envValue := os.Getenv(envKey)
  216. if len(envValue) > 0 {
  217. key.SetValue(envValue)
  218. if shouldRedactKey(envKey) {
  219. envValue = "*********"
  220. }
  221. if shouldRedactURLKey(envKey) {
  222. u, err := url.Parse(envValue)
  223. if err != nil {
  224. return fmt.Errorf("could not parse environment variable. key: %s, value: %s. error: %v", envKey, envValue, err)
  225. }
  226. ui := u.User
  227. if ui != nil {
  228. _, exists := ui.Password()
  229. if exists {
  230. u.User = url.UserPassword(ui.Username(), "-redacted-")
  231. envValue = u.String()
  232. }
  233. }
  234. }
  235. appliedEnvOverrides = append(appliedEnvOverrides, fmt.Sprintf("%s=%s", envKey, envValue))
  236. }
  237. }
  238. }
  239. return nil
  240. }
  241. func applyCommandLineDefaultProperties(props map[string]string, file *ini.File) {
  242. appliedCommandLineProperties = make([]string, 0)
  243. for _, section := range file.Sections() {
  244. for _, key := range section.Keys() {
  245. keyString := fmt.Sprintf("default.%s.%s", section.Name(), key.Name())
  246. value, exists := props[keyString]
  247. if exists {
  248. key.SetValue(value)
  249. if shouldRedactKey(keyString) {
  250. value = "*********"
  251. }
  252. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  253. }
  254. }
  255. }
  256. }
  257. func applyCommandLineProperties(props map[string]string, file *ini.File) {
  258. for _, section := range file.Sections() {
  259. sectionName := section.Name() + "."
  260. if section.Name() == ini.DEFAULT_SECTION {
  261. sectionName = ""
  262. }
  263. for _, key := range section.Keys() {
  264. keyString := sectionName + key.Name()
  265. value, exists := props[keyString]
  266. if exists {
  267. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  268. key.SetValue(value)
  269. }
  270. }
  271. }
  272. }
  273. func getCommandLineProperties(args []string) map[string]string {
  274. props := make(map[string]string)
  275. for _, arg := range args {
  276. if !strings.HasPrefix(arg, "cfg:") {
  277. continue
  278. }
  279. trimmed := strings.TrimPrefix(arg, "cfg:")
  280. parts := strings.Split(trimmed, "=")
  281. if len(parts) != 2 {
  282. log.Fatal(3, "Invalid command line argument. argument: %v", arg)
  283. return nil
  284. }
  285. props[parts[0]] = parts[1]
  286. }
  287. return props
  288. }
  289. func makeAbsolute(path string, root string) string {
  290. if filepath.IsAbs(path) {
  291. return path
  292. }
  293. return filepath.Join(root, path)
  294. }
  295. func evalEnvVarExpression(value string) string {
  296. regex := regexp.MustCompile(`\${(\w+)}`)
  297. return regex.ReplaceAllStringFunc(value, func(envVar string) string {
  298. envVar = strings.TrimPrefix(envVar, "${")
  299. envVar = strings.TrimSuffix(envVar, "}")
  300. envValue := os.Getenv(envVar)
  301. // if env variable is hostname and it is empty use os.Hostname as default
  302. if envVar == "HOSTNAME" && envValue == "" {
  303. envValue, _ = os.Hostname()
  304. }
  305. return envValue
  306. })
  307. }
  308. func evalConfigValues(file *ini.File) {
  309. for _, section := range file.Sections() {
  310. for _, key := range section.Keys() {
  311. key.SetValue(evalEnvVarExpression(key.Value()))
  312. }
  313. }
  314. }
  315. func loadSpecifedConfigFile(configFile string, masterFile *ini.File) error {
  316. if configFile == "" {
  317. configFile = filepath.Join(HomePath, CustomInitPath)
  318. // return without error if custom file does not exist
  319. if !pathExists(configFile) {
  320. return nil
  321. }
  322. }
  323. userConfig, err := ini.Load(configFile)
  324. if err != nil {
  325. return fmt.Errorf("Failed to parse %v, %v", configFile, err)
  326. }
  327. userConfig.BlockMode = false
  328. for _, section := range userConfig.Sections() {
  329. for _, key := range section.Keys() {
  330. if key.Value() == "" {
  331. continue
  332. }
  333. defaultSec, err := masterFile.GetSection(section.Name())
  334. if err != nil {
  335. defaultSec, _ = masterFile.NewSection(section.Name())
  336. }
  337. defaultKey, err := defaultSec.GetKey(key.Name())
  338. if err != nil {
  339. defaultKey, _ = defaultSec.NewKey(key.Name(), key.Value())
  340. }
  341. defaultKey.SetValue(key.Value())
  342. }
  343. }
  344. configFiles = append(configFiles, configFile)
  345. return nil
  346. }
  347. func (cfg *Cfg) loadConfiguration(args *CommandLineArgs) (*ini.File, error) {
  348. var err error
  349. // load config defaults
  350. defaultConfigFile := path.Join(HomePath, "conf/defaults.ini")
  351. configFiles = append(configFiles, defaultConfigFile)
  352. // check if config file exists
  353. if _, err := os.Stat(defaultConfigFile); os.IsNotExist(err) {
  354. fmt.Println("Grafana-server Init Failed: Could not find config defaults, make sure homepath command line parameter is set or working directory is homepath")
  355. os.Exit(1)
  356. }
  357. // load defaults
  358. parsedFile, err := ini.Load(defaultConfigFile)
  359. if err != nil {
  360. fmt.Println(fmt.Sprintf("Failed to parse defaults.ini, %v", err))
  361. os.Exit(1)
  362. return nil, err
  363. }
  364. parsedFile.BlockMode = false
  365. // command line props
  366. commandLineProps := getCommandLineProperties(args.Args)
  367. // load default overrides
  368. applyCommandLineDefaultProperties(commandLineProps, parsedFile)
  369. // load specified config file
  370. err = loadSpecifedConfigFile(args.Config, parsedFile)
  371. if err != nil {
  372. cfg.initLogging(parsedFile)
  373. log.Fatal(3, err.Error())
  374. }
  375. // apply environment overrides
  376. err = applyEnvVariableOverrides(parsedFile)
  377. if err != nil {
  378. return nil, err
  379. }
  380. // apply command line overrides
  381. applyCommandLineProperties(commandLineProps, parsedFile)
  382. // evaluate config values containing environment variables
  383. evalConfigValues(parsedFile)
  384. // update data path and logging config
  385. cfg.DataPath = makeAbsolute(parsedFile.Section("paths").Key("data").String(), HomePath)
  386. cfg.initLogging(parsedFile)
  387. return parsedFile, err
  388. }
  389. func pathExists(path string) bool {
  390. _, err := os.Stat(path)
  391. if err == nil {
  392. return true
  393. }
  394. if os.IsNotExist(err) {
  395. return false
  396. }
  397. return false
  398. }
  399. func setHomePath(args *CommandLineArgs) {
  400. if args.HomePath != "" {
  401. HomePath = args.HomePath
  402. return
  403. }
  404. HomePath, _ = filepath.Abs(".")
  405. // check if homepath is correct
  406. if pathExists(filepath.Join(HomePath, "conf/defaults.ini")) {
  407. return
  408. }
  409. // try down one path
  410. if pathExists(filepath.Join(HomePath, "../conf/defaults.ini")) {
  411. HomePath = filepath.Join(HomePath, "../")
  412. }
  413. }
  414. var skipStaticRootValidation = false
  415. func validateStaticRootPath() error {
  416. if skipStaticRootValidation {
  417. return nil
  418. }
  419. if _, err := os.Stat(path.Join(StaticRootPath, "build")); err != nil {
  420. logger.Error("Failed to detect generated javascript files in public/build")
  421. }
  422. return nil
  423. }
  424. func NewCfg() *Cfg {
  425. return &Cfg{
  426. Raw: ini.Empty(),
  427. }
  428. }
  429. func (cfg *Cfg) Load(args *CommandLineArgs) error {
  430. setHomePath(args)
  431. iniFile, err := cfg.loadConfiguration(args)
  432. if err != nil {
  433. return err
  434. }
  435. cfg.Raw = iniFile
  436. // Temporary keep global, to make refactor in steps
  437. Raw = cfg.Raw
  438. ApplicationName = "Grafana"
  439. if IsEnterprise {
  440. ApplicationName += " Enterprise"
  441. }
  442. Env = iniFile.Section("").Key("app_mode").MustString("development")
  443. InstanceName = iniFile.Section("").Key("instance_name").MustString("unknown_instance_name")
  444. PluginsPath = makeAbsolute(iniFile.Section("paths").Key("plugins").String(), HomePath)
  445. cfg.ProvisioningPath = makeAbsolute(iniFile.Section("paths").Key("provisioning").String(), HomePath)
  446. server := iniFile.Section("server")
  447. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  448. cfg.AppUrl = AppUrl
  449. cfg.AppSubUrl = AppSubUrl
  450. Protocol = HTTP
  451. if server.Key("protocol").MustString("http") == "https" {
  452. Protocol = HTTPS
  453. CertFile = server.Key("cert_file").String()
  454. KeyFile = server.Key("cert_key").String()
  455. }
  456. if server.Key("protocol").MustString("http") == "socket" {
  457. Protocol = SOCKET
  458. SocketPath = server.Key("socket").String()
  459. }
  460. Domain = server.Key("domain").MustString("localhost")
  461. HttpAddr = server.Key("http_addr").MustString(DEFAULT_HTTP_ADDR)
  462. HttpPort = server.Key("http_port").MustString("3000")
  463. RouterLogging = server.Key("router_logging").MustBool(false)
  464. EnableGzip = server.Key("enable_gzip").MustBool(false)
  465. EnforceDomain = server.Key("enforce_domain").MustBool(false)
  466. StaticRootPath = makeAbsolute(server.Key("static_root_path").String(), HomePath)
  467. if err := validateStaticRootPath(); err != nil {
  468. return err
  469. }
  470. // read data proxy settings
  471. dataproxy := iniFile.Section("dataproxy")
  472. DataProxyLogging = dataproxy.Key("logging").MustBool(false)
  473. // read security settings
  474. security := iniFile.Section("security")
  475. SecretKey = security.Key("secret_key").String()
  476. LogInRememberDays = security.Key("login_remember_days").MustInt()
  477. CookieUserName = security.Key("cookie_username").String()
  478. CookieRememberName = security.Key("cookie_remember_name").String()
  479. DisableGravatar = security.Key("disable_gravatar").MustBool(true)
  480. cfg.DisableBruteForceLoginProtection = security.Key("disable_brute_force_login_protection").MustBool(false)
  481. DisableBruteForceLoginProtection = cfg.DisableBruteForceLoginProtection
  482. // read snapshots settings
  483. snapshots := iniFile.Section("snapshots")
  484. ExternalSnapshotUrl = snapshots.Key("external_snapshot_url").String()
  485. ExternalSnapshotName = snapshots.Key("external_snapshot_name").String()
  486. ExternalEnabled = snapshots.Key("external_enabled").MustBool(true)
  487. SnapShotRemoveExpired = snapshots.Key("snapshot_remove_expired").MustBool(true)
  488. // read dashboard settings
  489. dashboards := iniFile.Section("dashboards")
  490. DashboardVersionsToKeep = dashboards.Key("versions_to_keep").MustInt(20)
  491. // read data source proxy white list
  492. DataProxyWhiteList = make(map[string]bool)
  493. for _, hostAndIp := range util.SplitString(security.Key("data_source_proxy_whitelist").String()) {
  494. DataProxyWhiteList[hostAndIp] = true
  495. }
  496. // admin
  497. AdminUser = security.Key("admin_user").String()
  498. AdminPassword = security.Key("admin_password").String()
  499. users := iniFile.Section("users")
  500. AllowUserSignUp = users.Key("allow_sign_up").MustBool(true)
  501. AllowUserOrgCreate = users.Key("allow_org_create").MustBool(true)
  502. AutoAssignOrg = users.Key("auto_assign_org").MustBool(true)
  503. AutoAssignOrgId = users.Key("auto_assign_org_id").MustInt(1)
  504. AutoAssignOrgRole = users.Key("auto_assign_org_role").In("Editor", []string{"Editor", "Admin", "Viewer"})
  505. VerifyEmailEnabled = users.Key("verify_email_enabled").MustBool(false)
  506. LoginHint = users.Key("login_hint").String()
  507. DefaultTheme = users.Key("default_theme").String()
  508. ExternalUserMngLinkUrl = users.Key("external_manage_link_url").String()
  509. ExternalUserMngLinkName = users.Key("external_manage_link_name").String()
  510. ExternalUserMngInfo = users.Key("external_manage_info").String()
  511. ViewersCanEdit = users.Key("viewers_can_edit").MustBool(false)
  512. // auth
  513. auth := iniFile.Section("auth")
  514. DisableLoginForm = auth.Key("disable_login_form").MustBool(false)
  515. DisableSignoutMenu = auth.Key("disable_signout_menu").MustBool(false)
  516. SignoutRedirectUrl = auth.Key("signout_redirect_url").String()
  517. // anonymous access
  518. AnonymousEnabled = iniFile.Section("auth.anonymous").Key("enabled").MustBool(false)
  519. AnonymousOrgName = iniFile.Section("auth.anonymous").Key("org_name").String()
  520. AnonymousOrgRole = iniFile.Section("auth.anonymous").Key("org_role").String()
  521. // auth proxy
  522. authProxy := iniFile.Section("auth.proxy")
  523. AuthProxyEnabled = authProxy.Key("enabled").MustBool(false)
  524. AuthProxyHeaderName = authProxy.Key("header_name").String()
  525. AuthProxyHeaderProperty = authProxy.Key("header_property").String()
  526. AuthProxyAutoSignUp = authProxy.Key("auto_sign_up").MustBool(true)
  527. AuthProxyLdapSyncTtl = authProxy.Key("ldap_sync_ttl").MustInt()
  528. AuthProxyWhitelist = authProxy.Key("whitelist").String()
  529. AuthProxyHeaders = make(map[string]string)
  530. for _, propertyAndHeader := range util.SplitString(authProxy.Key("headers").String()) {
  531. split := strings.SplitN(propertyAndHeader, ":", 2)
  532. if len(split) == 2 {
  533. AuthProxyHeaders[split[0]] = split[1]
  534. }
  535. }
  536. // basic auth
  537. authBasic := iniFile.Section("auth.basic")
  538. BasicAuthEnabled = authBasic.Key("enabled").MustBool(true)
  539. // global plugin settings
  540. PluginAppsSkipVerifyTLS = iniFile.Section("plugins").Key("app_tls_skip_verify_insecure").MustBool(false)
  541. // Rendering
  542. renderSec := iniFile.Section("rendering")
  543. cfg.RendererUrl = renderSec.Key("server_url").String()
  544. cfg.RendererCallbackUrl = renderSec.Key("callback_url").String()
  545. if cfg.RendererCallbackUrl == "" {
  546. cfg.RendererCallbackUrl = AppUrl
  547. } else {
  548. if cfg.RendererCallbackUrl[len(cfg.RendererCallbackUrl)-1] != '/' {
  549. cfg.RendererCallbackUrl += "/"
  550. }
  551. _, err := url.Parse(cfg.RendererCallbackUrl)
  552. if err != nil {
  553. log.Fatal(4, "Invalid callback_url(%s): %s", cfg.RendererCallbackUrl, err)
  554. }
  555. }
  556. cfg.ImagesDir = filepath.Join(cfg.DataPath, "png")
  557. cfg.PhantomDir = filepath.Join(HomePath, "tools/phantomjs")
  558. cfg.TempDataLifetime = iniFile.Section("paths").Key("temp_data_lifetime").MustDuration(time.Second * 3600 * 24)
  559. cfg.MetricsEndpointEnabled = iniFile.Section("metrics").Key("enabled").MustBool(true)
  560. analytics := iniFile.Section("analytics")
  561. ReportingEnabled = analytics.Key("reporting_enabled").MustBool(true)
  562. CheckForUpdates = analytics.Key("check_for_updates").MustBool(true)
  563. GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
  564. GoogleTagManagerId = analytics.Key("google_tag_manager_id").String()
  565. ldapSec := iniFile.Section("auth.ldap")
  566. LdapEnabled = ldapSec.Key("enabled").MustBool(false)
  567. LdapConfigFile = ldapSec.Key("config_file").String()
  568. LdapAllowSignup = ldapSec.Key("allow_sign_up").MustBool(true)
  569. alerting := iniFile.Section("alerting")
  570. AlertingEnabled = alerting.Key("enabled").MustBool(true)
  571. ExecuteAlerts = alerting.Key("execute_alerts").MustBool(true)
  572. AlertingRenderLimit = alerting.Key("concurrent_render_limit").MustInt(5)
  573. AlertingErrorOrTimeout = alerting.Key("error_or_timeout").MustString("alerting")
  574. AlertingNoDataOrNullValues = alerting.Key("nodata_or_nullvalues").MustString("no_data")
  575. explore := iniFile.Section("explore")
  576. ExploreEnabled = explore.Key("enabled").MustBool(false)
  577. cfg.readSessionConfig()
  578. cfg.readSmtpSettings()
  579. cfg.readQuotaSettings()
  580. if VerifyEmailEnabled && !cfg.Smtp.Enabled {
  581. log.Warn("require_email_validation is enabled but smtp is disabled")
  582. }
  583. // check old key name
  584. GrafanaComUrl = iniFile.Section("grafana_net").Key("url").MustString("")
  585. if GrafanaComUrl == "" {
  586. GrafanaComUrl = iniFile.Section("grafana_com").Key("url").MustString("https://grafana.com")
  587. }
  588. imageUploadingSection := iniFile.Section("external_image_storage")
  589. ImageUploadProvider = imageUploadingSection.Key("provider").MustString("")
  590. return nil
  591. }
  592. func (cfg *Cfg) readSessionConfig() {
  593. sec := cfg.Raw.Section("session")
  594. SessionOptions = session.Options{}
  595. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres", "memcache"})
  596. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  597. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  598. SessionOptions.CookiePath = AppSubUrl
  599. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  600. SessionOptions.Gclifetime = cfg.Raw.Section("session").Key("gc_interval_time").MustInt64(86400)
  601. SessionOptions.Maxlifetime = cfg.Raw.Section("session").Key("session_life_time").MustInt64(86400)
  602. SessionOptions.IDLength = 16
  603. if SessionOptions.Provider == "file" {
  604. SessionOptions.ProviderConfig = makeAbsolute(SessionOptions.ProviderConfig, cfg.DataPath)
  605. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  606. }
  607. if SessionOptions.CookiePath == "" {
  608. SessionOptions.CookiePath = "/"
  609. }
  610. SessionConnMaxLifetime = cfg.Raw.Section("session").Key("conn_max_lifetime").MustInt64(14400)
  611. }
  612. func (cfg *Cfg) initLogging(file *ini.File) {
  613. // split on comma
  614. logModes := strings.Split(file.Section("log").Key("mode").MustString("console"), ",")
  615. // also try space
  616. if len(logModes) == 1 {
  617. logModes = strings.Split(file.Section("log").Key("mode").MustString("console"), " ")
  618. }
  619. cfg.LogsPath = makeAbsolute(file.Section("paths").Key("logs").String(), HomePath)
  620. log.ReadLoggingConfig(logModes, cfg.LogsPath, file)
  621. }
  622. func (cfg *Cfg) LogConfigSources() {
  623. var text bytes.Buffer
  624. for _, file := range configFiles {
  625. logger.Info("Config loaded from", "file", file)
  626. }
  627. if len(appliedCommandLineProperties) > 0 {
  628. for _, prop := range appliedCommandLineProperties {
  629. logger.Info("Config overridden from command line", "arg", prop)
  630. }
  631. }
  632. if len(appliedEnvOverrides) > 0 {
  633. text.WriteString("\tEnvironment variables used:\n")
  634. for _, prop := range appliedEnvOverrides {
  635. logger.Info("Config overridden from Environment variable", "var", prop)
  636. }
  637. }
  638. logger.Info("Path Home", "path", HomePath)
  639. logger.Info("Path Data", "path", cfg.DataPath)
  640. logger.Info("Path Logs", "path", cfg.LogsPath)
  641. logger.Info("Path Plugins", "path", PluginsPath)
  642. logger.Info("Path Provisioning", "path", cfg.ProvisioningPath)
  643. logger.Info("App mode " + Env)
  644. }