setting.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. Args []string
  89. }
  90. func init() {
  91. IsWindows = runtime.GOOS == "windows"
  92. log.NewLogger(0, "console", `{"level": 0}`)
  93. HomePath, _ = filepath.Abs(".")
  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. userConfig, err := ini.Load(configFile)
  191. if err != nil {
  192. log.Fatal(3, "Failed to parse %v, %v", configFile, err)
  193. }
  194. for _, section := range userConfig.Sections() {
  195. for _, key := range section.Keys() {
  196. if key.Value() == "" {
  197. continue
  198. }
  199. defaultSec, err := Cfg.GetSection(section.Name())
  200. if err != nil {
  201. log.Fatal(3, "Unknown config section %s defined in %s", section.Name(), configFile)
  202. }
  203. defaultKey, err := defaultSec.GetKey(key.Name())
  204. if err != nil {
  205. log.Fatal(3, "Unknown config key %s defined in section %s, in file", key.Name(), section.Name(), configFile)
  206. }
  207. defaultKey.SetValue(key.Value())
  208. }
  209. }
  210. configFiles = append(configFiles, configFile)
  211. }
  212. func loadConfiguration(args *CommandLineArgs) {
  213. var err error
  214. args.Config = evalEnvVarExpression(args.Config)
  215. // load config defaults
  216. defaultConfigFile := path.Join(HomePath, "conf/defaults.ini")
  217. configFiles = append(configFiles, defaultConfigFile)
  218. Cfg, err = ini.Load(defaultConfigFile)
  219. Cfg.BlockMode = true
  220. if err != nil {
  221. log.Fatal(3, "Failed to parse defaults.ini, %v", err)
  222. }
  223. // command line props
  224. commandLineProps := getCommandLineProperties(args.Args)
  225. // load default overrides
  226. applyCommandLineDefaultProperties(commandLineProps)
  227. // load specified config file
  228. if args.Config != "" {
  229. loadSpecifedConfigFile(args.Config)
  230. }
  231. // apply environment overrides
  232. applyEnvVariableOverrides()
  233. // apply command line overrides
  234. applyCommandLineProperties(commandLineProps)
  235. // evaluate config values containing environment variables
  236. evalConfigValues()
  237. }
  238. func NewConfigContext(args *CommandLineArgs) {
  239. loadConfiguration(args)
  240. DataPath = makeAbsolute(Cfg.Section("paths").Key("data").String(), HomePath)
  241. initLogging(args)
  242. AppName = Cfg.Section("").Key("app_name").MustString("Grafana")
  243. Env = Cfg.Section("").Key("app_mode").MustString("development")
  244. server := Cfg.Section("server")
  245. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  246. Protocol = HTTP
  247. if server.Key("protocol").MustString("http") == "https" {
  248. Protocol = HTTPS
  249. CertFile = server.Key("cert_file").String()
  250. KeyFile = server.Key("cert_key").String()
  251. }
  252. Domain = server.Key("domain").MustString("localhost")
  253. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  254. HttpPort = server.Key("http_port").MustString("3000")
  255. StaticRootPath = server.Key("static_root_path").MustString(path.Join(HomePath, "public"))
  256. RouterLogging = server.Key("router_logging").MustBool(false)
  257. EnableGzip = server.Key("enable_gzip").MustBool(false)
  258. security := Cfg.Section("security")
  259. SecretKey = security.Key("secret_key").String()
  260. LogInRememberDays = security.Key("login_remember_days").MustInt()
  261. CookieUserName = security.Key("cookie_username").String()
  262. CookieRememberName = security.Key("cookie_remember_name").String()
  263. // admin
  264. AdminUser = security.Key("admin_user").String()
  265. AdminPassword = security.Key("admin_password").String()
  266. users := Cfg.Section("users")
  267. AllowUserSignUp = users.Key("allow_sign_up").MustBool(true)
  268. AllowUserOrgCreate = users.Key("allow_org_create").MustBool(true)
  269. AutoAssignOrg = users.Key("auto_assign_org").MustBool(true)
  270. AutoAssignOrgRole = users.Key("auto_assign_org_role").In("Editor", []string{"Editor", "Admin", "Viewer"})
  271. // anonymous access
  272. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  273. AnonymousOrgName = Cfg.Section("auth.anonymous").Key("org_name").String()
  274. AnonymousOrgRole = Cfg.Section("auth.anonymous").Key("org_role").String()
  275. // PhantomJS rendering
  276. ImagesDir = filepath.Join(DataPath, "png")
  277. PhantomDir = filepath.Join(HomePath, "vendor/phantomjs")
  278. analytics := Cfg.Section("analytics")
  279. ReportingEnabled = analytics.Key("reporting_enabled").MustBool(true)
  280. GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
  281. readSessionConfig()
  282. }
  283. func readSessionConfig() {
  284. sec := Cfg.Section("session")
  285. SessionOptions = session.Options{}
  286. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres"})
  287. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  288. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  289. SessionOptions.CookiePath = AppSubUrl
  290. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  291. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  292. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  293. SessionOptions.IDLength = 16
  294. if SessionOptions.Provider == "file" {
  295. SessionOptions.ProviderConfig = makeAbsolute(SessionOptions.ProviderConfig, DataPath)
  296. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  297. }
  298. if SessionOptions.CookiePath == "" {
  299. SessionOptions.CookiePath = "/"
  300. }
  301. }
  302. var logLevels = map[string]string{
  303. "Trace": "0",
  304. "Debug": "1",
  305. "Info": "2",
  306. "Warn": "3",
  307. "Error": "4",
  308. "Critical": "5",
  309. }
  310. func initLogging(args *CommandLineArgs) {
  311. // Get and check log mode.
  312. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",")
  313. LogsPath = makeAbsolute(Cfg.Section("paths").Key("logs").String(), HomePath)
  314. LogConfigs = make([]string, len(LogModes))
  315. for i, mode := range LogModes {
  316. mode = strings.TrimSpace(mode)
  317. sec, err := Cfg.GetSection("log." + mode)
  318. if err != nil {
  319. log.Fatal(4, "Unknown log mode: %s", mode)
  320. }
  321. // Log level.
  322. levelName := Cfg.Section("log."+mode).Key("level").In("Trace",
  323. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  324. level, ok := logLevels[levelName]
  325. if !ok {
  326. log.Fatal(4, "Unknown log level: %s", levelName)
  327. }
  328. // Generate log configuration.
  329. switch mode {
  330. case "console":
  331. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  332. case "file":
  333. logPath := sec.Key("file_name").MustString(path.Join(LogsPath, "grafana.log"))
  334. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  335. LogConfigs[i] = fmt.Sprintf(
  336. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  337. logPath,
  338. sec.Key("log_rotate").MustBool(true),
  339. sec.Key("max_lines").MustInt(1000000),
  340. 1<<uint(sec.Key("max_size_shift").MustInt(28)),
  341. sec.Key("daily_rotate").MustBool(true),
  342. sec.Key("max_days").MustInt(7))
  343. case "conn":
  344. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  345. sec.Key("reconnect_on_msg").MustBool(),
  346. sec.Key("reconnect").MustBool(),
  347. sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}),
  348. sec.Key("addr").MustString(":7020"))
  349. case "smtp":
  350. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  351. sec.Key("user").MustString("example@example.com"),
  352. sec.Key("passwd").MustString("******"),
  353. sec.Key("host").MustString("127.0.0.1:25"),
  354. sec.Key("receivers").MustString("[]"),
  355. sec.Key("subject").MustString("Diagnostic message from serve"))
  356. case "database":
  357. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  358. sec.Key("driver").String(),
  359. sec.Key("conn").String())
  360. }
  361. log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, LogConfigs[i])
  362. }
  363. }
  364. func LogConfigurationInfo() {
  365. var text bytes.Buffer
  366. text.WriteString("Configuration Info\n")
  367. text.WriteString("Config files:\n")
  368. for i, file := range configFiles {
  369. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, file))
  370. }
  371. if len(appliedCommandLineProperties) > 0 {
  372. text.WriteString("Command lines overrides:\n")
  373. for i, prop := range appliedCommandLineProperties {
  374. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  375. }
  376. }
  377. if len(appliedEnvOverrides) > 0 {
  378. text.WriteString("\tEnvironment variables used:\n")
  379. for i, prop := range appliedCommandLineProperties {
  380. text.WriteString(fmt.Sprintf(" [%d]: %s\n", i, prop))
  381. }
  382. }
  383. text.WriteString("Paths:\n")
  384. text.WriteString(fmt.Sprintf(" home: %s\n", HomePath))
  385. text.WriteString(fmt.Sprintf(" data: %s\n", DataPath))
  386. text.WriteString(fmt.Sprintf(" logs: %s\n", LogsPath))
  387. log.Info(text.String())
  388. }