server.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package server // import "github.com/docker/docker/api/server"
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/docker/docker/api/server/httpstatus"
  10. "github.com/docker/docker/api/server/httputils"
  11. "github.com/docker/docker/api/server/middleware"
  12. "github.com/docker/docker/api/server/router"
  13. "github.com/docker/docker/api/server/router/debug"
  14. "github.com/docker/docker/dockerversion"
  15. "github.com/gorilla/mux"
  16. "github.com/sirupsen/logrus"
  17. )
  18. // versionMatcher defines a variable matcher to be parsed by the router
  19. // when a request is about to be served.
  20. const versionMatcher = "/v{version:[0-9.]+}"
  21. // Config provides the configuration for the API server
  22. type Config struct {
  23. CorsHeaders string
  24. Version string
  25. SocketGroup string
  26. TLSConfig *tls.Config
  27. // Hosts is a list of addresses for the API to listen on.
  28. Hosts []string
  29. }
  30. // Server contains instance details for the server
  31. type Server struct {
  32. cfg *Config
  33. servers []*HTTPServer
  34. routers []router.Router
  35. middlewares []middleware.Middleware
  36. }
  37. // New returns a new instance of the server based on the specified configuration.
  38. // It allocates resources which will be needed for ServeAPI(ports, unix-sockets).
  39. func New(cfg *Config) *Server {
  40. return &Server{
  41. cfg: cfg,
  42. }
  43. }
  44. // UseMiddleware appends a new middleware to the request chain.
  45. // This needs to be called before the API routes are configured.
  46. func (s *Server) UseMiddleware(m middleware.Middleware) {
  47. s.middlewares = append(s.middlewares, m)
  48. }
  49. // Accept sets a listener the server accepts connections into.
  50. func (s *Server) Accept(addr string, listeners ...net.Listener) {
  51. for _, listener := range listeners {
  52. httpServer := &HTTPServer{
  53. srv: &http.Server{
  54. Addr: addr,
  55. ReadHeaderTimeout: 5 * time.Minute, // "G112: Potential Slowloris Attack (gosec)"; not a real concern for our use, so setting a long timeout.
  56. },
  57. l: listener,
  58. }
  59. s.servers = append(s.servers, httpServer)
  60. }
  61. }
  62. // Close closes servers and thus stop receiving requests
  63. func (s *Server) Close() {
  64. for _, srv := range s.servers {
  65. if err := srv.Close(); err != nil {
  66. logrus.Error(err)
  67. }
  68. }
  69. }
  70. // serveAPI loops through all initialized servers and spawns goroutine
  71. // with Serve method for each. It sets createMux() as Handler also.
  72. func (s *Server) serveAPI() error {
  73. var chErrors = make(chan error, len(s.servers))
  74. for _, srv := range s.servers {
  75. srv.srv.Handler = s.createMux()
  76. go func(srv *HTTPServer) {
  77. var err error
  78. logrus.Infof("API listen on %s", srv.l.Addr())
  79. if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  80. err = nil
  81. }
  82. chErrors <- err
  83. }(srv)
  84. }
  85. for range s.servers {
  86. err := <-chErrors
  87. if err != nil {
  88. return err
  89. }
  90. }
  91. return nil
  92. }
  93. // HTTPServer contains an instance of http server and the listener.
  94. // srv *http.Server, contains configuration to create an http server and a mux router with all api end points.
  95. // l net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
  96. type HTTPServer struct {
  97. srv *http.Server
  98. l net.Listener
  99. }
  100. // Serve starts listening for inbound requests.
  101. func (s *HTTPServer) Serve() error {
  102. return s.srv.Serve(s.l)
  103. }
  104. // Close closes the HTTPServer from listening for the inbound requests.
  105. func (s *HTTPServer) Close() error {
  106. return s.l.Close()
  107. }
  108. func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
  109. return func(w http.ResponseWriter, r *http.Request) {
  110. // Define the context that we'll pass around to share info
  111. // like the docker-request-id.
  112. //
  113. // The 'context' will be used for global data that should
  114. // apply to all requests. Data that is specific to the
  115. // immediate function being called should still be passed
  116. // as 'args' on the function call.
  117. // use intermediate variable to prevent "should not use basic type
  118. // string as key in context.WithValue" golint errors
  119. ctx := context.WithValue(r.Context(), dockerversion.UAStringKey{}, r.Header.Get("User-Agent"))
  120. r = r.WithContext(ctx)
  121. handlerFunc := s.handlerWithGlobalMiddlewares(handler)
  122. vars := mux.Vars(r)
  123. if vars == nil {
  124. vars = make(map[string]string)
  125. }
  126. if err := handlerFunc(ctx, w, r, vars); err != nil {
  127. statusCode := httpstatus.FromError(err)
  128. if statusCode >= 500 {
  129. logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
  130. }
  131. makeErrorHandler(err)(w, r)
  132. }
  133. }
  134. }
  135. // InitRouter initializes the list of routers for the server.
  136. // This method also enables the Go profiler.
  137. func (s *Server) InitRouter(routers ...router.Router) {
  138. s.routers = append(s.routers, routers...)
  139. }
  140. type pageNotFoundError struct{}
  141. func (pageNotFoundError) Error() string {
  142. return "page not found"
  143. }
  144. func (pageNotFoundError) NotFound() {}
  145. // createMux initializes the main router the server uses.
  146. func (s *Server) createMux() *mux.Router {
  147. m := mux.NewRouter()
  148. logrus.Debug("Registering routers")
  149. for _, apiRouter := range s.routers {
  150. for _, r := range apiRouter.Routes() {
  151. f := s.makeHTTPHandler(r.Handler())
  152. logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
  153. m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
  154. m.Path(r.Path()).Methods(r.Method()).Handler(f)
  155. }
  156. }
  157. debugRouter := debug.NewRouter()
  158. s.routers = append(s.routers, debugRouter)
  159. for _, r := range debugRouter.Routes() {
  160. f := s.makeHTTPHandler(r.Handler())
  161. m.Path("/debug" + r.Path()).Handler(f)
  162. }
  163. notFoundHandler := makeErrorHandler(pageNotFoundError{})
  164. m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
  165. m.NotFoundHandler = notFoundHandler
  166. m.MethodNotAllowedHandler = notFoundHandler
  167. return m
  168. }
  169. // Wait blocks the server goroutine until it exits.
  170. // It sends an error message if there is any error during
  171. // the API execution.
  172. func (s *Server) Wait(waitChan chan error) {
  173. if err := s.serveAPI(); err != nil {
  174. logrus.Errorf("ServeAPI error: %v", err)
  175. waitChan <- err
  176. return
  177. }
  178. waitChan <- nil
  179. }