server.go 7.1 KB

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