http_server.go 7.4 KB

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