server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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/docker/docker/utils"
  12. "github.com/gorilla/mux"
  13. "golang.org/x/net/context"
  14. )
  15. // versionMatcher defines a variable matcher to be parsed by the router
  16. // when a request is about to be served.
  17. const versionMatcher = "/v{version:[0-9.]+}"
  18. // Config provides the configuration for the API server
  19. type Config struct {
  20. Logging bool
  21. EnableCors bool
  22. CorsHeaders string
  23. AuthorizationPluginNames []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. authZPlugins []authorization.Plugin
  34. routerSwapper *routerSwapper
  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. // Accept sets a listener the server accepts connections into.
  44. func (s *Server) Accept(addr string, listeners ...net.Listener) {
  45. for _, listener := range listeners {
  46. httpServer := &HTTPServer{
  47. srv: &http.Server{
  48. Addr: addr,
  49. },
  50. l: listener,
  51. }
  52. s.servers = append(s.servers, httpServer)
  53. }
  54. }
  55. // Close closes servers and thus stop receiving requests
  56. func (s *Server) Close() {
  57. for _, srv := range s.servers {
  58. if err := srv.Close(); err != nil {
  59. logrus.Error(err)
  60. }
  61. }
  62. }
  63. // serveAPI loops through all initialized servers and spawns goroutine
  64. // with Server method for each. It sets createMux() as Handler also.
  65. func (s *Server) serveAPI() error {
  66. var chErrors = make(chan error, len(s.servers))
  67. for _, srv := range s.servers {
  68. srv.srv.Handler = s.routerSwapper
  69. go func(srv *HTTPServer) {
  70. var err error
  71. logrus.Infof("API listen on %s", srv.l.Addr())
  72. if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  73. err = nil
  74. }
  75. chErrors <- err
  76. }(srv)
  77. }
  78. for i := 0; i < len(s.servers); i++ {
  79. err := <-chErrors
  80. if err != nil {
  81. return err
  82. }
  83. }
  84. return nil
  85. }
  86. // HTTPServer contains an instance of http server and the listener.
  87. // srv *http.Server, contains configuration to create a http server and a mux router with all api end points.
  88. // l net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
  89. type HTTPServer struct {
  90. srv *http.Server
  91. l net.Listener
  92. }
  93. // Serve starts listening for inbound requests.
  94. func (s *HTTPServer) Serve() error {
  95. return s.srv.Serve(s.l)
  96. }
  97. // Close closes the HTTPServer from listening for the inbound requests.
  98. func (s *HTTPServer) Close() error {
  99. return s.l.Close()
  100. }
  101. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  102. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  103. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  104. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  105. w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
  106. }
  107. func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
  108. return func(w http.ResponseWriter, r *http.Request) {
  109. // log the handler call
  110. logrus.Debugf("Calling %s %s", r.Method, r.URL.Path)
  111. // Define the context that we'll pass around to share info
  112. // like the docker-request-id.
  113. //
  114. // The 'context' will be used for global data that should
  115. // apply to all requests. Data that is specific to the
  116. // immediate function being called should still be passed
  117. // as 'args' on the function call.
  118. ctx := context.Background()
  119. handlerFunc := s.handleWithGlobalMiddlewares(handler)
  120. vars := mux.Vars(r)
  121. if vars == nil {
  122. vars = make(map[string]string)
  123. }
  124. if err := handlerFunc(ctx, w, r, vars); err != nil {
  125. logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL.Path, utils.GetErrorMessage(err))
  126. httputils.WriteError(w, err)
  127. }
  128. }
  129. }
  130. // InitRouter initializes the list of routers for the server.
  131. // This method also enables the Go profiler if enableProfiler is true.
  132. func (s *Server) InitRouter(enableProfiler bool, routers ...router.Router) {
  133. for _, r := range routers {
  134. s.routers = append(s.routers, r)
  135. }
  136. m := s.createMux()
  137. if enableProfiler {
  138. profilerSetup(m)
  139. }
  140. s.routerSwapper = &routerSwapper{
  141. router: m,
  142. }
  143. }
  144. // createMux initializes the main router the server uses.
  145. func (s *Server) createMux() *mux.Router {
  146. m := mux.NewRouter()
  147. logrus.Debugf("Registering routers")
  148. for _, apiRouter := range s.routers {
  149. for _, r := range apiRouter.Routes() {
  150. f := s.makeHTTPHandler(r.Handler())
  151. logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
  152. m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
  153. m.Path(r.Path()).Methods(r.Method()).Handler(f)
  154. }
  155. }
  156. return m
  157. }
  158. // Wait blocks the server goroutine until it exits.
  159. // It sends an error message if there is any error during
  160. // the API execution.
  161. func (s *Server) Wait(waitChan chan error) {
  162. if err := s.serveAPI(); err != nil {
  163. logrus.Errorf("ServeAPI error: %v", err)
  164. waitChan <- err
  165. return
  166. }
  167. waitChan <- nil
  168. }
  169. // DisableProfiler reloads the server mux without adding the profiler routes.
  170. func (s *Server) DisableProfiler() {
  171. s.routerSwapper.Swap(s.createMux())
  172. }
  173. // EnableProfiler reloads the server mux adding the profiler routes.
  174. func (s *Server) EnableProfiler() {
  175. m := s.createMux()
  176. profilerSetup(m)
  177. s.routerSwapper.Swap(m)
  178. }