setting.go 14 KB

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