server.go 6.2 KB

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