setting.go 22 KB

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