github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/api/server/server.go (about) 1 package server // import "github.com/docker/docker/api/server" 2 3 import ( 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/gorilla/mux" 16 "github.com/sirupsen/logrus" 17 ) 18 19 // versionMatcher defines a variable matcher to be parsed by the router 20 // when a request is about to be served. 21 const versionMatcher = "/v{version:[0-9.]+}" 22 23 // Config provides the configuration for the API server 24 type Config struct { 25 Logging bool 26 CorsHeaders string 27 Version string 28 SocketGroup string 29 TLSConfig *tls.Config 30 } 31 32 // Server contains instance details for the server 33 type Server struct { 34 cfg *Config 35 servers []*HTTPServer 36 routers []router.Router 37 routerSwapper *routerSwapper 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). 43 func 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. 51 func (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. 56 func (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 69 func (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. 79 func (s *Server) serveAPI() error { 80 var chErrors = make(chan error, len(s.servers)) 81 for _, srv := range s.servers { 82 srv.srv.Handler = s.routerSwapper 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. 105 type HTTPServer struct { 106 srv *http.Server 107 l net.Listener 108 } 109 110 // Serve starts listening for inbound requests. 111 func (s *HTTPServer) Serve() error { 112 return s.srv.Serve(s.l) 113 } 114 115 // Close closes the HTTPServer from listening for the inbound requests. 116 func (s *HTTPServer) Close() error { 117 return s.l.Close() 118 } 119 120 func (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 var ki interface{} = dockerversion.UAStringKey 133 ctx := context.WithValue(context.Background(), ki, r.Header.Get("User-Agent")) 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 := httputils.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. 153 func (s *Server) InitRouter(routers ...router.Router) { 154 s.routers = append(s.routers, routers...) 155 156 m := s.createMux() 157 s.routerSwapper = &routerSwapper{ 158 router: m, 159 } 160 } 161 162 type pageNotFoundError struct{} 163 164 func (pageNotFoundError) Error() string { 165 return "page not found" 166 } 167 168 func (pageNotFoundError) NotFound() {} 169 170 // createMux initializes the main router the server uses. 171 func (s *Server) createMux() *mux.Router { 172 m := mux.NewRouter() 173 174 logrus.Debug("Registering routers") 175 for _, apiRouter := range s.routers { 176 for _, r := range apiRouter.Routes() { 177 f := s.makeHTTPHandler(r.Handler()) 178 179 logrus.Debugf("Registering %s, %s", r.Method(), r.Path()) 180 m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f) 181 m.Path(r.Path()).Methods(r.Method()).Handler(f) 182 } 183 } 184 185 debugRouter := debug.NewRouter() 186 s.routers = append(s.routers, debugRouter) 187 for _, r := range debugRouter.Routes() { 188 f := s.makeHTTPHandler(r.Handler()) 189 m.Path("/debug" + r.Path()).Handler(f) 190 } 191 192 notFoundHandler := httputils.MakeErrorHandler(pageNotFoundError{}) 193 m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler) 194 m.NotFoundHandler = notFoundHandler 195 196 return m 197 } 198 199 // Wait blocks the server goroutine until it exits. 200 // It sends an error message if there is any error during 201 // the API execution. 202 func (s *Server) Wait(waitChan chan error) { 203 if err := s.serveAPI(); err != nil { 204 logrus.Errorf("ServeAPI error: %v", err) 205 waitChan <- err 206 return 207 } 208 waitChan <- nil 209 }