github.com/jwhonce/docker@v0.6.7-0.20190327063223-da823cf3a5a3/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/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.
    22  const versionMatcher = "/v{version:[0-9.]+}"
    23  
    24  // Config provides the configuration for the API server
    25  type 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
    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 range s.servers {
    95  		err := <-chErrors
    96  		if err != nil {
    97  			return err
    98  		}
    99  	}
   100  	return nil
   101  }
   102  
   103  // HTTPServer contains an instance of http server and the listener.
   104  // srv *http.Server, contains configuration to create an http server and a mux router with all api end points.
   105  // l   net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
   106  type HTTPServer struct {
   107  	srv *http.Server
   108  	l   net.Listener
   109  }
   110  
   111  // Serve starts listening for inbound requests.
   112  func (s *HTTPServer) Serve() error {
   113  	return s.srv.Serve(s.l)
   114  }
   115  
   116  // Close closes the HTTPServer from listening for the inbound requests.
   117  func (s *HTTPServer) Close() error {
   118  	return s.l.Close()
   119  }
   120  
   121  func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
   122  	return func(w http.ResponseWriter, r *http.Request) {
   123  		// Define the context that we'll pass around to share info
   124  		// like the docker-request-id.
   125  		//
   126  		// The 'context' will be used for global data that should
   127  		// apply to all requests. Data that is specific to the
   128  		// immediate function being called should still be passed
   129  		// as 'args' on the function call.
   130  
   131  		// use intermediate variable to prevent "should not use basic type
   132  		// string as key in context.WithValue" golint errors
   133  		ctx := context.WithValue(r.Context(), dockerversion.UAStringKey{}, r.Header.Get("User-Agent"))
   134  		r = r.WithContext(ctx)
   135  		handlerFunc := s.handlerWithGlobalMiddlewares(handler)
   136  
   137  		vars := mux.Vars(r)
   138  		if vars == nil {
   139  			vars = make(map[string]string)
   140  		}
   141  
   142  		if err := handlerFunc(ctx, w, r, vars); err != nil {
   143  			statusCode := errdefs.GetHTTPErrorStatusCode(err)
   144  			if statusCode >= 500 {
   145  				logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
   146  			}
   147  			httputils.MakeErrorHandler(err)(w, r)
   148  		}
   149  	}
   150  }
   151  
   152  // InitRouter initializes the list of routers for the server.
   153  // This method also enables the Go profiler.
   154  func (s *Server) InitRouter(routers ...router.Router) {
   155  	s.routers = append(s.routers, routers...)
   156  
   157  	m := s.createMux()
   158  	s.routerSwapper = &routerSwapper{
   159  		router: m,
   160  	}
   161  }
   162  
   163  type pageNotFoundError struct{}
   164  
   165  func (pageNotFoundError) Error() string {
   166  	return "page not found"
   167  }
   168  
   169  func (pageNotFoundError) NotFound() {}
   170  
   171  // createMux initializes the main router the server uses.
   172  func (s *Server) createMux() *mux.Router {
   173  	m := mux.NewRouter()
   174  
   175  	logrus.Debug("Registering routers")
   176  	for _, apiRouter := range s.routers {
   177  		for _, r := range apiRouter.Routes() {
   178  			f := s.makeHTTPHandler(r.Handler())
   179  
   180  			logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
   181  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
   182  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
   183  		}
   184  	}
   185  
   186  	debugRouter := debug.NewRouter()
   187  	s.routers = append(s.routers, debugRouter)
   188  	for _, r := range debugRouter.Routes() {
   189  		f := s.makeHTTPHandler(r.Handler())
   190  		m.Path("/debug" + r.Path()).Handler(f)
   191  	}
   192  
   193  	notFoundHandler := httputils.MakeErrorHandler(pageNotFoundError{})
   194  	m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
   195  	m.NotFoundHandler = notFoundHandler
   196  	m.MethodNotAllowedHandler = notFoundHandler
   197  
   198  	return m
   199  }
   200  
   201  // Wait blocks the server goroutine until it exits.
   202  // It sends an error message if there is any error during
   203  // the API execution.
   204  func (s *Server) Wait(waitChan chan error) {
   205  	if err := s.serveAPI(); err != nil {
   206  		logrus.Errorf("ServeAPI error: %v", err)
   207  		waitChan <- err
   208  		return
   209  	}
   210  	waitChan <- nil
   211  }