setting.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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. LogConfigs []util.DynMap
  50. // Http server options
  51. Protocol Scheme
  52. Domain string
  53. HttpAddr, HttpPort string
  54. SshPort int
  55. CertFile, KeyFile string
  56. SocketPath string
  57. RouterLogging bool
  58. DataProxyLogging bool
  59. StaticRootPath string
  60. EnableGzip bool
  61. EnforceDomain bool
  62. // Security settings.
  63. SecretKey string
  64. LogInRememberDays int
  65. CookieUserName string
  66. CookieRememberName string
  67. DisableGravatar bool
  68. EmailCodeValidMinutes int
  69. DataProxyWhiteList map[string]bool
  70. DisableBruteForceLoginProtection bool
  71. // Snapshots
  72. ExternalSnapshotUrl string
  73. ExternalSnapshotName string
  74. ExternalEnabled bool
  75. SnapShotRemoveExpired bool
  76. // Dashboard history
  77. DashboardVersionsToKeep int
  78. // User settings
  79. AllowUserSignUp bool
  80. AllowUserOrgCreate bool
  81. AutoAssignOrg bool
  82. AutoAssignOrgId int
  83. AutoAssignOrgRole string
  84. VerifyEmailEnabled bool
  85. LoginHint string
  86. DefaultTheme string
  87. DisableLoginForm bool
  88. DisableSignoutMenu bool
  89. SignoutRedirectUrl string
  90. ExternalUserMngLinkUrl string
  91. ExternalUserMngLinkName string
  92. ExternalUserMngInfo string
  93. ViewersCanEdit bool
  94. // Http auth
  95. AdminUser string
  96. AdminPassword string
  97. AnonymousEnabled bool
  98. AnonymousOrgName string
  99. AnonymousOrgRole string
  100. // Auth proxy settings
  101. AuthProxyEnabled bool
  102. AuthProxyHeaderName string
  103. AuthProxyHeaderProperty string
  104. AuthProxyAutoSignUp bool
  105. AuthProxyLdapSyncTtl int
  106. AuthProxyWhitelist string
  107. AuthProxyHeaders map[string]string
  108. // Basic Auth
  109. BasicAuthEnabled bool
  110. // Plugin settings
  111. PluginAppsSkipVerifyTLS bool
  112. // Session settings.
  113. SessionOptions session.Options
  114. SessionConnMaxLifetime int64
  115. // Global setting objects.
  116. Raw *ini.File
  117. ConfRootPath string
  118. IsWindows bool
  119. // for logging purposes
  120. configFiles []string
  121. appliedCommandLineProperties []string
  122. appliedEnvOverrides []string
  123. ReportingEnabled bool
  124. CheckForUpdates bool
  125. GoogleAnalyticsId string
  126. GoogleTagManagerId string
  127. // LDAP
  128. LdapEnabled bool
  129. LdapConfigFile string
  130. LdapAllowSignup = true
  131. // QUOTA
  132. Quota QuotaSettings
  133. // Alerting
  134. AlertingEnabled bool
  135. ExecuteAlerts bool
  136. AlertingRenderLimit int
  137. AlertingErrorOrTimeout string
  138. AlertingNoDataOrNullValues string
  139. // Explore UI
  140. ExploreEnabled bool
  141. // logger
  142. logger log.Logger
  143. // Grafana.NET URL
  144. GrafanaComUrl string
  145. // S3 temp image store
  146. S3TempImageStoreBucketUrl string
  147. S3TempImageStoreAccessKey string
  148. S3TempImageStoreSecretKey string
  149. ImageUploadProvider string
  150. )
  151. // TODO move all global vars to this struct
  152. type Cfg struct {
  153. Raw *ini.File
  154. // HTTP Server Settings
  155. AppUrl string
  156. AppSubUrl string
  157. // Paths
  158. ProvisioningPath string
  159. DataPath string
  160. LogsPath string
  161. // SMTP email settings
  162. Smtp SmtpSettings
  163. // Rendering
  164. ImagesDir string
  165. PhantomDir string
  166. RendererUrl string
  167. RendererCallbackUrl string
  168. RendererLimit int
  169. RendererLimitAlerting int
  170. DisableBruteForceLoginProtection bool
  171. TempDataLifetime time.Duration
  172. MetricsEndpointEnabled bool
  173. EnableAlphaPanels 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. panels := iniFile.Section("panels")
  578. cfg.EnableAlphaPanels = panels.Key("enable_alpha").MustBool(false)
  579. cfg.readSessionConfig()
  580. cfg.readSmtpSettings()
  581. cfg.readQuotaSettings()
  582. if VerifyEmailEnabled && !cfg.Smtp.Enabled {
  583. log.Warn("require_email_validation is enabled but smtp is disabled")
  584. }
  585. // check old key name
  586. GrafanaComUrl = iniFile.Section("grafana_net").Key("url").MustString("")
  587. if GrafanaComUrl == "" {
  588. GrafanaComUrl = iniFile.Section("grafana_com").Key("url").MustString("https://grafana.com")
  589. }
  590. imageUploadingSection := iniFile.Section("external_image_storage")
  591. ImageUploadProvider = imageUploadingSection.Key("provider").MustString("")
  592. return nil
  593. }
  594. func (cfg *Cfg) readSessionConfig() {
  595. sec := cfg.Raw.Section("session")
  596. SessionOptions = session.Options{}
  597. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres", "memcache"})
  598. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  599. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  600. SessionOptions.CookiePath = AppSubUrl
  601. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  602. SessionOptions.Gclifetime = cfg.Raw.Section("session").Key("gc_interval_time").MustInt64(86400)
  603. SessionOptions.Maxlifetime = cfg.Raw.Section("session").Key("session_life_time").MustInt64(86400)
  604. SessionOptions.IDLength = 16
  605. if SessionOptions.Provider == "file" {
  606. SessionOptions.ProviderConfig = makeAbsolute(SessionOptions.ProviderConfig, cfg.DataPath)
  607. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  608. }
  609. if SessionOptions.CookiePath == "" {
  610. SessionOptions.CookiePath = "/"
  611. }
  612. SessionConnMaxLifetime = cfg.Raw.Section("session").Key("conn_max_lifetime").MustInt64(14400)
  613. }
  614. func (cfg *Cfg) initLogging(file *ini.File) {
  615. // split on comma
  616. logModes := strings.Split(file.Section("log").Key("mode").MustString("console"), ",")
  617. // also try space
  618. if len(logModes) == 1 {
  619. logModes = strings.Split(file.Section("log").Key("mode").MustString("console"), " ")
  620. }
  621. cfg.LogsPath = makeAbsolute(file.Section("paths").Key("logs").String(), HomePath)
  622. log.ReadLoggingConfig(logModes, cfg.LogsPath, file)
  623. }
  624. func (cfg *Cfg) LogConfigSources() {
  625. var text bytes.Buffer
  626. for _, file := range configFiles {
  627. logger.Info("Config loaded from", "file", file)
  628. }
  629. if len(appliedCommandLineProperties) > 0 {
  630. for _, prop := range appliedCommandLineProperties {
  631. logger.Info("Config overridden from command line", "arg", prop)
  632. }
  633. }
  634. if len(appliedEnvOverrides) > 0 {
  635. text.WriteString("\tEnvironment variables used:\n")
  636. for _, prop := range appliedEnvOverrides {
  637. logger.Info("Config overridden from Environment variable", "var", prop)
  638. }
  639. }
  640. logger.Info("Path Home", "path", HomePath)
  641. logger.Info("Path Data", "path", cfg.DataPath)
  642. logger.Info("Path Logs", "path", cfg.LogsPath)
  643. logger.Info("Path Plugins", "path", PluginsPath)
  644. logger.Info("Path Provisioning", "path", cfg.ProvisioningPath)
  645. logger.Info("App mode " + Env)
  646. }