http_server.go 7.2 KB

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