http_server.go 6.4 KB

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