http_server.go 9.1 KB

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