server.go 5.3 KB

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