http_server.go 8.9 KB

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