github.com/rish1988/moby@v25.0.2+incompatible/api/server/server.go (about)

     1  package server // import "github.com/docker/docker/api/server"
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	"github.com/containerd/log"
     8  	"github.com/docker/docker/api/server/httpstatus"
     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  	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
    16  )
    17  
    18  // versionMatcher defines a variable matcher to be parsed by the router
    19  // when a request is about to be served.
    20  const versionMatcher = "/v{version:[0-9.]+}"
    21  
    22  // Server contains instance details for the server
    23  type Server struct {
    24  	middlewares []middleware.Middleware
    25  }
    26  
    27  // UseMiddleware appends a new middleware to the request chain.
    28  // This needs to be called before the API routes are configured.
    29  func (s *Server) UseMiddleware(m middleware.Middleware) {
    30  	s.middlewares = append(s.middlewares, m)
    31  }
    32  
    33  func (s *Server) makeHTTPHandler(handler httputils.APIFunc, operation string) http.HandlerFunc {
    34  	return otelhttp.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    35  		// Define the context that we'll pass around to share info
    36  		// like the docker-request-id.
    37  		//
    38  		// The 'context' will be used for global data that should
    39  		// apply to all requests. Data that is specific to the
    40  		// immediate function being called should still be passed
    41  		// as 'args' on the function call.
    42  
    43  		// use intermediate variable to prevent "should not use basic type
    44  		// string as key in context.WithValue" golint errors
    45  		ctx := context.WithValue(r.Context(), dockerversion.UAStringKey{}, r.Header.Get("User-Agent"))
    46  
    47  		r = r.WithContext(ctx)
    48  		handlerFunc := s.handlerWithGlobalMiddlewares(handler)
    49  
    50  		vars := mux.Vars(r)
    51  		if vars == nil {
    52  			vars = make(map[string]string)
    53  		}
    54  
    55  		if err := handlerFunc(ctx, w, r, vars); err != nil {
    56  			statusCode := httpstatus.FromError(err)
    57  			if statusCode >= 500 {
    58  				log.G(ctx).Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
    59  			}
    60  			makeErrorHandler(err)(w, r)
    61  		}
    62  	}), operation).ServeHTTP
    63  }
    64  
    65  type pageNotFoundError struct{}
    66  
    67  func (pageNotFoundError) Error() string {
    68  	return "page not found"
    69  }
    70  
    71  func (pageNotFoundError) NotFound() {}
    72  
    73  // CreateMux returns a new mux with all the routers registered.
    74  func (s *Server) CreateMux(routers ...router.Router) *mux.Router {
    75  	m := mux.NewRouter()
    76  
    77  	log.G(context.TODO()).Debug("Registering routers")
    78  	for _, apiRouter := range routers {
    79  		for _, r := range apiRouter.Routes() {
    80  			f := s.makeHTTPHandler(r.Handler(), r.Method()+" "+r.Path())
    81  
    82  			log.G(context.TODO()).Debugf("Registering %s, %s", r.Method(), r.Path())
    83  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
    84  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
    85  		}
    86  	}
    87  
    88  	debugRouter := debug.NewRouter()
    89  	for _, r := range debugRouter.Routes() {
    90  		f := s.makeHTTPHandler(r.Handler(), r.Method()+" "+r.Path())
    91  		m.Path("/debug" + r.Path()).Handler(f)
    92  	}
    93  
    94  	notFoundHandler := makeErrorHandler(pageNotFoundError{})
    95  	m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
    96  	m.NotFoundHandler = notFoundHandler
    97  	m.MethodNotAllowedHandler = notFoundHandler
    98  
    99  	return m
   100  }