setting.go 14 KB

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