setting.go 13 KB

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