http_server.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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/prometheus/client_golang/prometheus"
  13. "github.com/prometheus/client_golang/prometheus/promhttp"
  14. gocache "github.com/patrickmn/go-cache"
  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/setting"
  25. )
  26. type HTTPServer struct {
  27. log log.Logger
  28. macaron *macaron.Macaron
  29. context context.Context
  30. streamManager *live.StreamManager
  31. cache *gocache.Cache
  32. httpSrv *http.Server
  33. }
  34. func NewHTTPServer() *HTTPServer {
  35. return &HTTPServer{
  36. log: log.New("http.server"),
  37. cache: gocache.New(5*time.Minute, 10*time.Minute),
  38. }
  39. }
  40. func (hs *HTTPServer) Start(ctx context.Context) error {
  41. var err error
  42. hs.context = ctx
  43. hs.streamManager = live.NewStreamManager()
  44. hs.macaron = hs.newMacaron()
  45. hs.registerRoutes()
  46. hs.streamManager.Run(ctx)
  47. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  48. hs.log.Info("Initializing HTTP Server", "address", listenAddr, "protocol", setting.Protocol, "subUrl", setting.AppSubUrl, "socket", setting.SocketPath)
  49. hs.httpSrv = &http.Server{Addr: listenAddr, Handler: hs.macaron}
  50. switch setting.Protocol {
  51. case setting.HTTP:
  52. err = hs.httpSrv.ListenAndServe()
  53. if err == http.ErrServerClosed {
  54. hs.log.Debug("server was shutdown gracefully")
  55. return nil
  56. }
  57. case setting.HTTPS:
  58. err = hs.listenAndServeTLS(setting.CertFile, setting.KeyFile)
  59. if err == http.ErrServerClosed {
  60. hs.log.Debug("server was shutdown gracefully")
  61. return nil
  62. }
  63. case setting.SOCKET:
  64. ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: setting.SocketPath, Net: "unix"})
  65. if err != nil {
  66. hs.log.Debug("server was shutdown gracefully")
  67. return nil
  68. }
  69. // Make socket writable by group
  70. os.Chmod(setting.SocketPath, 0660)
  71. err = hs.httpSrv.Serve(ln)
  72. if err != nil {
  73. hs.log.Debug("server was shutdown gracefully")
  74. return nil
  75. }
  76. default:
  77. hs.log.Error("Invalid protocol", "protocol", setting.Protocol)
  78. err = errors.New("Invalid Protocol")
  79. }
  80. return err
  81. }
  82. func (hs *HTTPServer) Shutdown(ctx context.Context) error {
  83. err := hs.httpSrv.Shutdown(ctx)
  84. hs.log.Info("Stopped HTTP server")
  85. return err
  86. }
  87. func (hs *HTTPServer) listenAndServeTLS(certfile, keyfile string) error {
  88. if certfile == "" {
  89. return fmt.Errorf("cert_file cannot be empty when using HTTPS")
  90. }
  91. if keyfile == "" {
  92. return fmt.Errorf("cert_key cannot be empty when using HTTPS")
  93. }
  94. if _, err := os.Stat(setting.CertFile); os.IsNotExist(err) {
  95. return fmt.Errorf(`Cannot find SSL cert_file at %v`, setting.CertFile)
  96. }
  97. if _, err := os.Stat(setting.KeyFile); os.IsNotExist(err) {
  98. return fmt.Errorf(`Cannot find SSL key_file at %v`, setting.KeyFile)
  99. }
  100. tlsCfg := &tls.Config{
  101. MinVersion: tls.VersionTLS12,
  102. PreferServerCipherSuites: true,
  103. CipherSuites: []uint16{
  104. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  105. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  106. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  107. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  108. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  109. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  110. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  111. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  112. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  113. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  114. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  115. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  116. },
  117. }
  118. hs.httpSrv.TLSConfig = tlsCfg
  119. hs.httpSrv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
  120. return hs.httpSrv.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  121. }
  122. func (hs *HTTPServer) newMacaron() *macaron.Macaron {
  123. macaron.Env = setting.Env
  124. m := macaron.New()
  125. m.Use(middleware.Logger())
  126. if setting.EnableGzip {
  127. m.Use(middleware.Gziper())
  128. }
  129. m.Use(middleware.Recovery())
  130. for _, route := range plugins.StaticRoutes {
  131. pluginRoute := path.Join("/public/plugins/", route.PluginId)
  132. hs.log.Debug("Plugins: Adding route", "route", pluginRoute, "dir", route.Directory)
  133. hs.mapStatic(m, route.Directory, "", pluginRoute)
  134. }
  135. hs.mapStatic(m, setting.StaticRootPath, "", "public")
  136. hs.mapStatic(m, setting.StaticRootPath, "robots.txt", "robots.txt")
  137. if setting.ImageUploadProvider == "local" {
  138. hs.mapStatic(m, setting.ImagesDir, "", "/public/img/attachments")
  139. }
  140. m.Use(macaron.Renderer(macaron.RenderOptions{
  141. Directory: path.Join(setting.StaticRootPath, "views"),
  142. IndentJSON: macaron.Env != macaron.PROD,
  143. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  144. }))
  145. m.Use(hs.healthHandler)
  146. m.Use(hs.metricsEndpoint)
  147. m.Use(middleware.GetContextHandler())
  148. m.Use(middleware.Sessioner(&setting.SessionOptions, setting.SessionConnMaxLifetime))
  149. m.Use(middleware.OrgRedirect())
  150. // needs to be after context handler
  151. if setting.EnforceDomain {
  152. m.Use(middleware.ValidateHostHeader(setting.Domain))
  153. }
  154. m.Use(middleware.AddDefaultResponseHeaders())
  155. return m
  156. }
  157. func (hs *HTTPServer) metricsEndpoint(ctx *macaron.Context) {
  158. if ctx.Req.Method != "GET" || ctx.Req.URL.Path != "/metrics" {
  159. return
  160. }
  161. promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}).
  162. ServeHTTP(ctx.Resp, ctx.Req.Request)
  163. }
  164. func (hs *HTTPServer) healthHandler(ctx *macaron.Context) {
  165. notHeadOrGet := ctx.Req.Method != http.MethodGet && ctx.Req.Method != http.MethodHead
  166. if notHeadOrGet || ctx.Req.URL.Path != "/api/health" {
  167. return
  168. }
  169. data := simplejson.New()
  170. data.Set("database", "ok")
  171. data.Set("version", setting.BuildVersion)
  172. data.Set("commit", setting.BuildCommit)
  173. if err := bus.Dispatch(&models.GetDBHealthQuery{}); err != nil {
  174. data.Set("database", "failing")
  175. ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
  176. ctx.Resp.WriteHeader(503)
  177. } else {
  178. ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
  179. ctx.Resp.WriteHeader(200)
  180. }
  181. dataBytes, _ := data.EncodePretty()
  182. ctx.Resp.Write(dataBytes)
  183. }
  184. func (hs *HTTPServer) mapStatic(m *macaron.Macaron, rootDir string, dir string, prefix string) {
  185. headers := func(c *macaron.Context) {
  186. c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
  187. }
  188. if setting.Env == setting.DEV {
  189. headers = func(c *macaron.Context) {
  190. c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
  191. }
  192. }
  193. m.Use(httpstatic.Static(
  194. path.Join(rootDir, dir),
  195. httpstatic.StaticOptions{
  196. SkipLogging: true,
  197. Prefix: prefix,
  198. AddHeaders: headers,
  199. },
  200. ))
  201. }