setting.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 account
  57. SingleAccountMode bool
  58. DefaultAccountName string
  59. DefaultAccountRole string
  60. // Http auth
  61. AdminUser string
  62. AdminPassword string
  63. AnonymousEnabled bool
  64. AnonymousAccountName string
  65. AnonymousAccountRole 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. )
  80. func init() {
  81. IsWindows = runtime.GOOS == "windows"
  82. log.NewLogger(0, "console", `{"level": 0}`)
  83. WorkDir, _ = filepath.Abs(".")
  84. }
  85. func findConfigFiles() []string {
  86. ConfRootPath = path.Join(WorkDir, "conf")
  87. filenames := make([]string, 0)
  88. configFile := path.Join(ConfRootPath, "grafana.ini")
  89. if com.IsFile(configFile) {
  90. filenames = append(filenames, configFile)
  91. }
  92. configFile = path.Join(ConfRootPath, "grafana.dev.ini")
  93. if com.IsFile(configFile) {
  94. filenames = append(filenames, configFile)
  95. }
  96. configFile = path.Join(ConfRootPath, "grafana.custom.ini")
  97. if com.IsFile(configFile) {
  98. filenames = append(filenames, configFile)
  99. }
  100. if len(filenames) == 0 {
  101. log.Fatal(3, "Could not find any config file")
  102. }
  103. return filenames
  104. }
  105. func parseAppUrlAndSubUrl(section *ini.Section) (string, string) {
  106. appUrl := section.Key("root_url").MustString("http://localhost:3000/")
  107. if appUrl[len(appUrl)-1] != '/' {
  108. appUrl += "/"
  109. }
  110. // Check if has app suburl.
  111. url, err := url.Parse(appUrl)
  112. if err != nil {
  113. log.Fatal(4, "Invalid root_url(%s): %s", appUrl, err)
  114. }
  115. appSubUrl := strings.TrimSuffix(url.Path, "/")
  116. return appUrl, appSubUrl
  117. }
  118. func ToAbsUrl(relativeUrl string) string {
  119. return AppUrl + relativeUrl
  120. }
  121. func loadEnvVariableOverrides() {
  122. for _, section := range Cfg.Sections() {
  123. for _, key := range section.Keys() {
  124. sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
  125. keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
  126. envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
  127. envValue := os.Getenv(envKey)
  128. if len(envValue) > 0 {
  129. log.Info("Setting: ENV override found: %s", envKey)
  130. key.SetValue(envValue)
  131. }
  132. }
  133. }
  134. }
  135. func NewConfigContext() {
  136. configFiles := findConfigFiles()
  137. //log.Info("Loading config files: %v", configFiles)
  138. var err error
  139. for i, file := range configFiles {
  140. if i == 0 {
  141. Cfg, err = ini.Load(configFiles[i])
  142. } else {
  143. err = Cfg.Append(configFiles[i])
  144. }
  145. if err != nil {
  146. log.Fatal(4, "Fail to parse config file: %v, error: %v", file, err)
  147. }
  148. }
  149. loadEnvVariableOverrides()
  150. AppName = Cfg.Section("").Key("app_name").MustString("Grafana")
  151. Env = Cfg.Section("").Key("app_mode").MustString("development")
  152. server := Cfg.Section("server")
  153. AppUrl, AppSubUrl = parseAppUrlAndSubUrl(server)
  154. Protocol = HTTP
  155. if server.Key("protocol").MustString("http") == "https" {
  156. Protocol = HTTPS
  157. CertFile = server.Key("cert_file").String()
  158. KeyFile = server.Key("cert_file").String()
  159. }
  160. Domain = server.Key("domain").MustString("localhost")
  161. HttpAddr = server.Key("http_addr").MustString("0.0.0.0")
  162. HttpPort = server.Key("http_port").MustString("3000")
  163. port := os.Getenv("PORT")
  164. if port != "" {
  165. HttpPort = port
  166. }
  167. StaticRootPath = server.Key("static_root_path").MustString(path.Join(WorkDir, "webapp"))
  168. RouterLogging = server.Key("router_logging").MustBool(false)
  169. EnableGzip = server.Key("enable_gzip").MustBool(false)
  170. security := Cfg.Section("security")
  171. SecretKey = security.Key("secret_key").String()
  172. LogInRememberDays = security.Key("login_remember_days").MustInt()
  173. CookieUserName = security.Key("cookie_username").String()
  174. CookieRememberName = security.Key("cookie_remember_name").String()
  175. DisableUserSignUp = security.Key("disable_user_signup").MustBool(false)
  176. // admin
  177. AdminUser = security.Key("admin_user").String()
  178. AdminPassword = security.Key("admin_password").String()
  179. // single account
  180. SingleAccountMode = Cfg.Section("account.single").Key("enabled").MustBool(false)
  181. DefaultAccountName = Cfg.Section("account.single").Key("account_name").MustString("main")
  182. DefaultAccountRole = Cfg.Section("account.single").Key("default_role").In("Editor", []string{"Editor", "Admin", "Viewer"})
  183. // anonymous access
  184. AnonymousEnabled = Cfg.Section("auth.anonymous").Key("enabled").MustBool(false)
  185. AnonymousAccountName = Cfg.Section("auth.anonymous").Key("account_name").String()
  186. AnonymousAccountRole = Cfg.Section("auth.anonymous").Key("account_role").String()
  187. // PhantomJS rendering
  188. ImagesDir = "data/png"
  189. PhantomDir = "vendor/phantomjs"
  190. LogRootPath = Cfg.Section("log").Key("root_path").MustString(path.Join(WorkDir, "/data/log"))
  191. readSessionConfig()
  192. }
  193. func readSessionConfig() {
  194. sec := Cfg.Section("session")
  195. SessionOptions = session.Options{}
  196. SessionOptions.Provider = sec.Key("provider").In("memory", []string{"memory", "file", "redis", "mysql"})
  197. SessionOptions.ProviderConfig = strings.Trim(sec.Key("provider_config").String(), "\" ")
  198. SessionOptions.CookieName = sec.Key("cookie_name").MustString("grafana_sess")
  199. SessionOptions.CookiePath = AppSubUrl
  200. SessionOptions.Secure = sec.Key("cookie_secure").MustBool()
  201. SessionOptions.Gclifetime = Cfg.Section("session").Key("gc_interval_time").MustInt64(86400)
  202. SessionOptions.Maxlifetime = Cfg.Section("session").Key("session_life_time").MustInt64(86400)
  203. if SessionOptions.Provider == "file" {
  204. os.MkdirAll(path.Dir(SessionOptions.ProviderConfig), os.ModePerm)
  205. }
  206. }