server.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. package server
  2. import (
  3. "crypto/tls"
  4. "net"
  5. "net/http"
  6. "os"
  7. "strings"
  8. "github.com/Sirupsen/logrus"
  9. "github.com/docker/docker/api/server/httputils"
  10. "github.com/docker/docker/api/server/router"
  11. "github.com/docker/docker/api/server/router/container"
  12. "github.com/docker/docker/api/server/router/local"
  13. "github.com/docker/docker/api/server/router/network"
  14. "github.com/docker/docker/api/server/router/system"
  15. "github.com/docker/docker/api/server/router/volume"
  16. "github.com/docker/docker/daemon"
  17. "github.com/docker/docker/pkg/authorization"
  18. "github.com/docker/docker/pkg/sockets"
  19. "github.com/docker/docker/utils"
  20. "github.com/gorilla/mux"
  21. "golang.org/x/net/context"
  22. )
  23. // versionMatcher defines a variable matcher to be parsed by the router
  24. // when a request is about to be served.
  25. const versionMatcher = "/v{version:[0-9.]+}"
  26. // Config provides the configuration for the API server
  27. type Config struct {
  28. Logging bool
  29. EnableCors bool
  30. CorsHeaders string
  31. AuthZPluginNames []string
  32. Version string
  33. SocketGroup string
  34. TLSConfig *tls.Config
  35. Addrs []Addr
  36. }
  37. // Server contains instance details for the server
  38. type Server struct {
  39. cfg *Config
  40. servers []*HTTPServer
  41. routers []router.Router
  42. authZPlugins []authorization.Plugin
  43. }
  44. // Addr contains string representation of address and its protocol (tcp, unix...).
  45. type Addr struct {
  46. Proto string
  47. Addr string
  48. }
  49. // New returns a new instance of the server based on the specified configuration.
  50. // It allocates resources which will be needed for ServeAPI(ports, unix-sockets).
  51. func New(cfg *Config) (*Server, error) {
  52. s := &Server{
  53. cfg: cfg,
  54. }
  55. for _, addr := range cfg.Addrs {
  56. srv, err := s.newServer(addr.Proto, addr.Addr)
  57. if err != nil {
  58. return nil, err
  59. }
  60. logrus.Debugf("Server created for HTTP on %s (%s)", addr.Proto, addr.Addr)
  61. s.servers = append(s.servers, srv...)
  62. }
  63. return s, nil
  64. }
  65. // Close closes servers and thus stop receiving requests
  66. func (s *Server) Close() {
  67. for _, srv := range s.servers {
  68. if err := srv.Close(); err != nil {
  69. logrus.Error(err)
  70. }
  71. }
  72. }
  73. // ServeAPI loops through all initialized servers and spawns goroutine
  74. // with Server method for each. It sets CreateMux() as Handler also.
  75. func (s *Server) ServeAPI() error {
  76. var chErrors = make(chan error, len(s.servers))
  77. for _, srv := range s.servers {
  78. srv.srv.Handler = s.CreateMux()
  79. go func(srv *HTTPServer) {
  80. var err error
  81. logrus.Infof("API listen on %s", srv.l.Addr())
  82. if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  83. err = nil
  84. }
  85. chErrors <- err
  86. }(srv)
  87. }
  88. for i := 0; i < len(s.servers); i++ {
  89. err := <-chErrors
  90. if err != nil {
  91. return err
  92. }
  93. }
  94. return nil
  95. }
  96. // HTTPServer contains an instance of http server and the listener.
  97. // srv *http.Server, contains configuration to create a http server and a mux router with all api end points.
  98. // l net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
  99. type HTTPServer struct {
  100. srv *http.Server
  101. l net.Listener
  102. }
  103. // Serve starts listening for inbound requests.
  104. func (s *HTTPServer) Serve() error {
  105. return s.srv.Serve(s.l)
  106. }
  107. // Close closes the HTTPServer from listening for the inbound requests.
  108. func (s *HTTPServer) Close() error {
  109. return s.l.Close()
  110. }
  111. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  112. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  113. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  114. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  115. w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
  116. }
  117. func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
  118. if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
  119. logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
  120. }
  121. if l, err = sockets.NewTCPSocket(addr, s.cfg.TLSConfig); err != nil {
  122. return nil, err
  123. }
  124. if err := allocateDaemonPort(addr); err != nil {
  125. return nil, err
  126. }
  127. return
  128. }
  129. func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
  130. return func(w http.ResponseWriter, r *http.Request) {
  131. // log the handler call
  132. logrus.Debugf("Calling %s %s", r.Method, r.URL.Path)
  133. // Define the context that we'll pass around to share info
  134. // like the docker-request-id.
  135. //
  136. // The 'context' will be used for global data that should
  137. // apply to all requests. Data that is specific to the
  138. // immediate function being called should still be passed
  139. // as 'args' on the function call.
  140. ctx := context.Background()
  141. handlerFunc := s.handleWithGlobalMiddlewares(handler)
  142. vars := mux.Vars(r)
  143. if vars == nil {
  144. vars = make(map[string]string)
  145. }
  146. if err := handlerFunc(ctx, w, r, vars); err != nil {
  147. logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL.Path, utils.GetErrorMessage(err))
  148. httputils.WriteError(w, err)
  149. }
  150. }
  151. }
  152. // InitRouters initializes a list of routers for the server.
  153. func (s *Server) InitRouters(d *daemon.Daemon) {
  154. s.addRouter(container.NewRouter(d))
  155. s.addRouter(local.NewRouter(d))
  156. s.addRouter(network.NewRouter(d))
  157. s.addRouter(system.NewRouter(d))
  158. s.addRouter(volume.NewRouter(d))
  159. }
  160. // addRouter adds a new router to the server.
  161. func (s *Server) addRouter(r router.Router) {
  162. s.routers = append(s.routers, r)
  163. }
  164. // CreateMux initializes the main router the server uses.
  165. // we keep enableCors just for legacy usage, need to be removed in the future
  166. func (s *Server) CreateMux() *mux.Router {
  167. m := mux.NewRouter()
  168. if os.Getenv("DEBUG") != "" {
  169. profilerSetup(m, "/debug/")
  170. }
  171. logrus.Debugf("Registering routers")
  172. for _, apiRouter := range s.routers {
  173. for _, r := range apiRouter.Routes() {
  174. f := s.makeHTTPHandler(r.Handler())
  175. logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
  176. m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
  177. m.Path(r.Path()).Methods(r.Method()).Handler(f)
  178. }
  179. }
  180. return m
  181. }