http_server.go 8.1 KB

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