server.go 5.2 KB

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