server.go 6.1 KB

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