http_server.go 4.4 KB

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