setting.go 14 KB

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