github.com/olljanat/moby@v1.13.1/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 an 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  			statusCode := httputils.GetHTTPErrorStatusCode(err)
   141  			errFormat := "%v"
   142  			if statusCode == http.StatusInternalServerError {
   143  				errFormat = "%+v"
   144  			}
   145  			logrus.Errorf("Handler for %s %s returned error: "+errFormat, r.Method, r.URL.Path, err)
   146  			httputils.MakeErrorHandler(err)(w, r)
   147  		}
   148  	}
   149  }
   150  
   151  // InitRouter initializes the list of routers for the server.
   152  // This method also enables the Go profiler if enableProfiler is true.
   153  func (s *Server) InitRouter(enableProfiler bool, routers ...router.Router) {
   154  	s.routers = append(s.routers, routers...)
   155  
   156  	m := s.createMux()
   157  	if enableProfiler {
   158  		profilerSetup(m)
   159  	}
   160  	s.routerSwapper = &routerSwapper{
   161  		router: m,
   162  	}
   163  }
   164  
   165  // createMux initializes the main router the server uses.
   166  func (s *Server) createMux() *mux.Router {
   167  	m := mux.NewRouter()
   168  
   169  	logrus.Debug("Registering routers")
   170  	for _, apiRouter := range s.routers {
   171  		for _, r := range apiRouter.Routes() {
   172  			f := s.makeHTTPHandler(r.Handler())
   173  
   174  			logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
   175  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
   176  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
   177  		}
   178  	}
   179  
   180  	err := errors.NewRequestNotFoundError(fmt.Errorf("page not found"))
   181  	notFoundHandler := httputils.MakeErrorHandler(err)
   182  	m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
   183  	m.NotFoundHandler = notFoundHandler
   184  
   185  	return m
   186  }
   187  
   188  // Wait blocks the server goroutine until it exits.
   189  // It sends an error message if there is any error during
   190  // the API execution.
   191  func (s *Server) Wait(waitChan chan error) {
   192  	if err := s.serveAPI(); err != nil {
   193  		logrus.Errorf("ServeAPI error: %v", err)
   194  		waitChan <- err
   195  		return
   196  	}
   197  	waitChan <- nil
   198  }
   199  
   200  // DisableProfiler reloads the server mux without adding the profiler routes.
   201  func (s *Server) DisableProfiler() {
   202  	s.routerSwapper.Swap(s.createMux())
   203  }
   204  
   205  // EnableProfiler reloads the server mux adding the profiler routes.
   206  func (s *Server) EnableProfiler() {
   207  	m := s.createMux()
   208  	profilerSetup(m)
   209  	s.routerSwapper.Swap(m)
   210  }