http_server.go 11 KB

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