http_server.go 8.3 KB

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