Browse Source

Revert "Merge pull request #16567 from calavera/context_per_request"

This reverts commit ff92f45be49146cd7ac7716c36d89de989cb262e, reversing
changes made to 80e31df3b6fdf6c1fbd6a5d0aceb0a148066508c.

Reverting to make the next revert easier.

Signed-off-by: Tibor Vass <tibor@docker.com>
Tibor Vass 9 years ago
parent
commit
79c31f4b13

+ 9 - 9
api/server/image.go

@@ -112,7 +112,7 @@ func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
 			OutStream:   output,
 			OutStream:   output,
 		}
 		}
 
 
-		err = s.daemon.Repositories().Pull(ctx, image, tag, imagePullConfig)
+		err = s.daemon.Repositories(ctx).Pull(ctx, image, tag, imagePullConfig)
 	} else { //import
 	} else { //import
 		if tag == "" {
 		if tag == "" {
 			repo, tag = parsers.ParseRepositoryTag(repo)
 			repo, tag = parsers.ParseRepositoryTag(repo)
@@ -129,7 +129,7 @@ func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
 			return err
 			return err
 		}
 		}
 
 
-		err = s.daemon.Repositories().Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
+		err = s.daemon.Repositories(ctx).Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
 	}
 	}
 	if err != nil {
 	if err != nil {
 		if !output.Flushed() {
 		if !output.Flushed() {
@@ -184,7 +184,7 @@ func (s *Server) postImagesPush(ctx context.Context, w http.ResponseWriter, r *h
 
 
 	w.Header().Set("Content-Type", "application/json")
 	w.Header().Set("Content-Type", "application/json")
 
 
-	if err := s.daemon.Repositories().Push(ctx, name, imagePushConfig); err != nil {
+	if err := s.daemon.Repositories(ctx).Push(ctx, name, imagePushConfig); err != nil {
 		if !output.Flushed() {
 		if !output.Flushed() {
 			return err
 			return err
 		}
 		}
@@ -212,7 +212,7 @@ func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
 		names = r.Form["names"]
 		names = r.Form["names"]
 	}
 	}
 
 
-	if err := s.daemon.Repositories().ImageExport(names, output); err != nil {
+	if err := s.daemon.Repositories(ctx).ImageExport(names, output); err != nil {
 		if !output.Flushed() {
 		if !output.Flushed() {
 			return err
 			return err
 		}
 		}
@@ -223,7 +223,7 @@ func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
 }
 }
 
 
 func (s *Server) postImagesLoad(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
 func (s *Server) postImagesLoad(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
-	return s.daemon.Repositories().Load(r.Body, w)
+	return s.daemon.Repositories(ctx).Load(r.Body, w)
 }
 }
 
 
 func (s *Server) deleteImages(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
 func (s *Server) deleteImages(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
@@ -256,7 +256,7 @@ func (s *Server) getImagesByName(ctx context.Context, w http.ResponseWriter, r *
 		return fmt.Errorf("Missing parameter")
 		return fmt.Errorf("Missing parameter")
 	}
 	}
 
 
-	imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
+	imageInspect, err := s.daemon.Repositories(ctx).Lookup(vars["name"])
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
@@ -364,7 +364,7 @@ func (s *Server) getImagesJSON(ctx context.Context, w http.ResponseWriter, r *ht
 	}
 	}
 
 
 	// FIXME: The filter parameter could just be a match filter
 	// FIXME: The filter parameter could just be a match filter
-	images, err := s.daemon.Repositories().Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
+	images, err := s.daemon.Repositories(ctx).Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
@@ -378,7 +378,7 @@ func (s *Server) getImagesHistory(ctx context.Context, w http.ResponseWriter, r
 	}
 	}
 
 
 	name := vars["name"]
 	name := vars["name"]
-	history, err := s.daemon.Repositories().History(name)
+	history, err := s.daemon.Repositories(ctx).History(name)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
@@ -398,7 +398,7 @@ func (s *Server) postImagesTag(ctx context.Context, w http.ResponseWriter, r *ht
 	tag := r.Form.Get("tag")
 	tag := r.Form.Get("tag")
 	force := boolValue(r, "force")
 	force := boolValue(r, "force")
 	name := vars["name"]
 	name := vars["name"]
-	if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil {
+	if err := s.daemon.Repositories(ctx).Tag(repo, tag, name, force); err != nil {
 		return err
 		return err
 	}
 	}
 	s.daemon.EventsService.Log(ctx, "tag", utils.ImageReference(repo, tag), "")
 	s.daemon.EventsService.Log(ctx, "tag", utils.ImageReference(repo, tag), "")

+ 5 - 7
api/server/server.go

@@ -42,12 +42,12 @@ type Server struct {
 }
 }
 
 
 // New returns a new instance of the server based on the specified configuration.
 // New returns a new instance of the server based on the specified configuration.
-func New(cfg *Config) *Server {
+func New(ctx context.Context, cfg *Config) *Server {
 	srv := &Server{
 	srv := &Server{
 		cfg:   cfg,
 		cfg:   cfg,
 		start: make(chan struct{}),
 		start: make(chan struct{}),
 	}
 	}
-	srv.router = createRouter(srv)
+	srv.router = createRouter(ctx, srv)
 	return srv
 	return srv
 }
 }
 
 
@@ -291,7 +291,7 @@ func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
 	return
 	return
 }
 }
 
 
-func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
+func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 	return func(w http.ResponseWriter, r *http.Request) {
 		// log the handler generation
 		// log the handler generation
 		logrus.Debugf("Calling %s %s", localMethod, localRoute)
 		logrus.Debugf("Calling %s %s", localMethod, localRoute)
@@ -303,8 +303,6 @@ func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHan
 		// apply to all requests. Data that is specific to the
 		// apply to all requests. Data that is specific to the
 		// immediate function being called should still be passed
 		// immediate function being called should still be passed
 		// as 'args' on the function call.
 		// as 'args' on the function call.
-		ctx := context.Background()
-
 		reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
 		reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
 		ctx = context.WithValue(ctx, context.RequestID, reqID)
 		ctx = context.WithValue(ctx, context.RequestID, reqID)
 		handlerFunc := s.handleWithGlobalMiddlewares(localHandler)
 		handlerFunc := s.handleWithGlobalMiddlewares(localHandler)
@@ -318,7 +316,7 @@ func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHan
 
 
 // createRouter initializes the main router the server uses.
 // createRouter initializes the main router the server uses.
 // we keep enableCors just for legacy usage, need to be removed in the future
 // we keep enableCors just for legacy usage, need to be removed in the future
-func createRouter(s *Server) *mux.Router {
+func createRouter(ctx context.Context, s *Server) *mux.Router {
 	r := mux.NewRouter()
 	r := mux.NewRouter()
 	if os.Getenv("DEBUG") != "" {
 	if os.Getenv("DEBUG") != "" {
 		profilerSetup(r, "/debug/")
 		profilerSetup(r, "/debug/")
@@ -398,7 +396,7 @@ func createRouter(s *Server) *mux.Router {
 			localMethod := method
 			localMethod := method
 
 
 			// build the handler function
 			// build the handler function
-			f := s.makeHTTPHandler(localMethod, localRoute, localFct)
+			f := s.makeHTTPHandler(ctx, localMethod, localRoute, localFct)
 
 
 			// add the new route
 			// add the new route
 			if localRoute == "" {
 			if localRoute == "" {

+ 6 - 2
api/server/server_experimental_unix.go

@@ -2,8 +2,12 @@
 
 
 package server
 package server
 
 
-func (s *Server) registerSubRouter() {
-	httpHandler := s.daemon.NetworkAPIRouter()
+import (
+	"github.com/docker/docker/context"
+)
+
+func (s *Server) registerSubRouter(ctx context.Context) {
+	httpHandler := s.daemon.NetworkAPIRouter(ctx)
 
 
 	subrouter := s.router.PathPrefix("/v{version:[0-9.]+}/networks").Subrouter()
 	subrouter := s.router.PathPrefix("/v{version:[0-9.]+}/networks").Subrouter()
 	subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler)
 	subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler)

+ 5 - 1
api/server/server_stub.go

@@ -2,5 +2,9 @@
 
 
 package server
 package server
 
 
-func (s *Server) registerSubRouter() {
+import (
+	"github.com/docker/docker/context"
+)
+
+func (s *Server) registerSubRouter(ctx context.Context) {
 }
 }

+ 3 - 2
api/server/server_unix.go

@@ -8,6 +8,7 @@ import (
 	"net/http"
 	"net/http"
 	"strconv"
 	"strconv"
 
 
+	"github.com/docker/docker/context"
 	"github.com/docker/docker/daemon"
 	"github.com/docker/docker/daemon"
 	"github.com/docker/docker/pkg/sockets"
 	"github.com/docker/docker/pkg/sockets"
 	"github.com/docker/libnetwork/portallocator"
 	"github.com/docker/libnetwork/portallocator"
@@ -63,10 +64,10 @@ func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
 // AcceptConnections allows clients to connect to the API server.
 // AcceptConnections allows clients to connect to the API server.
 // Referenced Daemon is notified about this server, and waits for the
 // Referenced Daemon is notified about this server, and waits for the
 // daemon acknowledgement before the incoming connections are accepted.
 // daemon acknowledgement before the incoming connections are accepted.
-func (s *Server) AcceptConnections(d *daemon.Daemon) {
+func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
 	// Tell the init daemon we are accepting requests
 	// Tell the init daemon we are accepting requests
 	s.daemon = d
 	s.daemon = d
-	s.registerSubRouter()
+	s.registerSubRouter(ctx)
 	go systemdDaemon.SdNotify("READY=1")
 	go systemdDaemon.SdNotify("READY=1")
 	// close the lock so the listeners start accepting connections
 	// close the lock so the listeners start accepting connections
 	select {
 	select {

+ 3 - 2
api/server/server_windows.go

@@ -7,6 +7,7 @@ import (
 	"net"
 	"net"
 	"net/http"
 	"net/http"
 
 
+	"github.com/docker/docker/context"
 	"github.com/docker/docker/daemon"
 	"github.com/docker/docker/daemon"
 )
 )
 
 
@@ -42,9 +43,9 @@ func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
 }
 }
 
 
 // AcceptConnections allows router to start listening for the incoming requests.
 // AcceptConnections allows router to start listening for the incoming requests.
-func (s *Server) AcceptConnections(d *daemon.Daemon) {
+func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
 	s.daemon = d
 	s.daemon = d
-	s.registerSubRouter()
+	s.registerSubRouter(ctx)
 	// close the lock so the listeners start accepting connections
 	// close the lock so the listeners start accepting connections
 	select {
 	select {
 	case <-s.start:
 	case <-s.start:

+ 2 - 2
builder/dispatchers.go

@@ -209,7 +209,7 @@ func from(ctx context.Context, b *builder, args []string, attributes map[string]
 		return nil
 		return nil
 	}
 	}
 
 
-	image, err := b.Daemon.Repositories().LookupImage(name)
+	image, err := b.Daemon.Repositories(ctx).LookupImage(name)
 	if b.Pull {
 	if b.Pull {
 		image, err = b.pullImage(ctx, name)
 		image, err = b.pullImage(ctx, name)
 		if err != nil {
 		if err != nil {
@@ -217,7 +217,7 @@ func from(ctx context.Context, b *builder, args []string, attributes map[string]
 		}
 		}
 	}
 	}
 	if err != nil {
 	if err != nil {
-		if b.Daemon.Graph().IsNotExist(err, name) {
+		if b.Daemon.Graph(ctx).IsNotExist(err, name) {
 			image, err = b.pullImage(ctx, name)
 			image, err = b.pullImage(ctx, name)
 		}
 		}
 
 

+ 4 - 4
builder/internals.go

@@ -132,7 +132,7 @@ func (b *builder) commit(ctx context.Context, id string, autoCmd *stringutils.St
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
-	b.Daemon.Graph().Retain(b.id, image.ID)
+	b.Daemon.Graph(ctx).Retain(b.id, image.ID)
 	b.activeImages = append(b.activeImages, image.ID)
 	b.activeImages = append(b.activeImages, image.ID)
 	b.image = image.ID
 	b.image = image.ID
 	return nil
 	return nil
@@ -516,11 +516,11 @@ func (b *builder) pullImage(ctx context.Context, name string) (*image.Image, err
 		OutStream:  ioutils.NopWriteCloser(b.OutOld),
 		OutStream:  ioutils.NopWriteCloser(b.OutOld),
 	}
 	}
 
 
-	if err := b.Daemon.Repositories().Pull(ctx, remote, tag, imagePullConfig); err != nil {
+	if err := b.Daemon.Repositories(ctx).Pull(ctx, remote, tag, imagePullConfig); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 
 
-	image, err := b.Daemon.Repositories().LookupImage(name)
+	image, err := b.Daemon.Repositories(ctx).LookupImage(name)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
@@ -600,7 +600,7 @@ func (b *builder) probeCache(ctx context.Context) (bool, error) {
 	fmt.Fprintf(b.OutStream, " ---> Using cache\n")
 	fmt.Fprintf(b.OutStream, " ---> Using cache\n")
 	logrus.Debugf("[BUILDER] Use cached version")
 	logrus.Debugf("[BUILDER] Use cached version")
 	b.image = cache.ID
 	b.image = cache.ID
-	b.Daemon.Graph().Retain(b.id, cache.ID)
+	b.Daemon.Graph(ctx).Retain(b.id, cache.ID)
 	b.activeImages = append(b.activeImages, cache.ID)
 	b.activeImages = append(b.activeImages, cache.ID)
 	return true, nil
 	return true, nil
 }
 }

+ 2 - 2
builder/job.go

@@ -230,7 +230,7 @@ func Build(ctx context.Context, d *daemon.Daemon, buildConfig *Config) error {
 	}
 	}
 
 
 	defer func() {
 	defer func() {
-		builder.Daemon.Graph().Release(builder.id, builder.activeImages...)
+		builder.Daemon.Graph(ctx).Release(builder.id, builder.activeImages...)
 	}()
 	}()
 
 
 	id, err := builder.Run(ctx, context)
 	id, err := builder.Run(ctx, context)
@@ -238,7 +238,7 @@ func Build(ctx context.Context, d *daemon.Daemon, buildConfig *Config) error {
 		return err
 		return err
 	}
 	}
 	if repoName != "" {
 	if repoName != "" {
-		return d.Repositories().Tag(repoName, tag, id, true)
+		return d.Repositories(ctx).Tag(repoName, tag, id, true)
 	}
 	}
 	return nil
 	return nil
 }
 }

+ 1 - 1
daemon/create.go

@@ -30,7 +30,7 @@ func (daemon *Daemon) ContainerCreate(ctx context.Context, name string, config *
 
 
 	container, buildWarnings, err := daemon.Create(ctx, config, hostConfig, name)
 	container, buildWarnings, err := daemon.Create(ctx, config, hostConfig, name)
 	if err != nil {
 	if err != nil {
-		if daemon.Graph().IsNotExist(err, config.Image) {
+		if daemon.Graph(ctx).IsNotExist(err, config.Image) {
 			if strings.Contains(config.Image, "@") {
 			if strings.Contains(config.Image, "@") {
 				return types.ContainerCreateResponse{"", warnings}, derr.ErrorCodeNoSuchImageHash.WithArgs(config.Image)
 				return types.ContainerCreateResponse{"", warnings}, derr.ErrorCodeNoSuchImageHash.WithArgs(config.Image)
 			}
 			}

+ 10 - 11
daemon/daemon.go

@@ -253,7 +253,7 @@ func (daemon *Daemon) ensureName(container *Container) error {
 	return nil
 	return nil
 }
 }
 
 
-func (daemon *Daemon) restore() error {
+func (daemon *Daemon) restore(ctx context.Context) error {
 	type cr struct {
 	type cr struct {
 		container  *Container
 		container  *Container
 		registered bool
 		registered bool
@@ -309,7 +309,6 @@ func (daemon *Daemon) restore() error {
 	}
 	}
 
 
 	group := sync.WaitGroup{}
 	group := sync.WaitGroup{}
-	ctx := context.Background()
 	for _, c := range containers {
 	for _, c := range containers {
 		group.Add(1)
 		group.Add(1)
 
 
@@ -574,7 +573,7 @@ func (daemon *Daemon) registerLink(parent, child *Container, alias string) error
 
 
 // NewDaemon sets up everything for the daemon to be able to service
 // NewDaemon sets up everything for the daemon to be able to service
 // requests from the webserver.
 // requests from the webserver.
-func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
+func NewDaemon(ctx context.Context, config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
 	setDefaultMtu(config)
 	setDefaultMtu(config)
 
 
 	// Ensure we have compatible configuration options
 	// Ensure we have compatible configuration options
@@ -642,7 +641,7 @@ func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo
 	// Ensure the graph driver is shutdown at a later point
 	// Ensure the graph driver is shutdown at a later point
 	defer func() {
 	defer func() {
 		if err != nil {
 		if err != nil {
-			if err := d.Shutdown(context.Background()); err != nil {
+			if err := d.Shutdown(ctx); err != nil {
 				logrus.Error(err)
 				logrus.Error(err)
 			}
 			}
 		}
 		}
@@ -786,7 +785,7 @@ func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo
 
 
 	go d.execCommandGC()
 	go d.execCommandGC()
 
 
-	if err := d.restore(); err != nil {
+	if err := d.restore(ctx); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
 
 
@@ -799,7 +798,7 @@ func (daemon *Daemon) Shutdown(ctx context.Context) error {
 	if daemon.containers != nil {
 	if daemon.containers != nil {
 		group := sync.WaitGroup{}
 		group := sync.WaitGroup{}
 		logrus.Debug("starting clean shutdown of all containers...")
 		logrus.Debug("starting clean shutdown of all containers...")
-		for _, container := range daemon.List() {
+		for _, container := range daemon.List(ctx) {
 			c := container
 			c := container
 			if c.IsRunning() {
 			if c.IsRunning() {
 				logrus.Debugf("stopping %s", c.ID)
 				logrus.Debugf("stopping %s", c.ID)
@@ -974,12 +973,12 @@ func (daemon *Daemon) createRootfs(container *Container) error {
 // which need direct access to daemon.graph.
 // which need direct access to daemon.graph.
 // Once the tests switch to using engine and jobs, this method
 // Once the tests switch to using engine and jobs, this method
 // can go away.
 // can go away.
-func (daemon *Daemon) Graph() *graph.Graph {
+func (daemon *Daemon) Graph(ctx context.Context) *graph.Graph {
 	return daemon.graph
 	return daemon.graph
 }
 }
 
 
 // Repositories returns all repositories.
 // Repositories returns all repositories.
-func (daemon *Daemon) Repositories() *graph.TagStore {
+func (daemon *Daemon) Repositories(ctx context.Context) *graph.TagStore {
 	return daemon.repositories
 	return daemon.repositories
 }
 }
 
 
@@ -993,13 +992,13 @@ func (daemon *Daemon) systemInitPath() string {
 
 
 // GraphDriver returns the currently used driver for processing
 // GraphDriver returns the currently used driver for processing
 // container layers.
 // container layers.
-func (daemon *Daemon) GraphDriver() graphdriver.Driver {
+func (daemon *Daemon) GraphDriver(ctx context.Context) graphdriver.Driver {
 	return daemon.driver
 	return daemon.driver
 }
 }
 
 
 // ExecutionDriver returns the currently used driver for creating and
 // ExecutionDriver returns the currently used driver for creating and
 // starting execs in a container.
 // starting execs in a container.
-func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
+func (daemon *Daemon) ExecutionDriver(ctx context.Context) execdriver.Driver {
 	return daemon.execDriver
 	return daemon.execDriver
 }
 }
 
 
@@ -1013,7 +1012,7 @@ func (daemon *Daemon) containerGraph() *graphdb.Database {
 // returned if the parent image cannot be found.
 // returned if the parent image cannot be found.
 func (daemon *Daemon) ImageGetCached(ctx context.Context, imgID string, config *runconfig.Config) (*image.Image, error) {
 func (daemon *Daemon) ImageGetCached(ctx context.Context, imgID string, config *runconfig.Config) (*image.Image, error) {
 	// Retrieve all images
 	// Retrieve all images
-	images := daemon.Graph().Map()
+	images := daemon.Graph(ctx).Map()
 
 
 	// Store the tree in a map of map (map[parentId][childId])
 	// Store the tree in a map of map (map[parentId][childId])
 	imageMap := make(map[string]map[string]struct{})
 	imageMap := make(map[string]map[string]struct{})

+ 3 - 3
daemon/daemon_unix.go

@@ -123,8 +123,8 @@ func verifyPlatformContainerSettings(ctx context.Context, daemon *Daemon, hostCo
 	warnings := []string{}
 	warnings := []string{}
 	sysInfo := sysinfo.New(true)
 	sysInfo := sysinfo.New(true)
 
 
-	if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
-		return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
+	if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver(ctx).Name(), "lxc") {
+		return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver(ctx).Name())
 	}
 	}
 
 
 	// memory subsystem checks and adjustments
 	// memory subsystem checks and adjustments
@@ -492,7 +492,7 @@ func setupInitLayer(initLayer string) error {
 
 
 // NetworkAPIRouter implements a feature for server-experimental,
 // NetworkAPIRouter implements a feature for server-experimental,
 // directly calling into libnetwork.
 // directly calling into libnetwork.
-func (daemon *Daemon) NetworkAPIRouter() func(w http.ResponseWriter, req *http.Request) {
+func (daemon *Daemon) NetworkAPIRouter(ctx context.Context) func(w http.ResponseWriter, req *http.Request) {
 	return nwapi.NewHTTPHandler(daemon.netController)
 	return nwapi.NewHTTPHandler(daemon.netController)
 }
 }
 
 

+ 16 - 16
daemon/image_delete.go

@@ -54,7 +54,7 @@ import (
 func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDelete, error) {
 func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDelete, error) {
 	records := []types.ImageDelete{}
 	records := []types.ImageDelete{}
 
 
-	img, err := daemon.Repositories().LookupImage(imageRef)
+	img, err := daemon.Repositories(ctx).LookupImage(imageRef)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
@@ -66,7 +66,7 @@ func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, p
 		// true, there are multiple repository references to this
 		// true, there are multiple repository references to this
 		// image, or there are no containers using the given reference.
 		// image, or there are no containers using the given reference.
 		if !(force || daemon.imageHasMultipleRepositoryReferences(ctx, img.ID)) {
 		if !(force || daemon.imageHasMultipleRepositoryReferences(ctx, img.ID)) {
-			if container := daemon.getContainerUsingImage(img.ID); container != nil {
+			if container := daemon.getContainerUsingImage(ctx, img.ID); container != nil {
 				// If we removed the repository reference then
 				// If we removed the repository reference then
 				// this image would remain "dangling" and since
 				// this image would remain "dangling" and since
 				// we really want to avoid that the client must
 				// we really want to avoid that the client must
@@ -91,7 +91,7 @@ func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, p
 		// repository reference to the image then we will want to
 		// repository reference to the image then we will want to
 		// remove that reference.
 		// remove that reference.
 		// FIXME: Is this the behavior we want?
 		// FIXME: Is this the behavior we want?
-		repoRefs := daemon.Repositories().ByID()[img.ID]
+		repoRefs := daemon.Repositories(ctx).ByID()[img.ID]
 		if len(repoRefs) == 1 {
 		if len(repoRefs) == 1 {
 			parsedRef, err := daemon.removeImageRef(ctx, repoRefs[0])
 			parsedRef, err := daemon.removeImageRef(ctx, repoRefs[0])
 			if err != nil {
 			if err != nil {
@@ -117,13 +117,13 @@ func isImageIDPrefix(imageID, possiblePrefix string) bool {
 // imageHasMultipleRepositoryReferences returns whether there are multiple
 // imageHasMultipleRepositoryReferences returns whether there are multiple
 // repository references to the given imageID.
 // repository references to the given imageID.
 func (daemon *Daemon) imageHasMultipleRepositoryReferences(ctx context.Context, imageID string) bool {
 func (daemon *Daemon) imageHasMultipleRepositoryReferences(ctx context.Context, imageID string) bool {
-	return len(daemon.Repositories().ByID()[imageID]) > 1
+	return len(daemon.Repositories(ctx).ByID()[imageID]) > 1
 }
 }
 
 
 // getContainerUsingImage returns a container that was created using the given
 // getContainerUsingImage returns a container that was created using the given
 // imageID. Returns nil if there is no such container.
 // imageID. Returns nil if there is no such container.
-func (daemon *Daemon) getContainerUsingImage(imageID string) *Container {
-	for _, container := range daemon.List() {
+func (daemon *Daemon) getContainerUsingImage(ctx context.Context, imageID string) *Container {
+	for _, container := range daemon.List(ctx) {
 		if container.ImageID == imageID {
 		if container.ImageID == imageID {
 			return container
 			return container
 		}
 		}
@@ -146,7 +146,7 @@ func (daemon *Daemon) removeImageRef(ctx context.Context, repositoryRef string)
 	// Ignore the boolean value returned, as far as we're concerned, this
 	// Ignore the boolean value returned, as far as we're concerned, this
 	// is an idempotent operation and it's okay if the reference didn't
 	// is an idempotent operation and it's okay if the reference didn't
 	// exist in the first place.
 	// exist in the first place.
-	_, err := daemon.Repositories().Delete(repository, ref)
+	_, err := daemon.Repositories(ctx).Delete(repository, ref)
 
 
 	return utils.ImageReference(repository, ref), err
 	return utils.ImageReference(repository, ref), err
 }
 }
@@ -157,7 +157,7 @@ func (daemon *Daemon) removeImageRef(ctx context.Context, repositoryRef string)
 // daemon's event service. An "Untagged" types.ImageDelete is added to the
 // daemon's event service. An "Untagged" types.ImageDelete is added to the
 // given list of records.
 // given list of records.
 func (daemon *Daemon) removeAllReferencesToImageID(ctx context.Context, imgID string, records *[]types.ImageDelete) error {
 func (daemon *Daemon) removeAllReferencesToImageID(ctx context.Context, imgID string, records *[]types.ImageDelete) error {
-	imageRefs := daemon.Repositories().ByID()[imgID]
+	imageRefs := daemon.Repositories(ctx).ByID()[imgID]
 
 
 	for _, imageRef := range imageRefs {
 	for _, imageRef := range imageRefs {
 		parsedRef, err := daemon.removeImageRef(ctx, imageRef)
 		parsedRef, err := daemon.removeImageRef(ctx, imageRef)
@@ -224,7 +224,7 @@ func (daemon *Daemon) imageDeleteHelper(ctx context.Context, img *image.Image, r
 		return err
 		return err
 	}
 	}
 
 
-	if err := daemon.Graph().Delete(img.ID); err != nil {
+	if err := daemon.Graph(ctx).Delete(img.ID); err != nil {
 		return err
 		return err
 	}
 	}
 
 
@@ -238,7 +238,7 @@ func (daemon *Daemon) imageDeleteHelper(ctx context.Context, img *image.Image, r
 	// We need to prune the parent image. This means delete it if there are
 	// We need to prune the parent image. This means delete it if there are
 	// no tags/digests referencing it and there are no containers using it (
 	// no tags/digests referencing it and there are no containers using it (
 	// either running or stopped).
 	// either running or stopped).
-	parentImg, err := daemon.Graph().Get(img.Parent)
+	parentImg, err := daemon.Graph(ctx).Get(img.Parent)
 	if err != nil {
 	if err != nil {
 		return derr.ErrorCodeImgNoParent.WithArgs(err)
 		return derr.ErrorCodeImgNoParent.WithArgs(err)
 	}
 	}
@@ -271,7 +271,7 @@ func (daemon *Daemon) checkImageDeleteConflict(ctx context.Context, img *image.I
 
 
 func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
 func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
 	// Check if the image ID is being used by a pull or build.
 	// Check if the image ID is being used by a pull or build.
-	if daemon.Graph().IsHeld(img.ID) {
+	if daemon.Graph(ctx).IsHeld(img.ID) {
 		return &imageDeleteConflict{
 		return &imageDeleteConflict{
 			hard:    true,
 			hard:    true,
 			imgID:   img.ID,
 			imgID:   img.ID,
@@ -280,7 +280,7 @@ func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
 	}
 	}
 
 
 	// Check if the image has any descendent images.
 	// Check if the image has any descendent images.
-	if daemon.Graph().HasChildren(img) {
+	if daemon.Graph(ctx).HasChildren(img) {
 		return &imageDeleteConflict{
 		return &imageDeleteConflict{
 			hard:    true,
 			hard:    true,
 			imgID:   img.ID,
 			imgID:   img.ID,
@@ -289,7 +289,7 @@ func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
 	}
 	}
 
 
 	// Check if any running container is using the image.
 	// Check if any running container is using the image.
-	for _, container := range daemon.List() {
+	for _, container := range daemon.List(ctx) {
 		if !container.IsRunning() {
 		if !container.IsRunning() {
 			// Skip this until we check for soft conflicts later.
 			// Skip this until we check for soft conflicts later.
 			continue
 			continue
@@ -309,7 +309,7 @@ func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
 
 
 func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
 func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
 	// Check if any repository tags/digest reference this image.
 	// Check if any repository tags/digest reference this image.
-	if daemon.Repositories().HasReferences(img) {
+	if daemon.Repositories(ctx).HasReferences(img) {
 		return &imageDeleteConflict{
 		return &imageDeleteConflict{
 			imgID:   img.ID,
 			imgID:   img.ID,
 			message: "image is referenced in one or more repositories",
 			message: "image is referenced in one or more repositories",
@@ -317,7 +317,7 @@ func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *ima
 	}
 	}
 
 
 	// Check if any stopped containers reference this image.
 	// Check if any stopped containers reference this image.
-	for _, container := range daemon.List() {
+	for _, container := range daemon.List(ctx) {
 		if container.IsRunning() {
 		if container.IsRunning() {
 			// Skip this as it was checked above in hard conflict conditions.
 			// Skip this as it was checked above in hard conflict conditions.
 			continue
 			continue
@@ -338,5 +338,5 @@ func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *ima
 // that there are no repository references to the given image and it has no
 // that there are no repository references to the given image and it has no
 // child images.
 // child images.
 func (daemon *Daemon) imageIsDangling(ctx context.Context, img *image.Image) bool {
 func (daemon *Daemon) imageIsDangling(ctx context.Context, img *image.Image) bool {
-	return !(daemon.Repositories().HasReferences(img) || daemon.Graph().HasChildren(img))
+	return !(daemon.Repositories(ctx).HasReferences(img) || daemon.Graph(ctx).HasChildren(img))
 }
 }

+ 5 - 5
daemon/info.go

@@ -20,7 +20,7 @@ import (
 
 
 // SystemInfo returns information about the host server the daemon is running on.
 // SystemInfo returns information about the host server the daemon is running on.
 func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
 func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
-	images := daemon.Graph().Map()
+	images := daemon.Graph(ctx).Map()
 	var imgcount int
 	var imgcount int
 	if images == nil {
 	if images == nil {
 		imgcount = 0
 		imgcount = 0
@@ -66,10 +66,10 @@ func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
 
 
 	v := &types.Info{
 	v := &types.Info{
 		ID:                 daemon.ID,
 		ID:                 daemon.ID,
-		Containers:         len(daemon.List()),
+		Containers:         len(daemon.List(ctx)),
 		Images:             imgcount,
 		Images:             imgcount,
-		Driver:             daemon.GraphDriver().String(),
-		DriverStatus:       daemon.GraphDriver().Status(),
+		Driver:             daemon.GraphDriver(ctx).String(),
+		DriverStatus:       daemon.GraphDriver(ctx).Status(),
 		IPv4Forwarding:     !sysInfo.IPv4ForwardingDisabled,
 		IPv4Forwarding:     !sysInfo.IPv4ForwardingDisabled,
 		BridgeNfIptables:   !sysInfo.BridgeNfCallIptablesDisabled,
 		BridgeNfIptables:   !sysInfo.BridgeNfCallIptablesDisabled,
 		BridgeNfIP6tables:  !sysInfo.BridgeNfCallIP6tablesDisabled,
 		BridgeNfIP6tables:  !sysInfo.BridgeNfCallIP6tablesDisabled,
@@ -77,7 +77,7 @@ func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
 		NFd:                fileutils.GetTotalUsedFds(),
 		NFd:                fileutils.GetTotalUsedFds(),
 		NGoroutines:        runtime.NumGoroutine(),
 		NGoroutines:        runtime.NumGoroutine(),
 		SystemTime:         time.Now().Format(time.RFC3339Nano),
 		SystemTime:         time.Now().Format(time.RFC3339Nano),
-		ExecutionDriver:    daemon.ExecutionDriver().Name(),
+		ExecutionDriver:    daemon.ExecutionDriver(ctx).Name(),
 		LoggingDriver:      daemon.defaultLogConfig.Type,
 		LoggingDriver:      daemon.defaultLogConfig.Type,
 		NEventsListener:    daemon.EventsService.SubscribersCount(),
 		NEventsListener:    daemon.EventsService.SubscribersCount(),
 		KernelVersion:      kernelVersion,
 		KernelVersion:      kernelVersion,

+ 5 - 5
daemon/list.go

@@ -36,7 +36,7 @@ const (
 var errStopIteration = errors.New("container list iteration stopped")
 var errStopIteration = errors.New("container list iteration stopped")
 
 
 // List returns an array of all containers registered in the daemon.
 // List returns an array of all containers registered in the daemon.
-func (daemon *Daemon) List() []*Container {
+func (daemon *Daemon) List(ctx context.Context) []*Container {
 	return daemon.containers.List()
 	return daemon.containers.List()
 }
 }
 
 
@@ -93,7 +93,7 @@ func (daemon *Daemon) reduceContainers(ctx context.Context, config *ContainersCo
 		return nil, err
 		return nil, err
 	}
 	}
 
 
-	for _, container := range daemon.List() {
+	for _, container := range daemon.List(ctx) {
 		t, err := daemon.reducePsContainer(ctx, container, fctx, reducer)
 		t, err := daemon.reducePsContainer(ctx, container, fctx, reducer)
 		if err != nil {
 		if err != nil {
 			if err != errStopIteration {
 			if err != errStopIteration {
@@ -160,11 +160,11 @@ func (daemon *Daemon) foldFilter(ctx context.Context, config *ContainersConfig)
 	var ancestorFilter bool
 	var ancestorFilter bool
 	if ancestors, ok := psFilters["ancestor"]; ok {
 	if ancestors, ok := psFilters["ancestor"]; ok {
 		ancestorFilter = true
 		ancestorFilter = true
-		byParents := daemon.Graph().ByParent()
+		byParents := daemon.Graph(ctx).ByParent()
 		// The idea is to walk the graph down the most "efficient" way.
 		// The idea is to walk the graph down the most "efficient" way.
 		for _, ancestor := range ancestors {
 		for _, ancestor := range ancestors {
 			// First, get the imageId of the ancestor filter (yay)
 			// First, get the imageId of the ancestor filter (yay)
-			image, err := daemon.Repositories().LookupImage(ancestor)
+			image, err := daemon.Repositories(ctx).LookupImage(ancestor)
 			if err != nil {
 			if err != nil {
 				logrus.Warnf("Error while looking up for image %v", ancestor)
 				logrus.Warnf("Error while looking up for image %v", ancestor)
 				continue
 				continue
@@ -293,7 +293,7 @@ func (daemon *Daemon) transformContainer(ctx context.Context, container *Contain
 		Names: lctx.names[container.ID],
 		Names: lctx.names[container.ID],
 	}
 	}
 
 
-	img, err := daemon.Repositories().LookupImage(container.Config.Image)
+	img, err := daemon.Repositories(ctx).LookupImage(container.Config.Image)
 	if err != nil {
 	if err != nil {
 		// If the image can no longer be found by its original reference,
 		// If the image can no longer be found by its original reference,
 		// it makes sense to show the ID instead of a stale reference.
 		// it makes sense to show the ID instead of a stale reference.

+ 1 - 1
daemon/top_unix.go

@@ -31,7 +31,7 @@ func (daemon *Daemon) ContainerTop(ctx context.Context, name string, psArgs stri
 		return nil, derr.ErrorCodeNotRunning.WithArgs(name)
 		return nil, derr.ErrorCodeNotRunning.WithArgs(name)
 	}
 	}
 
 
-	pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID)
+	pids, err := daemon.ExecutionDriver(ctx).GetPidsForContainer(container.ID)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}

+ 14 - 9
docker/daemon.go

@@ -151,6 +151,11 @@ func getGlobalFlag() (globalFlag *flag.Flag) {
 
 
 // CmdDaemon is the daemon command, called the raw arguments after `docker daemon`.
 // CmdDaemon is the daemon command, called the raw arguments after `docker daemon`.
 func (cli *DaemonCli) CmdDaemon(args ...string) error {
 func (cli *DaemonCli) CmdDaemon(args ...string) error {
+	// This may need to be made even more global - it all depends
+	// on whether we want the CLI to have a context object too.
+	// For now we'll leave it as a daemon-side object only.
+	ctx := context.Background()
+
 	// warn from uuid package when running the daemon
 	// warn from uuid package when running the daemon
 	uuid.Loggerf = logrus.Warnf
 	uuid.Loggerf = logrus.Warnf
 
 
@@ -225,7 +230,7 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
 		serverConfig.TLSConfig = tlsConfig
 		serverConfig.TLSConfig = tlsConfig
 	}
 	}
 
 
-	api := apiserver.New(serverConfig)
+	api := apiserver.New(ctx, serverConfig)
 
 
 	// The serve API routine never exits unless an error occurs
 	// The serve API routine never exits unless an error occurs
 	// We need to start it as a goroutine and wait on it so
 	// We need to start it as a goroutine and wait on it so
@@ -246,7 +251,7 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
 	cli.TrustKeyPath = commonFlags.TrustKey
 	cli.TrustKeyPath = commonFlags.TrustKey
 
 
 	registryService := registry.NewService(cli.registryOptions)
 	registryService := registry.NewService(cli.registryOptions)
-	d, err := daemon.NewDaemon(cli.Config, registryService)
+	d, err := daemon.NewDaemon(ctx, cli.Config, registryService)
 	if err != nil {
 	if err != nil {
 		if pfile != nil {
 		if pfile != nil {
 			if err := pfile.Remove(); err != nil {
 			if err := pfile.Remove(); err != nil {
@@ -261,14 +266,14 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
 	logrus.WithFields(logrus.Fields{
 	logrus.WithFields(logrus.Fields{
 		"version":     dockerversion.VERSION,
 		"version":     dockerversion.VERSION,
 		"commit":      dockerversion.GITCOMMIT,
 		"commit":      dockerversion.GITCOMMIT,
-		"execdriver":  d.ExecutionDriver().Name(),
-		"graphdriver": d.GraphDriver().String(),
+		"execdriver":  d.ExecutionDriver(ctx).Name(),
+		"graphdriver": d.GraphDriver(ctx).String(),
 	}).Info("Docker daemon")
 	}).Info("Docker daemon")
 
 
 	signal.Trap(func() {
 	signal.Trap(func() {
 		api.Close()
 		api.Close()
 		<-serveAPIWait
 		<-serveAPIWait
-		shutdownDaemon(d, 15)
+		shutdownDaemon(ctx, d, 15)
 		if pfile != nil {
 		if pfile != nil {
 			if err := pfile.Remove(); err != nil {
 			if err := pfile.Remove(); err != nil {
 				logrus.Error(err)
 				logrus.Error(err)
@@ -278,12 +283,12 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
 
 
 	// after the daemon is done setting up we can tell the api to start
 	// after the daemon is done setting up we can tell the api to start
 	// accepting connections with specified daemon
 	// accepting connections with specified daemon
-	api.AcceptConnections(d)
+	api.AcceptConnections(ctx, d)
 
 
 	// Daemon is fully initialized and handling API traffic
 	// Daemon is fully initialized and handling API traffic
 	// Wait for serve API to complete
 	// Wait for serve API to complete
 	errAPI := <-serveAPIWait
 	errAPI := <-serveAPIWait
-	shutdownDaemon(d, 15)
+	shutdownDaemon(ctx, d, 15)
 	if errAPI != nil {
 	if errAPI != nil {
 		if pfile != nil {
 		if pfile != nil {
 			if err := pfile.Remove(); err != nil {
 			if err := pfile.Remove(); err != nil {
@@ -298,10 +303,10 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
 // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
 // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
 // d.Shutdown() is waiting too long to kill container or worst it's
 // d.Shutdown() is waiting too long to kill container or worst it's
 // blocked there
 // blocked there
-func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) {
+func shutdownDaemon(ctx context.Context, d *daemon.Daemon, timeout time.Duration) {
 	ch := make(chan struct{})
 	ch := make(chan struct{})
 	go func() {
 	go func() {
-		d.Shutdown(context.Background())
+		d.Shutdown(ctx)
 		close(ch)
 		close(ch)
 	}()
 	}()
 	select {
 	select {