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