server.go 5.7 KB

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