http_server.go 6.3 KB

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