setting.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. // Copyright 2014 Unknwon
  2. // Copyright 2014 Torkel Ödegaard
  3. package setting
  4. import (
  5. "fmt"
  6. "net/url"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "github.com/Unknwon/com"
  13. "github.com/macaron-contrib/session"
  14. "gopkg.in/ini.v1"
  15. "github.com/grafana/grafana/pkg/log"
  16. )
  17. type Scheme string
  18. const (
  19. HTTP Scheme = "http"
  20. HTTPS Scheme = "https"
  21. )
  22. const (
  23. DEV string = "development"
  24. PROD string = "production"
  25. TEST string = "test"
  26. )
  27. var (
  28. // App settings.
  29. Env string = DEV
  30. AppName string
  31. AppUrl string
  32. AppSubUrl string
  33. // build
  34. BuildVersion string
  35. BuildCommit string
  36. BuildStamp int64
  37. // Log settings.
  38. LogRootPath string
  39. LogModes []string
  40. LogConfigs []string
  41. // Http server options
  42. Protocol Scheme
  43. Domain string
  44. HttpAddr, HttpPort string
  45. SshPort int
  46. CertFile, KeyFile string
  47. RouterLogging bool
  48. StaticRootPath string
  49. EnableGzip bool
  50. // Security settings.
  51. SecretKey string
  52. LogInRememberDays int
  53. CookieUserName string
  54. CookieRememberName string
  55. // User settings
  56. AllowUserSignUp bool
  57. AllowUserOrgCreate bool
  58. AutoAssignOrg bool
  59. AutoAssignOrgRole string
  60. // Http auth
  61. AdminUser string
  62. AdminPassword string
  63. AnonymousEnabled bool
  64. AnonymousOrgName string
  65. AnonymousOrgRole string
  66. // Session settings.
  67. SessionOptions session.Options
  68. // Global setting objects.
  69. DataPath string
  70. WorkPath string
  71. Cfg *ini.File
  72. ConfRootPath string
  73. IsWindows bool
  74. // PhantomJs Rendering
  75. ImagesDir string
  76. PhantomDir string
  77. configFiles []string
  78. ReportingEnabled bool
  79. GoogleAnalyticsId string
  80. )
  81. type CommandLineArgs struct {
  82. DefaultDataPath string
  83. DefaultLogPath string
  84. Config string
  85. }
  86. func init() {
  87. IsWindows = runtime.GOOS == "windows"
  88. log.NewLogger(0, "console", `{"level": 0}`)
  89. WorkPath, _ = filepath.Abs(".")
  90. }
  91. func findConfigFiles(customConfigFile string) {
  92. ConfRootPath = path.Join(WorkPath, "conf")
  93. configFiles = make([]string, 0)
  94. configFile := path.Join(ConfRootPath, "defaults.ini")
  95. if com.IsFile(configFile) {
  96. configFiles = append(configFiles, configFile)
  97. }
  98. configFile = path.Join(ConfRootPath, "dev.ini")
  99. if com.IsFile(configFile) {
  100. configFiles = append(configFiles, configFile)
  101. }
  102. configFile = path.Join(ConfRootPath, "custom.ini")
  103. if com.IsFile(configFile) {
  104. configFiles = append(configFiles, configFile)
  105. }
  106. if customConfigFile != "" {
  107. configFiles = append(configFiles, customConfigFile)
  108. }
  109. if len(configFiles) == 0 {
  110. log.Fatal(3, "Could not find any config file")
  111. }
  112. }
  113. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  114. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  115. if appUrl[len(appUrl)-1] != '/' {
  116. appUrl += "/"
  117. }
  118. // Check if has app suburl.
  119. url, err := url.Parse(appUrl)
  120. if err != nil {
  121. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  122. }
  123. appSubUrl := strings.TrimSuffix(url.Path, "/")
  124. return appUrl, appSubUrl
  125. }
  126. func ToAbsUrl(relativeUrl string) string {
  127. return AppUrl + relativeUrl
  128. }
  129. func loadEnvVariableOverrides() {
  130. for _, section := range Cfg.Sections() {
  131. for _, key := range section.Keys() {
  132. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  133. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  134. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  135. envValue := os.Getenv(envKey)
  136. if len(envValue) > 0 {
  137. log.Info("Setting: ENV override found: %s", envKey)
  138. key.SetValue(envValue)
  139. }
  140. }
  141. }
  142. }
  143. func NewConfigContext(args *CommandLineArgs) {
  144. findConfigFiles(args.Config)
  145. var err error
  146. for i, file := range configFiles {
  147. if i == 0 {
  148. Cfg, err = ini.Load(configFiles[i])
  149. Cfg.BlockMode = false
  150. } else {
  151. err = Cfg.Append(configFiles[i])
  152. }
  153. if err != nil {
  154. log.Fatal(4, "Fail to parse config file: %v, error: %v", file, err)
  155. }
  156. }
  157. loadEnvVariableOverrides()
  158. DataPath = Cfg.Section("").Key("data_path").String()
  159. // if no data path in config, use command line, otherwise default to
  160. // data folder relative to working dir
  161. if DataPath == "" {
  162. if args.DefaultDataPath != "" {
  163. DataPath = args.DefaultDataPath
  164. } else {
  165. DataPath = filepath.Join(WorkPath, "data")
  166. }
  167. }
  168. initLogging(args)
  169. AppName = Cfg.Section("").Key("app_name").MustString("Grafana")
  170. Env = Cfg.Section("").Key("app_mode").MustString("development")
  171. server := Cfg.Section("server")
  172. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  173. Protocol = HTTP
  174. if server.Key("protocol").MustString("http") == "https" {
  175. Protocol = HTTPS
  176. CertFile = server.Key("cert_file").String()
  177. KeyFile = server.Key("cert_key").String()
  178. }
  179. Domain = server.Key("domain").MustString("localhost")
  180. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  181. HttpPort = server.Key("http_port").MustString("3000")
  182. StaticRootPath = server.Key("static_root_path").MustString(path.Join(WorkPath, "public"))
  183. RouterLogging = server.Key("router_logging").MustBool(false)
  184. EnableGzip = server.Key("enable_gzip").MustBool(false)
  185. security := Cfg.Section("security")
  186. SecretKey = security.Key("secret_key").String()
  187. LogInRememberDays = security.Key("login_remember_days").MustInt()
  188. CookieUserName = security.Key("cookie_username").String()
  189. CookieRememberName = security.Key("cookie_remember_name").String()
  190. // admin
  191. AdminUser = security.Key("admin_user").String()
  192. AdminPassword = security.Key("admin_password").String()
  193. users := Cfg.Section("users")
  194. AllowUserSignUp = users.Key("allow_sign_up").MustBool(true)
  195. AllowUserOrgCreate = users.Key("allow_org_create").MustBool(true)
  196. AutoAssignOrg = users.Key("auto_assign_org").MustBool(true)
  197. AutoAssignOrgRole = users.Key("auto_assign_org_role").In("Editor", []string{"Editor", "Admin", "Viewer"})
  198. // anonymous access
  199. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  200. AnonymousOrgName = Cfg.Section("auth.anonymous").Key("org_name").String()
  201. AnonymousOrgRole = Cfg.Section("auth.anonymous").Key("org_role").String()
  202. // PhantomJS rendering
  203. ImagesDir = filepath.Join(DataPath, "png")
  204. PhantomDir = filepath.Join(WorkPath, "vendor/phantomjs")
  205. analytics := Cfg.Section("analytics")
  206. ReportingEnabled = analytics.Key("reporting_enabled").MustBool(true)
  207. GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
  208. readSessionConfig()
  209. }
  210. func readSessionConfig() {
  211. sec := Cfg.Section("session")
  212. SessionOptions = session.Options{}
  213. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql", "postgres"})
  214. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  215. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  216. SessionOptions.CookiePath = AppSubUrl
  217. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  218. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  219. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  220. SessionOptions.IDLength = 16
  221. if SessionOptions.Provider == "file" {
  222. if !filepath.IsAbs(SessionOptions.ProviderConfig) {
  223. SessionOptions.ProviderConfig = filepath.Join(DataPath, SessionOptions.ProviderConfig)
  224. }
  225. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  226. }
  227. if SessionOptions.CookiePath == "" {
  228. SessionOptions.CookiePath = "/"
  229. }
  230. }
  231. var logLevels = map[string]string{
  232. "Trace": "0",
  233. "Debug": "1",
  234. "Info": "2",
  235. "Warn": "3",
  236. "Error": "4",
  237. "Critical": "5",
  238. }
  239. func initLogging(args *CommandLineArgs) {
  240. // Get and check log mode.
  241. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",")
  242. LogRootPath = Cfg.Section("log").Key("root_path").String()
  243. if LogRootPath == "" {
  244. if args.DefaultLogPath != "" {
  245. LogRootPath = args.DefaultLogPath
  246. } else {
  247. LogRootPath = filepath.Join(DataPath, "log")
  248. }
  249. }
  250. LogConfigs = make([]string, len(LogModes))
  251. for i, mode := range LogModes {
  252. mode = strings.TrimSpace(mode)
  253. sec, err := Cfg.GetSection("log." + mode)
  254. if err != nil {
  255. log.Fatal(4, "Unknown log mode: %s", mode)
  256. }
  257. // Log level.
  258. levelName := Cfg.Section("log."+mode).Key("level").In("Trace",
  259. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  260. level, ok := logLevels[levelName]
  261. if !ok {
  262. log.Fatal(4, "Unknown log level: %s", levelName)
  263. }
  264. // Generate log configuration.
  265. switch mode {
  266. case "console":
  267. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  268. case "file":
  269. logPath := sec.Key("file_name").MustString(path.Join(LogRootPath, "grafana.log"))
  270. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  271. LogConfigs[i] = fmt.Sprintf(
  272. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  273. logPath,
  274. sec.Key("log_rotate").MustBool(true),
  275. sec.Key("max_lines").MustInt(1000000),
  276. 1<<uint(sec.Key("max_size_shift").MustInt(28)),
  277. sec.Key("daily_rotate").MustBool(true),
  278. sec.Key("max_days").MustInt(7))
  279. case "conn":
  280. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  281. sec.Key("reconnect_on_msg").MustBool(),
  282. sec.Key("reconnect").MustBool(),
  283. sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}),
  284. sec.Key("addr").MustString(":7020"))
  285. case "smtp":
  286. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  287. sec.Key("user").MustString("example@example.com"),
  288. sec.Key("passwd").MustString("******"),
  289. sec.Key("host").MustString("127.0.0.1:25"),
  290. sec.Key("receivers").MustString("[]"),
  291. sec.Key("subject").MustString("Diagnostic message from serve"))
  292. case "database":
  293. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  294. sec.Key("driver").String(),
  295. sec.Key("conn").String())
  296. }
  297. log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, LogConfigs[i])
  298. }
  299. }
  300. func LogLoadedConfigFiles() {
  301. for _, file := range configFiles {
  302. log.Info("Config: Loaded from %s", file)
  303. }
  304. }