setting.go 14 KB

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