http_server.go 8.6 KB

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