server.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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/api/server/router/volume"
  14. "github.com/docker/docker/daemon"
  15. "github.com/docker/docker/pkg/sockets"
  16. "github.com/docker/docker/utils"
  17. "github.com/gorilla/mux"
  18. "golang.org/x/net/context"
  19. )
  20. // versionMatcher defines a variable matcher to be parsed by the router
  21. // when a request is about to be served.
  22. const versionMatcher = "/v{version:[0-9.]+}"
  23. // Config provides the configuration for the API server
  24. type Config struct {
  25. Logging bool
  26. EnableCors bool
  27. CorsHeaders string
  28. Version string
  29. SocketGroup string
  30. TLSConfig *tls.Config
  31. Addrs []Addr
  32. }
  33. // Server contains instance details for the server
  34. type Server struct {
  35. cfg *Config
  36. start chan struct{}
  37. servers []*HTTPServer
  38. routers []router.Router
  39. }
  40. // Addr contains string representation of address and its protocol (tcp, unix...).
  41. type Addr struct {
  42. Proto string
  43. Addr string
  44. }
  45. // New returns a new instance of the server based on the specified configuration.
  46. // It allocates resources which will be needed for ServeAPI(ports, unix-sockets).
  47. func New(cfg *Config) (*Server, error) {
  48. s := &Server{
  49. cfg: cfg,
  50. start: make(chan struct{}),
  51. }
  52. for _, addr := range cfg.Addrs {
  53. srv, err := s.newServer(addr.Proto, addr.Addr)
  54. if err != nil {
  55. return nil, err
  56. }
  57. logrus.Debugf("Server created for HTTP on %s (%s)", addr.Proto, addr.Addr)
  58. s.servers = append(s.servers, srv...)
  59. }
  60. return s, nil
  61. }
  62. // Close closes servers and thus stop receiving requests
  63. func (s *Server) Close() {
  64. for _, srv := range s.servers {
  65. if err := srv.Close(); err != nil {
  66. logrus.Error(err)
  67. }
  68. }
  69. }
  70. // ServeAPI loops through all initialized servers and spawns goroutine
  71. // with Serve() method for each.
  72. func (s *Server) ServeAPI() error {
  73. var chErrors = make(chan error, len(s.servers))
  74. for _, srv := range s.servers {
  75. go func(srv *HTTPServer) {
  76. var err error
  77. logrus.Infof("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. vars := mux.Vars(r)
  139. if vars == nil {
  140. vars = make(map[string]string)
  141. }
  142. if err := handlerFunc(ctx, w, r, vars); err != nil {
  143. logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL.Path, utils.GetErrorMessage(err))
  144. httputils.WriteError(w, err)
  145. }
  146. }
  147. }
  148. // InitRouters initializes a list of routers for the server.
  149. // Sets those routers as Handler for each server.
  150. func (s *Server) InitRouters(d *daemon.Daemon) {
  151. s.addRouter(local.NewRouter(d))
  152. s.addRouter(network.NewRouter(d))
  153. s.addRouter(volume.NewRouter(d))
  154. for _, srv := range s.servers {
  155. srv.srv.Handler = s.CreateMux()
  156. }
  157. }
  158. // addRouter adds a new router to the server.
  159. func (s *Server) addRouter(r router.Router) {
  160. s.routers = append(s.routers, r)
  161. }
  162. // CreateMux initializes the main router the server uses.
  163. // we keep enableCors just for legacy usage, need to be removed in the future
  164. func (s *Server) CreateMux() *mux.Router {
  165. m := mux.NewRouter()
  166. if os.Getenv("DEBUG") != "" {
  167. profilerSetup(m, "/debug/")
  168. }
  169. logrus.Debugf("Registering routers")
  170. for _, apiRouter := range s.routers {
  171. for _, r := range apiRouter.Routes() {
  172. f := s.makeHTTPHandler(r.Handler())
  173. logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
  174. m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
  175. m.Path(r.Path()).Methods(r.Method()).Handler(f)
  176. }
  177. }
  178. return m
  179. }
  180. // AcceptConnections allows clients to connect to the API server.
  181. // Referenced Daemon is notified about this server, and waits for the
  182. // daemon acknowledgement before the incoming connections are accepted.
  183. func (s *Server) AcceptConnections() {
  184. // close the lock so the listeners start accepting connections
  185. select {
  186. case <-s.start:
  187. default:
  188. close(s.start)
  189. }
  190. }