http_server.go 8.8 KB

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