setting.go 24 KB

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