setting.go 15 KB

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