github.com/jiasir/docker@v1.3.3-0.20170609024000-252e610103e7/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/docker/docker/dockerversion"
    16  	"github.com/gorilla/mux"
    17  	"golang.org/x/net/context"
    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  	EnableCors  bool
    28  	CorsHeaders string
    29  	Version     string
    30  	SocketGroup string
    31  	TLSConfig   *tls.Config
    32  }
    33  
    34  // Server contains instance details for the server
    35  type Server struct {
    36  	cfg           *Config
    37  	servers       []*HTTPServer
    38  	routers       []router.Router
    39  	routerSwapper *routerSwapper
    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  			},
    64  			l: listener,
    65  		}
    66  		s.servers = append(s.servers, httpServer)
    67  	}
    68  }
    69  
    70  // Close closes servers and thus stop receiving requests
    71  func (s *Server) Close() {
    72  	for _, srv := range s.servers {
    73  		if err := srv.Close(); err != nil {
    74  			logrus.Error(err)
    75  		}
    76  	}
    77  }
    78  
    79  // serveAPI loops through all initialized servers and spawns goroutine
    80  // with Serve method for each. It sets createMux() as Handler also.
    81  func (s *Server) serveAPI() error {
    82  	var chErrors = make(chan error, len(s.servers))
    83  	for _, srv := range s.servers {
    84  		srv.srv.Handler = s.routerSwapper
    85  		go func(srv *HTTPServer) {
    86  			var err error
    87  			logrus.Infof("API listen on %s", srv.l.Addr())
    88  			if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
    89  				err = nil
    90  			}
    91  			chErrors <- err
    92  		}(srv)
    93  	}
    94  
    95  	for range s.servers {
    96  		err := <-chErrors
    97  		if err != nil {
    98  			return err
    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(), dockerversion.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  			if statusCode >= 500 {
   142  				logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
   143  			}
   144  			httputils.MakeErrorHandler(err)(w, r)
   145  		}
   146  	}
   147  }
   148  
   149  // InitRouter initializes the list of routers for the server.
   150  // This method also enables the Go profiler if enableProfiler is true.
   151  func (s *Server) InitRouter(enableProfiler bool, routers ...router.Router) {
   152  	s.routers = append(s.routers, routers...)
   153  
   154  	m := s.createMux()
   155  	if enableProfiler {
   156  		profilerSetup(m)
   157  	}
   158  	s.routerSwapper = &routerSwapper{
   159  		router: m,
   160  	}
   161  }
   162  
   163  // createMux initializes the main router the server uses.
   164  func (s *Server) createMux() *mux.Router {
   165  	m := mux.NewRouter()
   166  
   167  	logrus.Debug("Registering routers")
   168  	for _, apiRouter := range s.routers {
   169  		for _, r := range apiRouter.Routes() {
   170  			f := s.makeHTTPHandler(r.Handler())
   171  
   172  			logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
   173  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
   174  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
   175  		}
   176  	}
   177  
   178  	err := errors.NewRequestNotFoundError(fmt.Errorf("page not found"))
   179  	notFoundHandler := httputils.MakeErrorHandler(err)
   180  	m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
   181  	m.NotFoundHandler = notFoundHandler
   182  
   183  	return m
   184  }
   185  
   186  // Wait blocks the server goroutine until it exits.
   187  // It sends an error message if there is any error during
   188  // the API execution.
   189  func (s *Server) Wait(waitChan chan error) {
   190  	if err := s.serveAPI(); err != nil {
   191  		logrus.Errorf("ServeAPI error: %v", err)
   192  		waitChan <- err
   193  		return
   194  	}
   195  	waitChan <- nil
   196  }
   197  
   198  // DisableProfiler reloads the server mux without adding the profiler routes.
   199  func (s *Server) DisableProfiler() {
   200  	s.routerSwapper.Swap(s.createMux())
   201  }
   202  
   203  // EnableProfiler reloads the server mux adding the profiler routes.
   204  func (s *Server) EnableProfiler() {
   205  	m := s.createMux()
   206  	profilerSetup(m)
   207  	s.routerSwapper.Swap(m)
   208  }