server.go 5.9 KB

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