http_server.go 6.0 KB

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