setting.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. DisableUserSignUp bool
  56. // single organization
  57. SingleOrgMode bool
  58. DefaultOrgName string
  59. DefaultOrgRole 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. WorkDir string
  70. Cfg *ini.File
  71. ConfRootPath string
  72. CustomPath string // Custom directory path.
  73. ProdMode bool
  74. RunUser string
  75. IsWindows bool
  76. // PhantomJs Rendering
  77. ImagesDir string
  78. PhantomDir string
  79. configFiles []string
  80. )
  81. func init() {
  82. IsWindows = runtime.GOOS == "windows"
  83. log.NewLogger(0, "console", `{"level": 0}`)
  84. WorkDir, _ = filepath.Abs(".")
  85. }
  86. func findConfigFiles(customConfigFile string) {
  87. ConfRootPath = path.Join(WorkDir, "conf")
  88. configFiles = make([]string, 0)
  89. configFile := path.Join(ConfRootPath, "defaults.ini")
  90. if com.IsFile(configFile) {
  91. configFiles = append(configFiles, configFile)
  92. }
  93. configFile = path.Join(ConfRootPath, "dev.ini")
  94. if com.IsFile(configFile) {
  95. configFiles = append(configFiles, configFile)
  96. }
  97. configFile = path.Join(ConfRootPath, "custom.ini")
  98. if com.IsFile(configFile) {
  99. configFiles = append(configFiles, configFile)
  100. }
  101. if customConfigFile != "" {
  102. configFiles = append(configFiles, customConfigFile)
  103. }
  104. if len(configFiles) == 0 {
  105. log.Fatal(3, "Could not find any config file")
  106. }
  107. }
  108. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  109. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  110. if appUrl[len(appUrl)-1] != '/' {
  111. appUrl += "/"
  112. }
  113. // Check if has app suburl.
  114. url, err := url.Parse(appUrl)
  115. if err != nil {
  116. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  117. }
  118. appSubUrl := strings.TrimSuffix(url.Path, "/")
  119. return appUrl, appSubUrl
  120. }
  121. func ToAbsUrl(relativeUrl string) string {
  122. return AppUrl + relativeUrl
  123. }
  124. func loadEnvVariableOverrides() {
  125. for _, section := range Cfg.Sections() {
  126. for _, key := range section.Keys() {
  127. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  128. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  129. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  130. envValue := os.Getenv(envKey)
  131. if len(envValue) > 0 {
  132. log.Info("Setting: ENV override found: %s", envKey)
  133. key.SetValue(envValue)
  134. }
  135. }
  136. }
  137. }
  138. func NewConfigContext(config string) {
  139. findConfigFiles(config)
  140. var err error
  141. for i, file := range configFiles {
  142. if i == 0 {
  143. Cfg, err = ini.Load(configFiles[i])
  144. } else {
  145. err = Cfg.Append(configFiles[i])
  146. }
  147. if err != nil {
  148. log.Fatal(4, "Fail to parse config file: %v, error: %v", file, err)
  149. }
  150. }
  151. loadEnvVariableOverrides()
  152. initLogging()
  153. AppName = Cfg.Section("").Key("app_name").MustString("Grafana")
  154. Env = Cfg.Section("").Key("app_mode").MustString("development")
  155. server := Cfg.Section("server")
  156. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  157. Protocol = HTTP
  158. if server.Key("protocol").MustString("http") == "https" {
  159. Protocol = HTTPS
  160. CertFile = server.Key("cert_file").String()
  161. KeyFile = server.Key("cert_file").String()
  162. }
  163. Domain = server.Key("domain").MustString("localhost")
  164. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  165. HttpPort = server.Key("http_port").MustString("3000")
  166. StaticRootPath = server.Key("static_root_path").MustString(path.Join(WorkDir, "webapp"))
  167. RouterLogging = server.Key("router_logging").MustBool(false)
  168. EnableGzip = server.Key("enable_gzip").MustBool(false)
  169. security := Cfg.Section("security")
  170. SecretKey = security.Key("secret_key").String()
  171. LogInRememberDays = security.Key("login_remember_days").MustInt()
  172. CookieUserName = security.Key("cookie_username").String()
  173. CookieRememberName = security.Key("cookie_remember_name").String()
  174. DisableUserSignUp = security.Key("disable_user_signup").MustBool(false)
  175. // admin
  176. AdminUser = security.Key("admin_user").String()
  177. AdminPassword = security.Key("admin_password").String()
  178. // single account
  179. SingleOrgMode = Cfg.Section("organization.single").Key("enabled").MustBool(false)
  180. DefaultOrgName = Cfg.Section("organization.single").Key("org_name").MustString("main")
  181. DefaultOrgRole = Cfg.Section("organization.single").Key("default_role").In("Editor", []string{"Editor", "Admin", "Viewer"})
  182. // anonymous access
  183. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  184. AnonymousOrgName = Cfg.Section("auth.anonymous").Key("org_name").String()
  185. AnonymousOrgRole = Cfg.Section("auth.anonymous").Key("org_role").String()
  186. // PhantomJS rendering
  187. ImagesDir = "data/png"
  188. PhantomDir = "vendor/phantomjs"
  189. readSessionConfig()
  190. }
  191. func readSessionConfig() {
  192. sec := Cfg.Section("session")
  193. SessionOptions = session.Options{}
  194. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql"})
  195. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  196. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  197. SessionOptions.CookiePath = AppSubUrl
  198. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  199. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  200. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  201. if SessionOptions.Provider == "file" {
  202. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  203. }
  204. }
  205. var logLevels = map[string]string{
  206. "Trace": "0",
  207. "Debug": "1",
  208. "Info": "2",
  209. "Warn": "3",
  210. "Error": "4",
  211. "Critical": "5",
  212. }
  213. func initLogging() {
  214. // Get and check log mode.
  215. LogModes = strings.Split(Cfg.Section("log").Key("mode").MustString("console"), ",")
  216. LogRootPath = Cfg.Section("log").Key("root_path").MustString(path.Join(WorkDir, "/data/log"))
  217. LogConfigs = make([]string, len(LogModes))
  218. for i, mode := range LogModes {
  219. mode = strings.TrimSpace(mode)
  220. sec, err := Cfg.GetSection("log." + mode)
  221. if err != nil {
  222. log.Fatal(4, "Unknown log mode: %s", mode)
  223. }
  224. // Log level.
  225. levelName := Cfg.Section("log."+mode).Key("level").In("Trace",
  226. []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
  227. level, ok := logLevels[levelName]
  228. if !ok {
  229. log.Fatal(4, "Unknown log level: %s", levelName)
  230. }
  231. // Generate log configuration.
  232. switch mode {
  233. case "console":
  234. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  235. case "file":
  236. logPath := sec.Key("file_name").MustString(path.Join(LogRootPath, "grafana.log"))
  237. os.MkdirAll(path.Dir(logPath), os.ModePerm)
  238. LogConfigs[i] = fmt.Sprintf(
  239. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  240. logPath,
  241. sec.Key("log_rotate").MustBool(true),
  242. sec.Key("max_lines").MustInt(1000000),
  243. 1<<uint(sec.Key("max_size_shift").MustInt(28)),
  244. sec.Key("daily_rotate").MustBool(true),
  245. sec.Key("max_days").MustInt(7))
  246. case "conn":
  247. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  248. sec.Key("reconnect_on_msg").MustBool(),
  249. sec.Key("reconnect").MustBool(),
  250. sec.Key("protocol").In("tcp", []string{"tcp", "unix", "udp"}),
  251. sec.Key("addr").MustString(":7020"))
  252. case "smtp":
  253. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
  254. sec.Key("user").MustString("example@example.com"),
  255. sec.Key("passwd").MustString("******"),
  256. sec.Key("host").MustString("127.0.0.1:25"),
  257. sec.Key("receivers").MustString("[]"),
  258. sec.Key("subject").MustString("Diagnostic message from serve"))
  259. case "database":
  260. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  261. sec.Key("driver").String(),
  262. sec.Key("conn").String())
  263. }
  264. log.NewLogger(Cfg.Section("log").Key("buffer_len").MustInt64(10000), mode, LogConfigs[i])
  265. }
  266. }
  267. func LogLoadedConfigFiles() {
  268. for _, file := range configFiles {
  269. log.Info("Config: Loaded from %s", file)
  270. }
  271. }