setting.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. // Copyright 2014 Unknwon
  2. // Copyright 2014 Torkel Ödegaard
  3. package setting
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "net/url"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "regexp"
  13. "runtime"
  14. "strings"
  15. "github.com/macaron-contrib/session"
  16. "gopkg.in/ini.v1"
  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. )
  25. const (
  26. DEV string = "development"
  27. PROD string = "production"
  28. TEST string = "test"
  29. )
  30. var (
  31. // App settings.
  32. Env string = DEV
  33. AppUrl string
  34. AppSubUrl string
  35. // build
  36. BuildVersion string
  37. BuildCommit string
  38. BuildStamp int64
  39. // Paths
  40. LogsPath string
  41. HomePath string
  42. DataPath string
  43. // Log settings.
  44. LogModes []string
  45. LogConfigs []util.DynMap
  46. // Http server options
  47. Protocol Scheme
  48. Domain string
  49. HttpAddr, HttpPort string
  50. SshPort int
  51. CertFile, KeyFile string
  52. RouterLogging bool
  53. StaticRootPath string
  54. EnableGzip bool
  55. EnforceDomain bool
  56. // Security settings.
  57. SecretKey string
  58. LogInRememberDays int
  59. CookieUserName string
  60. CookieRememberName string
  61. DisableGravatar bool
  62. EmailCodeValidMinutes int
  63. // User settings
  64. AllowUserSignUp bool
  65. AllowUserOrgCreate bool
  66. AutoAssignOrg bool
  67. AutoAssignOrgRole string
  68. // Http auth
  69. AdminUser string
  70. AdminPassword string
  71. AnonymousEnabled bool
  72. AnonymousOrgName string
  73. AnonymousOrgRole string
  74. // Auth proxy settings
  75. AuthProxyEnabled bool
  76. AuthProxyHeaderName string
  77. AuthProxyHeaderProperty string
  78. AuthProxyAutoSignUp bool
  79. // Basic Auth
  80. BasicAuthEnabled bool
  81. // Session settings.
  82. SessionOptions session.Options
  83. // Global setting objects.
  84. Cfg *ini.File
  85. ConfRootPath string
  86. IsWindows bool
  87. // PhantomJs Rendering
  88. ImagesDir string
  89. PhantomDir string
  90. // for logging purposes
  91. configFiles []string
  92. appliedCommandLineProperties []string
  93. appliedEnvOverrides []string
  94. ReportingEnabled bool
  95. GoogleAnalyticsId string
  96. GoogleTagManagerId string
  97. // LDAP
  98. LdapEnabled bool
  99. LdapConfigFile string
  100. // SMTP email settings
  101. Smtp SmtpSettings
  102. )
  103. type CommandLineArgs struct {
  104. Config string
  105. HomePath string
  106. Args []string
  107. }
  108. func init() {
  109. IsWindows = runtime.GOOS == "windows"
  110. log.NewLogger(0, "console", `{"level": 0}`)
  111. }
  112. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  113. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  114. if appUrl[len(appUrl)-1] != '/' {
  115. appUrl += "/"
  116. }
  117. // Check if has app suburl.
  118. url, err := url.Parse(appUrl)
  119. if err != nil {
  120. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  121. }
  122. appSubUrl := strings.TrimSuffix(url.Path, "/")
  123. return appUrl, appSubUrl
  124. }
  125. func ToAbsUrl(relativeUrl string) string {
  126. return AppUrl + relativeUrl
  127. }
  128. func applyEnvVariableOverrides() {
  129. appliedEnvOverrides = make([]string, 0)
  130. for _, section := range Cfg.Sections() {
  131. for _, key := range section.Keys() {
  132. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  133. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  134. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  135. envValue := os.Getenv(envKey)
  136. if len(envValue) > 0 {
  137. key.SetValue(envValue)
  138. appliedEnvOverrides = append(appliedEnvOverrides, fmt.Sprintf("%s=%s", envKey, envValue))
  139. }
  140. }
  141. }
  142. }
  143. func applyCommandLineDefaultProperties(props map[string]string) {
  144. appliedCommandLineProperties = make([]string, 0)
  145. for _, section := range Cfg.Sections() {
  146. for _, key := range section.Keys() {
  147. keyString := fmt.Sprintf("default.%s.%s", section.Name(), key.Name())
  148. value, exists := props[keyString]
  149. if exists {
  150. key.SetValue(value)
  151. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  152. }
  153. }
  154. }
  155. }
  156. func applyCommandLineProperties(props map[string]string) {
  157. for _, section := range Cfg.Sections() {
  158. for _, key := range section.Keys() {
  159. keyString := fmt.Sprintf("%s.%s", section.Name(), key.Name())
  160. value, exists := props[keyString]
  161. if exists {
  162. key.SetValue(value)
  163. appliedCommandLineProperties = append(appliedCommandLineProperties, fmt.Sprintf("%s=%s", keyString, value))
  164. }
  165. }
  166. }
  167. }
  168. func getCommandLineProperties(args []string) map[string]string {
  169. props := make(map[string]string)
  170. for _, arg := range args {
  171. if !strings.HasPrefix(arg, "cfg:") {
  172. continue
  173. }
  174. trimmed := strings.TrimPrefix(arg, "cfg:")
  175. parts := strings.Split(trimmed, "=")
  176. if len(parts) != 2 {
  177. log.Fatal(3, "Invalid command line argument", arg)
  178. return nil
  179. }
  180. props[parts[0]] = parts[1]
  181. }
  182. return props
  183. }
  184. func makeAbsolute(path string, root string) string {
  185. if filepath.IsAbs(path) {
  186. return path
  187. }
  188. return filepath.Join(root, path)
  189. }
  190. func evalEnvVarExpression(value string) string {
  191. regex := regexp.MustCompile(`\${(\w+)}`)
  192. return regex.ReplaceAllStringFunc(value, func(envVar string) string {
  193. envVar = strings.TrimPrefix(envVar, "${")
  194. envVar = strings.TrimSuffix(envVar, "}")
  195. envValue := os.Getenv(envVar)
  196. return envValue
  197. })
  198. }
  199. func evalConfigValues() {
  200. for _, section := range Cfg.Sections() {
  201. for _, key := range section.Keys() {
  202. key.SetValue(evalEnvVarExpression(key.Value()))
  203. }
  204. }
  205. }
  206. func loadSpecifedConfigFile(configFile string) {
  207. if configFile == "" {
  208. configFile = filepath.Join(HomePath, "conf/custom.ini")
  209. // return without error if custom file does not exist
  210. if !pathExists(configFile) {
  211. return
  212. }
  213. }
  214. userConfig, err := ini.Load(configFile)
  215. userConfig.BlockMode = false
  216. if err != nil {
  217. log.Fatal(3, "Failed to parse %v, %v", configFile, err)
  218. }
  219. for _, section := range userConfig.Sections() {
  220. for _, key := range section.Keys() {
  221. if key.Value() == "" {
  222. continue
  223. }
  224. defaultSec, err := Cfg.GetSection(section.Name())
  225. if err != nil {
  226. log.Error(3, "Unknown config section %s defined in %s", section.Name(), configFile)
  227. continue
  228. }
  229. defaultKey, err := defaultSec.GetKey(key.Name())
  230. if err != nil {
  231. log.Error(3, "Unknown config key %s defined in section %s, in file %s", key.Name(), section.Name(), configFile)
  232. continue
  233. }
  234. defaultKey.SetValue(key.Value())
  235. }
  236. }
  237. configFiles = append(configFiles, configFile)
  238. }
  239. func loadConfiguration(args *CommandLineArgs) {
  240. var err error
  241. // load config defaults
  242. defaultConfigFile := path.Join(HomePath, "conf/defaults.ini")
  243. configFiles = append(configFiles, defaultConfigFile)
  244. Cfg, err = ini.Load(defaultConfigFile)
  245. Cfg.BlockMode = false
  246. if err != nil {
  247. log.Fatal(3, "Failed to parse defaults.ini, %v", err)
  248. }
  249. // command line props
  250. commandLineProps := getCommandLineProperties(args.Args)
  251. // load default overrides
  252. applyCommandLineDefaultProperties(commandLineProps)
  253. // init logging before specific config so we can log errors from here on
  254. DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath)
  255. initLogging(args)
  256. // load specified config file
  257. loadSpecifedConfigFile(args.Config)
  258. // apply environment overrides
  259. applyEnvVariableOverrides()
  260. // apply command line overrides
  261. applyCommandLineProperties(commandLineProps)
  262. // evaluate config values containing environment variables
  263. evalConfigValues()
  264. // update data path and logging config
  265. DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath)
  266. initLogging(args)
  267. }
  268. func pathExists(path string) bool {
  269. _, err := os.Stat(path)
  270. if err == nil {
  271. return true
  272. }
  273. if os.IsNotExist(err) {
  274. return false
  275. }
  276. return false
  277. }
  278. func setHomePath(args *CommandLineArgs) {
  279. if args.HomePath != "" {
  280. HomePath = args.HomePath
  281. return
  282. }
  283. HomePath, _ = filepath.Abs(".")
  284. // check if homepath is correct
  285. if pathExists(filepath.Join(HomePath, "conf/defaults.ini")) {
  286. return
  287. }
  288. // try down one path
  289. if pathExists(filepath.Join(HomePath, "../conf/defaults.ini")) {
  290. HomePath = filepath.Join(HomePath, "../")
  291. }
  292. }
  293. func NewConfigContext(args *CommandLineArgs) {
  294. setHomePath(args)
  295. loadConfiguration(args)
  296. Env = Cfg.Section("").Key("app_mode").MustString("development")
  297. server := Cfg.Section("server")
  298. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  299. Protocol = HTTP
  300. if server.Key("protocol").MustString("http") == "https" {
  301. Protocol = HTTPS
  302. CertFile = server.Key("cert_file").String()
  303. KeyFile = server.Key("cert_key").String()
  304. }
  305. Domain = server.Key("domain").MustString("localhost")
  306. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  307. HttpPort = server.Key("http_port").MustString("3000")
  308. StaticRootPath = makeAbsolute(server.Key("static_root_path").String(), HomePath)
  309. RouterLogging = server.Key("router_logging").MustBool(false)
  310. EnableGzip = server.Key("enable_gzip").MustBool(false)
  311. EnforceDomain = server.Key("enforce_domain").MustBool(false)
  312. security := Cfg.Section("security")
  313. SecretKey = security.Key("secret_key").String()
  314. LogInRememberDays = security.Key("login_remember_days").MustInt()
  315. CookieUserName = security.Key("cookie_username").String()
  316. CookieRememberName = security.Key("cookie_remember_name").String()
  317. DisableGravatar = security.Key("disable_gravatar").MustBool(true)
  318. // admin
  319. AdminUser = security.Key("admin_user").String()
  320. AdminPassword = security.Key("admin_password").String()
  321. users := Cfg.Section("users")
  322. AllowUserSignUp = users.Key("allow_sign_up").MustBool(true)
  323. AllowUserOrgCreate = users.Key("allow_org_create").MustBool(true)
  324. AutoAssignOrg = users.Key("auto_assign_org").MustBool(true)
  325. AutoAssignOrgRole = users.Key("auto_assign_org_role").In("Editor", []string{"Editor", "Admin", "Read Only Editor", "Viewer"})
  326. // anonymous access
  327. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  328. AnonymousOrgName = Cfg.Section("auth.anonymous").Key("org_name").String()
  329. AnonymousOrgRole = Cfg.Section("auth.anonymous").Key("org_role").String()
  330. // auth proxy
  331. authProxy := Cfg.Section("auth.proxy")
  332. AuthProxyEnabled = authProxy.Key("enabled").MustBool(false)
  333. AuthProxyHeaderName = authProxy.Key("header_name").String()
  334. AuthProxyHeaderProperty = authProxy.Key("header_property").String()
  335. AuthProxyAutoSignUp = authProxy.Key("auto_sign_up").MustBool(true)
  336. authBasic := Cfg.Section("auth.basic")
  337. BasicAuthEnabled = authBasic.Key("enabled").MustBool(true)
  338. // PhantomJS rendering
  339. ImagesDir = filepath.Join(DataPath, "png")
  340. PhantomDir = filepath.Join(HomePath, "vendor/phantomjs")
  341. analytics := Cfg.Section("analytics")
  342. ReportingEnabled = analytics.Key("reporting_enabled").MustBool(true)
  343. GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
  344. GoogleTagManagerId = analytics.Key("google_tag_manager_id").String()
  345. ldapSec := Cfg.Section("auth.ldap")
  346. LdapEnabled = ldapSec.Key("enabled").MustBool(false)
  347. LdapConfigFile = ldapSec.Key("config_file").String()
  348. readSessionConfig()
  349. readSmtpSettings()
  350. }
  351. func readSessionConfig() {
  352. sec := Cfg.Section("session")
  353. SessionOptions = session.Options{}
  354. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres"})
  355. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  356. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  357. SessionOptions.CookiePath = AppSubUrl
  358. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  359. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  360. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  361. SessionOptions.IDLength = 16
  362. if SessionOptions.Provider == "file" {
  363. SessionOptions.ProviderConfig = makeAbsolute(SessionOptions.ProviderConfig, DataPath)
  364. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  365. }
  366. if SessionOptions.CookiePath == "" {
  367. SessionOptions.CookiePath = "/"
  368. }
  369. }
  370. var logLevels = map[string]int{
  371. "Trace": 0,
  372. "Debug": 1,
  373. "Info": 2,
  374. "Warn": 3,
  375. "Error": 4,
  376. "Critical": 5,
  377. }
  378. func initLogging(args *CommandLineArgs) {
  379. //close any existing log handlers.
  380. log.Close()
  381. // Get and check log mode.
  382. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",")
  383. LogsPath = makeAbsolute(Cfg.Section("paths").Key("logs").String(), HomePath)
  384. LogConfigs = make([]util.DynMap, len(LogModes))
  385. for i, mode := range LogModes {
  386. mode = strings.TrimSpace(mode)
  387. sec, err := Cfg.GetSection("log." + mode)
  388. if err != nil {
  389. log.Fatal(4, "Unknown log mode: %s", mode)
  390. }
  391. // Log level.
  392. levelName := Cfg.Section("log."+mode).Key("level").In("Trace",
  393. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  394. level, ok := logLevels[levelName]
  395. if !ok {
  396. log.Fatal(4, "Unknown log level: %s", levelName)
  397. }
  398. // Generate log configuration.
  399. switch mode {
  400. case "console":
  401. LogConfigs[i] = util.DynMap{"level": level}
  402. case "file":
  403. logPath := sec.Key("file_name").MustString(filepath.Join(LogsPath, "grafana.log"))
  404. os.MkdirAll(filepath.Dir(logPath), os.ModePerm)
  405. LogConfigs[i] = util.DynMap{
  406. "level": level,
  407. "filename": logPath,
  408. "rotate": sec.Key("log_rotate").MustBool(true),
  409. "maxlines": sec.Key("max_lines").MustInt(1000000),
  410. "maxsize": 1 << uint(sec.Key("max_size_shift").MustInt(28)),
  411. "daily": sec.Key("daily_rotate").MustBool(true),
  412. "maxdays": sec.Key("max_days").MustInt(7),
  413. }
  414. case "conn":
  415. LogConfigs[i] = util.DynMap{
  416. "level": level,
  417. "reconnectOnMsg": sec.Key("reconnect_on_msg").MustBool(),
  418. "reconnect": sec.Key("reconnect").MustBool(),
  419. "net": sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}),
  420. "addr": sec.Key("addr").MustString(":7020"),
  421. }
  422. case "smtp":
  423. LogConfigs[i] = util.DynMap{
  424. "level": level,
  425. "user": sec.Key("user").MustString("example@example.com"),
  426. "passwd": sec.Key("passwd").MustString("******"),
  427. "host": sec.Key("host").MustString("127.0.0.1:25"),
  428. "receivers": sec.Key("receivers").MustString("[]"),
  429. "subject": sec.Key("subject").MustString("Diagnostic message from serve"),
  430. }
  431. case "database":
  432. LogConfigs[i] = util.DynMap{
  433. "level": level,
  434. "driver": sec.Key("driver").String(),
  435. "conn": sec.Key("conn").String(),
  436. }
  437. }
  438. cfgJsonBytes, _ := json.Marshal(LogConfigs[i])
  439. log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, string(cfgJsonBytes))
  440. }
  441. }
  442. func LogConfigurationInfo() {
  443. var text bytes.Buffer
  444. text.WriteString("Configuration Info\n")
  445. text.WriteString("Config files:\n")
  446. for i, file := range configFiles {
  447. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, file))
  448. }
  449. if len(appliedCommandLineProperties) > 0 {
  450. text.WriteString("Command lines overrides:\n")
  451. for i, prop := range appliedCommandLineProperties {
  452. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  453. }
  454. }
  455. if len(appliedEnvOverrides) > 0 {
  456. text.WriteString("\tEnvironment variables used:\n")
  457. for i, prop := range appliedCommandLineProperties {
  458. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  459. }
  460. }
  461. text.WriteString("Paths:\n")
  462. text.WriteString(fmt.Sprintf(" home: %s\n", HomePath))
  463. text.WriteString(fmt.Sprintf(" data: %s\n", DataPath))
  464. text.WriteString(fmt.Sprintf(" logs: %s\n", LogsPath))
  465. log.Info(text.String())
  466. }