server.go 5.8 KB

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