http_server.go 5.9 KB

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