github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/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 i := 0; i < len(s.servers); i++ {
    96  		err := <-chErrors
    97  		if err != nil {
    98  			return err
    99  		}
   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  		ctx := context.WithValue(context.Background(), dockerversion.UAStringKey, r.Header.Get("User-Agent"))
   133  		handlerFunc := s.handlerWithGlobalMiddlewares(handler)
   134  
   135  		vars := mux.Vars(r)
   136  		if vars == nil {
   137  			vars = make(map[string]string)
   138  		}
   139  
   140  		if err := handlerFunc(ctx, w, r, vars); err != nil {
   141  			logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
   142  			httputils.MakeErrorHandler(err)(w, r)
   143  		}
   144  	}
   145  }
   146  
   147  // InitRouter initializes the list of routers for the server.
   148  // This method also enables the Go profiler if enableProfiler is true.
   149  func (s *Server) InitRouter(enableProfiler bool, routers ...router.Router) {
   150  	s.routers = append(s.routers, routers...)
   151  
   152  	m := s.createMux()
   153  	if enableProfiler {
   154  		profilerSetup(m)
   155  	}
   156  	s.routerSwapper = &routerSwapper{
   157  		router: m,
   158  	}
   159  }
   160  
   161  // createMux initializes the main router the server uses.
   162  func (s *Server) createMux() *mux.Router {
   163  	m := mux.NewRouter()
   164  
   165  	logrus.Debug("Registering routers")
   166  	for _, apiRouter := range s.routers {
   167  		for _, r := range apiRouter.Routes() {
   168  			f := s.makeHTTPHandler(r.Handler())
   169  
   170  			logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
   171  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
   172  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
   173  		}
   174  	}
   175  
   176  	err := errors.NewRequestNotFoundError(fmt.Errorf("page not found"))
   177  	notFoundHandler := httputils.MakeErrorHandler(err)
   178  	m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
   179  	m.NotFoundHandler = notFoundHandler
   180  
   181  	return m
   182  }
   183  
   184  // Wait blocks the server goroutine until it exits.
   185  // It sends an error message if there is any error during
   186  // the API execution.
   187  func (s *Server) Wait(waitChan chan error) {
   188  	if err := s.serveAPI(); err != nil {
   189  		logrus.Errorf("ServeAPI error: %v", err)
   190  		waitChan <- err
   191  		return
   192  	}
   193  	waitChan <- nil
   194  }
   195  
   196  // DisableProfiler reloads the server mux without adding the profiler routes.
   197  func (s *Server) DisableProfiler() {
   198  	s.routerSwapper.Swap(s.createMux())
   199  }
   200  
   201  // EnableProfiler reloads the server mux adding the profiler routes.
   202  func (s *Server) EnableProfiler() {
   203  	m := s.createMux()
   204  	profilerSetup(m)
   205  	s.routerSwapper.Swap(m)
   206  }