github.com/cookieai-jar/moby@v17.12.1-ce-rc2+incompatible/api/server/server.go (about)

     1  package server
     2  
     3  import (
     4  	"crypto/tls"
     5  	"net"
     6  	"net/http"
     7  	"strings"
     8  
     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  	"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  	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  		ctx := context.WithValue(context.Background(), dockerversion.UAStringKey, r.Header.Get("User-Agent"))
   130  		handlerFunc := s.handlerWithGlobalMiddlewares(handler)
   131  
   132  		vars := mux.Vars(r)
   133  		if vars == nil {
   134  			vars = make(map[string]string)
   135  		}
   136  
   137  		if err := handlerFunc(ctx, w, r, vars); err != nil {
   138  			statusCode := httputils.GetHTTPErrorStatusCode(err)
   139  			if statusCode >= 500 {
   140  				logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
   141  			}
   142  			httputils.MakeErrorHandler(err)(w, r)
   143  		}
   144  	}
   145  }
   146  
   147  // InitRouter initializes the list of routers for the server.
   148  // This method also enables the Go profiler if enableProfiler is true.
   149  func (s *Server) InitRouter(routers ...router.Router) {
   150  	s.routers = append(s.routers, routers...)
   151  
   152  	m := s.createMux()
   153  	s.routerSwapper = &routerSwapper{
   154  		router: m,
   155  	}
   156  }
   157  
   158  type pageNotFoundError struct{}
   159  
   160  func (pageNotFoundError) Error() string {
   161  	return "page not found"
   162  }
   163  
   164  func (pageNotFoundError) NotFound() {}
   165  
   166  // createMux initializes the main router the server uses.
   167  func (s *Server) createMux() *mux.Router {
   168  	m := mux.NewRouter()
   169  
   170  	logrus.Debug("Registering routers")
   171  	for _, apiRouter := range s.routers {
   172  		for _, r := range apiRouter.Routes() {
   173  			f := s.makeHTTPHandler(r.Handler())
   174  
   175  			logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
   176  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
   177  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
   178  		}
   179  	}
   180  
   181  	debugRouter := debug.NewRouter()
   182  	s.routers = append(s.routers, debugRouter)
   183  	for _, r := range debugRouter.Routes() {
   184  		f := s.makeHTTPHandler(r.Handler())
   185  		m.Path("/debug" + r.Path()).Handler(f)
   186  	}
   187  
   188  	notFoundHandler := httputils.MakeErrorHandler(pageNotFoundError{})
   189  	m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
   190  	m.NotFoundHandler = 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.
   198  func (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  }