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