server.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 Serve() method for each.
  73. func (s *Server) ServeAPI() error {
  74. var chErrors = make(chan error, len(s.servers))
  75. for _, srv := range s.servers {
  76. go func(srv *HTTPServer) {
  77. var err error
  78. logrus.Infof("API listen on %s", srv.l.Addr())
  79. if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  80. err = nil
  81. }
  82. chErrors <- err
  83. }(srv)
  84. }
  85. for i := 0; i < len(s.servers); i++ {
  86. err := <-chErrors
  87. if err != nil {
  88. return err
  89. }
  90. }
  91. return nil
  92. }
  93. // HTTPServer contains an instance of http server and the listener.
  94. // srv *http.Server, contains configuration to create a http server and a mux router with all api end points.
  95. // l net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
  96. type HTTPServer struct {
  97. srv *http.Server
  98. l net.Listener
  99. }
  100. // Serve starts listening for inbound requests.
  101. func (s *HTTPServer) Serve() error {
  102. return s.srv.Serve(s.l)
  103. }
  104. // Close closes the HTTPServer from listening for the inbound requests.
  105. func (s *HTTPServer) Close() error {
  106. return s.l.Close()
  107. }
  108. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  109. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  110. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  111. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  112. w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
  113. }
  114. func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
  115. if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
  116. logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
  117. }
  118. if l, err = sockets.NewTCPSocket(addr, s.cfg.TLSConfig, s.start); err != nil {
  119. return nil, err
  120. }
  121. if err := allocateDaemonPort(addr); err != nil {
  122. return nil, err
  123. }
  124. return
  125. }
  126. func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc {
  127. return func(w http.ResponseWriter, r *http.Request) {
  128. // log the handler call
  129. logrus.Debugf("Calling %s %s", r.Method, r.URL.Path)
  130. // Define the context that we'll pass around to share info
  131. // like the docker-request-id.
  132. //
  133. // The 'context' will be used for global data that should
  134. // apply to all requests. Data that is specific to the
  135. // immediate function being called should still be passed
  136. // as 'args' on the function call.
  137. ctx := context.Background()
  138. handlerFunc := s.handleWithGlobalMiddlewares(handler)
  139. vars := mux.Vars(r)
  140. if vars == nil {
  141. vars = make(map[string]string)
  142. }
  143. if err := handlerFunc(ctx, w, r, vars); err != nil {
  144. logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL.Path, utils.GetErrorMessage(err))
  145. httputils.WriteError(w, err)
  146. }
  147. }
  148. }
  149. // InitRouters initializes a list of routers for the server.
  150. // Sets those routers as Handler for each 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. for _, srv := range s.servers {
  157. srv.srv.Handler = s.CreateMux()
  158. }
  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. }
  182. // AcceptConnections allows clients to connect to the API server.
  183. // Referenced Daemon is notified about this server, and waits for the
  184. // daemon acknowledgement before the incoming connections are accepted.
  185. func (s *Server) AcceptConnections() {
  186. // close the lock so the listeners start accepting connections
  187. select {
  188. case <-s.start:
  189. default:
  190. close(s.start)
  191. }
  192. }