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