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