http_server.go 7.5 KB

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