server.go 5.7 KB

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