http_server.go 7.4 KB

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