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