server.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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/pkg/authorization"
  11. "github.com/docker/docker/utils"
  12. "github.com/docker/go-connections/sockets"
  13. "github.com/gorilla/mux"
  14. "golang.org/x/net/context"
  15. )
  16. // versionMatcher defines a variable matcher to be parsed by the router
  17. // when a request is about to be served.
  18. const versionMatcher = "/v{version:[0-9.]+}"
  19. // Config provides the configuration for the API server
  20. type Config struct {
  21. Logging bool
  22. EnableCors bool
  23. CorsHeaders string
  24. AuthorizationPluginNames []string
  25. Version string
  26. SocketGroup string
  27. TLSConfig *tls.Config
  28. Addrs []Addr
  29. }
  30. // Server contains instance details for the server
  31. type Server struct {
  32. cfg *Config
  33. servers []*HTTPServer
  34. routers []router.Router
  35. authZPlugins []authorization.Plugin
  36. routerSwapper *routerSwapper
  37. }
  38. // Addr contains string representation of address and its protocol (tcp, unix...).
  39. type Addr struct {
  40. Proto string
  41. Addr string
  42. }
  43. // New returns a new instance of the server based on the specified configuration.
  44. // It allocates resources which will be needed for ServeAPI(ports, unix-sockets).
  45. func New(cfg *Config) (*Server, error) {
  46. s := &Server{
  47. cfg: cfg,
  48. }
  49. for _, addr := range cfg.Addrs {
  50. srv, err := s.newServer(addr.Proto, addr.Addr)
  51. if err != nil {
  52. return nil, err
  53. }
  54. logrus.Debugf("Server created for HTTP on %s (%s)", addr.Proto, addr.Addr)
  55. s.servers = append(s.servers, srv...)
  56. }
  57. return s, nil
  58. }
  59. // Close closes servers and thus stop receiving requests
  60. func (s *Server) Close() {
  61. for _, srv := range s.servers {
  62. if err := srv.Close(); err != nil {
  63. logrus.Error(err)
  64. }
  65. }
  66. }
  67. // serveAPI loops through all initialized servers and spawns goroutine
  68. // with Server method for each. It sets createMux() as Handler also.
  69. func (s *Server) serveAPI() error {
  70. s.initRouterSwapper()
  71. var chErrors = make(chan error, len(s.servers))
  72. for _, srv := range s.servers {
  73. srv.srv.Handler = s.routerSwapper
  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); 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. // AddRouters initializes a list of routers for the server.
  148. func (s *Server) AddRouters(routers ...router.Router) {
  149. for _, r := range routers {
  150. s.addRouter(r)
  151. }
  152. }
  153. // addRouter adds a new router to the server.
  154. func (s *Server) addRouter(r router.Router) {
  155. s.routers = append(s.routers, r)
  156. }
  157. // createMux initializes the main router the server uses.
  158. func (s *Server) createMux() *mux.Router {
  159. m := mux.NewRouter()
  160. if utils.IsDebugEnabled() {
  161. profilerSetup(m, "/debug/")
  162. }
  163. logrus.Debugf("Registering routers")
  164. for _, apiRouter := range s.routers {
  165. for _, r := range apiRouter.Routes() {
  166. f := s.makeHTTPHandler(r.Handler())
  167. logrus.Debugf("Registering %s, %s", r.Method(), r.Path())
  168. m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
  169. m.Path(r.Path()).Methods(r.Method()).Handler(f)
  170. }
  171. }
  172. return m
  173. }
  174. // Wait blocks the server goroutine until it exits.
  175. // It sends an error message if there is any error during
  176. // the API execution.
  177. func (s *Server) Wait(waitChan chan error) {
  178. if err := s.serveAPI(); err != nil {
  179. logrus.Errorf("ServeAPI error: %v", err)
  180. waitChan <- err
  181. return
  182. }
  183. waitChan <- nil
  184. }
  185. func (s *Server) initRouterSwapper() {
  186. s.routerSwapper = &routerSwapper{
  187. router: s.createMux(),
  188. }
  189. }
  190. // Reload reads configuration changes and modifies the
  191. // server according to those changes.
  192. // Currently, only the --debug configuration is taken into account.
  193. func (s *Server) Reload(debug bool) {
  194. debugEnabled := utils.IsDebugEnabled()
  195. switch {
  196. case debugEnabled && !debug: // disable debug
  197. utils.DisableDebug()
  198. s.routerSwapper.Swap(s.createMux())
  199. case debug && !debugEnabled: // enable debug
  200. utils.EnableDebug()
  201. s.routerSwapper.Swap(s.createMux())
  202. }
  203. }