github.com/boynux/docker@v1.11.0-rc4/api/server/server.go (about)

     1  package server
     2  
     3  import (
     4  	"crypto/tls"
     5  	"net"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/Sirupsen/logrus"
    10  	"github.com/docker/docker/api/server/httputils"
    11  	"github.com/docker/docker/api/server/router"
    12  	"github.com/docker/docker/pkg/authorization"
    13  	"github.com/gorilla/mux"
    14  	"golang.org/x/net/context"
    15  )
    16  
    17  // versionMatcher defines a variable matcher to be parsed by the router
    18  // when a request is about to be served.
    19  const versionMatcher = "/v{version:[0-9.]+}"
    20  
    21  // Config provides the configuration for the API server
    22  type Config struct {
    23  	Logging                  bool
    24  	EnableCors               bool
    25  	CorsHeaders              string
    26  	AuthorizationPluginNames []string
    27  	Version                  string
    28  	SocketGroup              string
    29  	TLSConfig                *tls.Config
    30  }
    31  
    32  // Server contains instance details for the server
    33  type Server struct {
    34  	cfg           *Config
    35  	servers       []*HTTPServer
    36  	routers       []router.Router
    37  	authZPlugins  []authorization.Plugin
    38  	routerSwapper *routerSwapper
    39  }
    40  
    41  // New returns a new instance of the server based on the specified configuration.
    42  // It allocates resources which will be needed for ServeAPI(ports, unix-sockets).
    43  func New(cfg *Config) *Server {
    44  	return &Server{
    45  		cfg: cfg,
    46  	}
    47  }
    48  
    49  // Accept sets a listener the server accepts connections into.
    50  func (s *Server) Accept(addr string, listeners ...net.Listener) {
    51  	for _, listener := range listeners {
    52  		httpServer := &HTTPServer{
    53  			srv: &http.Server{
    54  				Addr: addr,
    55  			},
    56  			l: listener,
    57  		}
    58  		s.servers = append(s.servers, httpServer)
    59  	}
    60  }
    61  
    62  // Close closes servers and thus stop receiving requests
    63  func (s *Server) Close() {
    64  	for _, srv := range s.servers {
    65  		if err := srv.Close(); err != nil {
    66  			logrus.Error(err)
    67  		}
    68  	}
    69  }
    70  
    71  // serveAPI loops through all initialized servers and spawns goroutine
    72  // with Server method for each. It sets createMux() as Handler also.
    73  func (s *Server) serveAPI() error {
    74  	var chErrors = make(chan error, len(s.servers))
    75  	for _, srv := range s.servers {
    76  		srv.srv.Handler = s.routerSwapper
    77  		go func(srv *HTTPServer) {
    78  			var err error
    79  			logrus.Infof("API listen on %s", srv.l.Addr())
    80  			if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
    81  				err = nil
    82  			}
    83  			chErrors <- err
    84  		}(srv)
    85  	}
    86  
    87  	for i := 0; i < len(s.servers); i++ {
    88  		err := <-chErrors
    89  		if err != nil {
    90  			return err
    91  		}
    92  	}
    93  
    94  	return nil
    95  }
    96  
    97  // HTTPServer contains an instance of http server and the listener.
    98  // srv *http.Server, contains configuration to create a http server and a mux router with all api end points.
    99  // l   net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
   100  type HTTPServer struct {
   101  	srv *http.Server
   102  	l   net.Listener
   103  }
   104  
   105  // Serve starts listening for inbound requests.
   106  func (s *HTTPServer) Serve() error {
   107  	return s.srv.Serve(s.l)
   108  }
   109  
   110  // Close closes the HTTPServer from listening for the inbound requests.
   111  func (s *HTTPServer) Close() error {
   112  	return s.l.Close()
   113  }
   114  
   115  func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
   116  	return func(w http.ResponseWriter, r *http.Request) {
   117  		// Define the context that we'll pass around to share info
   118  		// like the docker-request-id.
   119  		//
   120  		// The 'context' will be used for global data that should
   121  		// apply to all requests. Data that is specific to the
   122  		// immediate function being called should still be passed
   123  		// as 'args' on the function call.
   124  		ctx := context.Background()
   125  		handlerFunc := s.handleWithGlobalMiddlewares(handler)
   126  
   127  		vars := mux.Vars(r)
   128  		if vars == nil {
   129  			vars = make(map[string]string)
   130  		}
   131  
   132  		if err := handlerFunc(ctx, w, r, vars); err != nil {
   133  			logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
   134  			httputils.WriteError(w, err)
   135  		}
   136  	}
   137  }
   138  
   139  // InitRouter initializes the list of routers for the server.
   140  // This method also enables the Go profiler if enableProfiler is true.
   141  func (s *Server) InitRouter(enableProfiler bool, routers ...router.Router) {
   142  	for _, r := range routers {
   143  		s.routers = append(s.routers, r)
   144  	}
   145  
   146  	m := s.createMux()
   147  	if enableProfiler {
   148  		profilerSetup(m)
   149  	}
   150  	s.routerSwapper = &routerSwapper{
   151  		router: m,
   152  	}
   153  }
   154  
   155  // createMux initializes the main router the server uses.
   156  func (s *Server) createMux() *mux.Router {
   157  	m := mux.NewRouter()
   158  
   159  	logrus.Debugf("Registering routers")
   160  	for _, apiRouter := range s.routers {
   161  		for _, r := range apiRouter.Routes() {
   162  			f := s.makeHTTPHandler(r.Handler())
   163  
   164  			logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
   165  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
   166  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
   167  		}
   168  	}
   169  
   170  	return m
   171  }
   172  
   173  // Wait blocks the server goroutine until it exits.
   174  // It sends an error message if there is any error during
   175  // the API execution.
   176  func (s *Server) Wait(waitChan chan error) {
   177  	if err := s.serveAPI(); err != nil {
   178  		logrus.Errorf("ServeAPI error: %v", err)
   179  		waitChan <- err
   180  		return
   181  	}
   182  	waitChan <- nil
   183  }
   184  
   185  // DisableProfiler reloads the server mux without adding the profiler routes.
   186  func (s *Server) DisableProfiler() {
   187  	s.routerSwapper.Swap(s.createMux())
   188  }
   189  
   190  // EnableProfiler reloads the server mux adding the profiler routes.
   191  func (s *Server) EnableProfiler() {
   192  	m := s.createMux()
   193  	profilerSetup(m)
   194  	s.routerSwapper.Swap(m)
   195  }