http_server.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package api
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "os"
  9. "path"
  10. macaron "gopkg.in/macaron.v1"
  11. "github.com/grafana/grafana/pkg/api/live"
  12. httpstatic "github.com/grafana/grafana/pkg/api/static"
  13. "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
  14. "github.com/grafana/grafana/pkg/log"
  15. "github.com/grafana/grafana/pkg/middleware"
  16. "github.com/grafana/grafana/pkg/plugins"
  17. "github.com/grafana/grafana/pkg/setting"
  18. )
  19. type HttpServer struct {
  20. log log.Logger
  21. macaron *macaron.Macaron
  22. context context.Context
  23. streamManager *live.StreamManager
  24. httpSrv *http.Server
  25. }
  26. func NewHttpServer() *HttpServer {
  27. return &HttpServer{
  28. log: log.New("http.server"),
  29. }
  30. }
  31. func (hs *HttpServer) Start(ctx context.Context) error {
  32. var err error
  33. hs.context = ctx
  34. hs.streamManager = live.NewStreamManager()
  35. hs.macaron = hs.newMacaron()
  36. hs.registerRoutes()
  37. hs.streamManager.Run(ctx)
  38. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  39. hs.log.Info("Initializing HTTP Server", "address", listenAddr, "protocol", setting.Protocol, "subUrl", setting.AppSubUrl)
  40. hs.httpSrv = &http.Server{Addr: listenAddr, Handler: hs.macaron}
  41. switch setting.Protocol {
  42. case setting.HTTP:
  43. err = hs.httpSrv.ListenAndServe()
  44. if err == http.ErrServerClosed {
  45. hs.log.Debug("server was shutdown gracefully")
  46. return nil
  47. }
  48. case setting.HTTPS:
  49. err = hs.httpSrv.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  50. if err == http.ErrServerClosed {
  51. hs.log.Debug("server was shutdown gracefully")
  52. return nil
  53. }
  54. default:
  55. hs.log.Error("Invalid protocol", "protocol", setting.Protocol)
  56. err = errors.New("Invalid Protocol")
  57. }
  58. return err
  59. }
  60. func (hs *HttpServer) Shutdown(ctx context.Context) error {
  61. err := hs.httpSrv.Shutdown(ctx)
  62. hs.log.Info("stopped http server")
  63. return err
  64. }
  65. func (hs *HttpServer) listenAndServeTLS(listenAddr, certfile, keyfile string) error {
  66. if certfile == "" {
  67. return fmt.Errorf("cert_file cannot be empty when using HTTPS")
  68. }
  69. if keyfile == "" {
  70. return fmt.Errorf("cert_key cannot be empty when using HTTPS")
  71. }
  72. if _, err := os.Stat(setting.CertFile); os.IsNotExist(err) {
  73. return fmt.Errorf(`Cannot find SSL cert_file at %v`, setting.CertFile)
  74. }
  75. if _, err := os.Stat(setting.KeyFile); os.IsNotExist(err) {
  76. return fmt.Errorf(`Cannot find SSL key_file at %v`, setting.KeyFile)
  77. }
  78. tlsCfg := &tls.Config{
  79. MinVersion: tls.VersionTLS12,
  80. PreferServerCipherSuites: true,
  81. CipherSuites: []uint16{
  82. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  83. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  84. tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  85. tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  86. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  87. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  88. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  89. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  90. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  91. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  92. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  93. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  94. },
  95. }
  96. srv := &http.Server{
  97. Addr: listenAddr,
  98. Handler: hs.macaron,
  99. TLSConfig: tlsCfg,
  100. TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
  101. }
  102. return srv.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  103. }
  104. func (hs *HttpServer) newMacaron() *macaron.Macaron {
  105. macaron.Env = setting.Env
  106. m := macaron.New()
  107. m.Use(middleware.Logger())
  108. m.Use(middleware.Recovery())
  109. if setting.EnableGzip {
  110. m.Use(middleware.Gziper())
  111. }
  112. for _, route := range plugins.StaticRoutes {
  113. pluginRoute := path.Join("/public/plugins/", route.PluginId)
  114. logger.Debug("Plugins: Adding route", "route", pluginRoute, "dir", route.Directory)
  115. hs.mapStatic(m, route.Directory, "", pluginRoute)
  116. }
  117. hs.mapStatic(m, setting.StaticRootPath, "", "public")
  118. hs.mapStatic(m, setting.StaticRootPath, "robots.txt", "robots.txt")
  119. m.Use(macaron.Renderer(macaron.RenderOptions{
  120. Directory: path.Join(setting.StaticRootPath, "views"),
  121. IndentJSON: macaron.Env != macaron.PROD,
  122. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  123. }))
  124. m.Use(middleware.GetContextHandler())
  125. m.Use(middleware.Sessioner(&setting.SessionOptions))
  126. m.Use(middleware.RequestMetrics())
  127. m.Use(middleware.OrgRedirect())
  128. // needs to be after context handler
  129. if setting.EnforceDomain {
  130. m.Use(middleware.ValidateHostHeader(setting.Domain))
  131. }
  132. return m
  133. }
  134. func (hs *HttpServer) mapStatic(m *macaron.Macaron, rootDir string, dir string, prefix string) {
  135. headers := func(c *macaron.Context) {
  136. c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
  137. }
  138. if setting.Env == setting.DEV {
  139. headers = func(c *macaron.Context) {
  140. c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
  141. }
  142. }
  143. m.Use(httpstatic.Static(
  144. path.Join(rootDir, dir),
  145. httpstatic.StaticOptions{
  146. SkipLogging: true,
  147. Prefix: prefix,
  148. AddHeaders: headers,
  149. },
  150. ))
  151. }