http_server.go 9.3 KB

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