server.go 5.5 KB

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