http_server.go 5.5 KB

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