http_server.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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.httpSrv.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(listenAddr, 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. srv := &http.Server{
  112. Addr: listenAddr,
  113. Handler: hs.macaron,
  114. TLSConfig: tlsCfg,
  115. TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
  116. }
  117. return srv.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
  118. }
  119. func (hs *HttpServer) newMacaron() *macaron.Macaron {
  120. macaron.Env = setting.Env
  121. m := macaron.New()
  122. m.Use(middleware.Logger())
  123. m.Use(middleware.Recovery())
  124. if setting.EnableGzip {
  125. m.Use(middleware.Gziper())
  126. }
  127. for _, route := range plugins.StaticRoutes {
  128. pluginRoute := path.Join("/public/plugins/", route.PluginId)
  129. logger.Debug("Plugins: Adding route", "route", pluginRoute, "dir", route.Directory)
  130. hs.mapStatic(m, route.Directory, "", pluginRoute)
  131. }
  132. hs.mapStatic(m, setting.StaticRootPath, "", "public")
  133. hs.mapStatic(m, setting.StaticRootPath, "robots.txt", "robots.txt")
  134. m.Use(macaron.Renderer(macaron.RenderOptions{
  135. Directory: path.Join(setting.StaticRootPath, "views"),
  136. IndentJSON: macaron.Env != macaron.PROD,
  137. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  138. }))
  139. m.Use(hs.healthHandler)
  140. m.Use(middleware.GetContextHandler())
  141. m.Use(middleware.Sessioner(&setting.SessionOptions))
  142. m.Use(middleware.RequestMetrics())
  143. m.Use(middleware.OrgRedirect())
  144. // needs to be after context handler
  145. if setting.EnforceDomain {
  146. m.Use(middleware.ValidateHostHeader(setting.Domain))
  147. }
  148. return m
  149. }
  150. func (hs *HttpServer) healthHandler(ctx *macaron.Context) {
  151. if ctx.Req.Method != "GET" || ctx.Req.URL.Path != "/api/health" {
  152. return
  153. }
  154. data := simplejson.New()
  155. data.Set("database", "ok")
  156. data.Set("version", setting.BuildVersion)
  157. data.Set("commit", setting.BuildCommit)
  158. if err := bus.Dispatch(&models.GetDBHealthQuery{}); err != nil {
  159. data.Set("database", "failing")
  160. }
  161. ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
  162. ctx.Resp.WriteHeader(200)
  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. }