http_server.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package api
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "os"
  10. "path"
  11. "time"
  12. "github.com/grafana/grafana/pkg/api/live"
  13. "github.com/grafana/grafana/pkg/api/routing"
  14. httpstatic "github.com/grafana/grafana/pkg/api/static"
  15. "github.com/grafana/grafana/pkg/bus"
  16. "github.com/grafana/grafana/pkg/components/simplejson"
  17. "github.com/grafana/grafana/pkg/infra/localcache"
  18. "github.com/grafana/grafana/pkg/infra/log"
  19. "github.com/grafana/grafana/pkg/infra/remotecache"
  20. "github.com/grafana/grafana/pkg/middleware"
  21. "github.com/grafana/grafana/pkg/models"
  22. "github.com/grafana/grafana/pkg/plugins"
  23. "github.com/grafana/grafana/pkg/registry"
  24. "github.com/grafana/grafana/pkg/services/datasources"
  25. "github.com/grafana/grafana/pkg/services/hooks"
  26. "github.com/grafana/grafana/pkg/services/login"
  27. "github.com/grafana/grafana/pkg/services/quota"
  28. "github.com/grafana/grafana/pkg/services/rendering"
  29. "github.com/grafana/grafana/pkg/setting"
  30. "github.com/prometheus/client_golang/prometheus"
  31. "github.com/prometheus/client_golang/prometheus/promhttp"
  32. macaron "gopkg.in/macaron.v1"
  33. )
  34. func init() {
  35. registry.Register(&registry.Descriptor{
  36. Name: "HTTPServer",
  37. Instance: &HTTPServer{},
  38. InitPriority: registry.High,
  39. })
  40. }
  41. type ProvisioningService interface {
  42. ProvisionDatasources() error
  43. ProvisionNotifications() error
  44. ProvisionDashboards() error
  45. GetDashboardProvisionerResolvedPath(name string) string
  46. }
  47. type HTTPServer struct {
  48. log log.Logger
  49. macaron *macaron.Macaron
  50. context context.Context
  51. streamManager *live.StreamManager
  52. httpSrv *http.Server
  53. RouteRegister routing.RouteRegister `inject:""`
  54. Bus bus.Bus `inject:""`
  55. RenderService rendering.Service `inject:""`
  56. Cfg *setting.Cfg `inject:""`
  57. HooksService *hooks.HooksService `inject:""`
  58. CacheService *localcache.CacheService `inject:""`
  59. DatasourceCache datasources.CacheService `inject:""`
  60. AuthTokenService models.UserTokenService `inject:""`
  61. QuotaService *quota.QuotaService `inject:""`
  62. RemoteCacheService *remotecache.RemoteCache `inject:""`
  63. ProvisioningService ProvisioningService `inject:""`
  64. Login *login.LoginService `inject:""`
  65. }
  66. func (hs *HTTPServer) Init() error {
  67. hs.log = log.New("http.server")
  68. hs.streamManager = live.NewStreamManager()
  69. hs.macaron = hs.newMacaron()
  70. hs.registerRoutes()
  71. return nil
  72. }
  73. func (hs *HTTPServer) Run(ctx context.Context) error {
  74. var err error
  75. hs.context = ctx
  76. hs.applyRoutes()
  77. hs.streamManager.Run(ctx)
  78. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  79. hs.log.Info("HTTP Server Listen", "address", listenAddr, "protocol", setting.Protocol, "subUrl", setting.AppSubUrl, "socket", setting.SocketPath)
  80. hs.httpSrv = &http.Server{Addr: listenAddr, Handler: hs.macaron}
  81. // handle http shutdown on server context done
  82. go func() {
  83. <-ctx.Done()
  84. // Hacky fix for race condition between ListenAndServe and Shutdown
  85. time.Sleep(time.Millisecond * 100)
  86. if err := hs.httpSrv.Shutdown(context.Background()); err != nil {
  87. hs.log.Error("Failed to shutdown server", "error", err)
  88. }
  89. }()
  90. switch setting.Protocol {
  91. case setting.HTTP:
  92. err = hs.httpSrv.ListenAndServe()
  93. if err == http.ErrServerClosed {
  94. hs.log.Debug("server was shutdown gracefully")
  95. return nil
  96. }
  97. case setting.HTTPS:
  98. err = hs.listenAndServeTLS(setting.CertFile, setting.KeyFile)
  99. if err == http.ErrServerClosed {
  100. hs.log.Debug("server was shutdown gracefully")
  101. return nil
  102. }
  103. case setting.SOCKET:
  104. ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: setting.SocketPath, Net: "unix"})
  105. if err != nil {
  106. hs.log.Debug("server was shutdown gracefully")
  107. return nil
  108. }
  109. // Make socket writable by group
  110. os.Chmod(setting.SocketPath, 0660)
  111. err = hs.httpSrv.Serve(ln)
  112. if err != nil {
  113. hs.log.Debug("server was shutdown gracefully")
  114. return nil
  115. }
  116. default:
  117. hs.log.Error("Invalid protocol", "protocol", setting.Protocol)
  118. err = errors.New("Invalid Protocol")
  119. }
  120. return err
  121. }
  122. func (hs *HTTPServer) listenAndServeTLS(certfile, keyfile string) error {
  123. if certfile == "" {
  124. return fmt.Errorf("cert_file cannot be empty when using HTTPS")
  125. }
  126. if keyfile == "" {
  127. return fmt.Errorf("cert_key cannot be empty when using HTTPS")
  128. }
  129. if _, err := os.Stat(setting.CertFile); os.IsNotExist(err) {
  130. return fmt.Errorf(`Cannot find SSL cert_file at %v`, setting.CertFile)
  131. }
  132. if _, err := os.Stat(setting.KeyFile); os.IsNotExist(err) {
  133. return fmt.Errorf(`Cannot find SSL key_file at %v`, setting.KeyFile)
  134. }
  135. tlsCfg := &tls.Config{
  136. MinVersion: tls.VersionTLS12,
  137. PreferServerCipherSuites: true,
  138. CipherSuites: []uint16{
  139. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  140. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  141. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  142. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  143. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  144. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  145. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  146. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  147. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  148. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  149. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  150. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  151. },
  152. }
  153. hs.httpSrv.TLSConfig = tlsCfg
  154. hs.httpSrv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
  155. return hs.httpSrv.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  156. }
  157. func (hs *HTTPServer) newMacaron() *macaron.Macaron {
  158. macaron.Env = setting.Env
  159. m := macaron.New()
  160. // automatically set HEAD for every GET
  161. m.SetAutoHead(true)
  162. return m
  163. }
  164. func (hs *HTTPServer) applyRoutes() {
  165. // start with middlewares & static routes
  166. hs.addMiddlewaresAndStaticRoutes()
  167. // then add view routes & api routes
  168. hs.RouteRegister.Register(hs.macaron)
  169. // then custom app proxy routes
  170. hs.initAppPluginRoutes(hs.macaron)
  171. // lastly not found route
  172. hs.macaron.NotFound(hs.NotFoundHandler)
  173. }
  174. func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() {
  175. m := hs.macaron
  176. m.Use(middleware.Logger())
  177. if setting.EnableGzip {
  178. m.Use(middleware.Gziper())
  179. }
  180. m.Use(middleware.Recovery())
  181. for _, route := range plugins.StaticRoutes {
  182. pluginRoute := path.Join("/public/plugins/", route.PluginId)
  183. hs.log.Debug("Plugins: Adding route", "route", pluginRoute, "dir", route.Directory)
  184. hs.mapStatic(hs.macaron, route.Directory, "", pluginRoute)
  185. }
  186. hs.mapStatic(m, setting.StaticRootPath, "build", "public/build")
  187. hs.mapStatic(m, setting.StaticRootPath, "", "public")
  188. hs.mapStatic(m, setting.StaticRootPath, "robots.txt", "robots.txt")
  189. if setting.ImageUploadProvider == "local" {
  190. hs.mapStatic(m, hs.Cfg.ImagesDir, "", "/public/img/attachments")
  191. }
  192. m.Use(middleware.AddDefaultResponseHeaders())
  193. if setting.ServeFromSubPath && setting.AppSubUrl != "" {
  194. m.SetURLPrefix(setting.AppSubUrl)
  195. }
  196. m.Use(macaron.Renderer(macaron.RenderOptions{
  197. Directory: path.Join(setting.StaticRootPath, "views"),
  198. IndentJSON: macaron.Env != macaron.PROD,
  199. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  200. }))
  201. m.Use(hs.healthHandler)
  202. m.Use(hs.metricsEndpoint)
  203. m.Use(middleware.GetContextHandler(
  204. hs.AuthTokenService,
  205. hs.RemoteCacheService,
  206. ))
  207. m.Use(middleware.OrgRedirect())
  208. // needs to be after context handler
  209. if setting.EnforceDomain {
  210. m.Use(middleware.ValidateHostHeader(setting.Domain))
  211. }
  212. m.Use(middleware.HandleNoCacheHeader())
  213. }
  214. func (hs *HTTPServer) metricsEndpoint(ctx *macaron.Context) {
  215. if !hs.Cfg.MetricsEndpointEnabled {
  216. return
  217. }
  218. if ctx.Req.Method != http.MethodGet || ctx.Req.URL.Path != "/metrics" {
  219. return
  220. }
  221. if hs.metricsEndpointBasicAuthEnabled() && !BasicAuthenticatedRequest(ctx.Req, hs.Cfg.MetricsEndpointBasicAuthUsername, hs.Cfg.MetricsEndpointBasicAuthPassword) {
  222. ctx.Resp.WriteHeader(http.StatusUnauthorized)
  223. return
  224. }
  225. promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}).
  226. ServeHTTP(ctx.Resp, ctx.Req.Request)
  227. }
  228. func (hs *HTTPServer) healthHandler(ctx *macaron.Context) {
  229. notHeadOrGet := ctx.Req.Method != http.MethodGet && ctx.Req.Method != http.MethodHead
  230. if notHeadOrGet || ctx.Req.URL.Path != "/api/health" {
  231. return
  232. }
  233. data := simplejson.New()
  234. data.Set("database", "ok")
  235. data.Set("version", setting.BuildVersion)
  236. data.Set("commit", setting.BuildCommit)
  237. if err := bus.Dispatch(&models.GetDBHealthQuery{}); err != nil {
  238. data.Set("database", "failing")
  239. ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
  240. ctx.Resp.WriteHeader(503)
  241. } else {
  242. ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
  243. ctx.Resp.WriteHeader(200)
  244. }
  245. dataBytes, _ := data.EncodePretty()
  246. ctx.Resp.Write(dataBytes)
  247. }
  248. func (hs *HTTPServer) mapStatic(m *macaron.Macaron, rootDir string, dir string, prefix string) {
  249. headers := func(c *macaron.Context) {
  250. c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
  251. }
  252. if prefix == "public/build" {
  253. headers = func(c *macaron.Context) {
  254. c.Resp.Header().Set("Cache-Control", "public, max-age=31536000")
  255. }
  256. }
  257. if setting.Env == setting.DEV {
  258. headers = func(c *macaron.Context) {
  259. c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
  260. }
  261. }
  262. m.Use(httpstatic.Static(
  263. path.Join(rootDir, dir),
  264. httpstatic.StaticOptions{
  265. SkipLogging: true,
  266. Prefix: prefix,
  267. AddHeaders: headers,
  268. },
  269. ))
  270. }
  271. func (hs *HTTPServer) metricsEndpointBasicAuthEnabled() bool {
  272. return hs.Cfg.MetricsEndpointBasicAuthUsername != "" && hs.Cfg.MetricsEndpointBasicAuthPassword != ""
  273. }