server.go 5.6 KB

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