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