Browse code

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 authored on 2015/09/30 02:40:17
Showing 17 changed files
... ...
@@ -112,7 +112,7 @@ func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
112 112
 			OutStream:   output,
113 113
 		}
114 114
 
115
-		err = s.daemon.Repositories().Pull(ctx, image, tag, imagePullConfig)
115
+		err = s.daemon.Repositories(ctx).Pull(ctx, image, tag, imagePullConfig)
116 116
 	} else { //import
117 117
 		if tag == "" {
118 118
 			repo, tag = parsers.ParseRepositoryTag(repo)
... ...
@@ -129,7 +129,7 @@ func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
129 129
 			return err
130 130
 		}
131 131
 
132
-		err = s.daemon.Repositories().Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
132
+		err = s.daemon.Repositories(ctx).Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
133 133
 	}
134 134
 	if err != nil {
135 135
 		if !output.Flushed() {
... ...
@@ -184,7 +184,7 @@ func (s *Server) postImagesPush(ctx context.Context, w http.ResponseWriter, r *h
184 184
 
185 185
 	w.Header().Set("Content-Type", "application/json")
186 186
 
187
-	if err := s.daemon.Repositories().Push(ctx, name, imagePushConfig); err != nil {
187
+	if err := s.daemon.Repositories(ctx).Push(ctx, name, imagePushConfig); err != nil {
188 188
 		if !output.Flushed() {
189 189
 			return err
190 190
 		}
... ...
@@ -212,7 +212,7 @@ func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
212 212
 		names = r.Form["names"]
213 213
 	}
214 214
 
215
-	if err := s.daemon.Repositories().ImageExport(names, output); err != nil {
215
+	if err := s.daemon.Repositories(ctx).ImageExport(names, output); err != nil {
216 216
 		if !output.Flushed() {
217 217
 			return err
218 218
 		}
... ...
@@ -223,7 +223,7 @@ func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
223 223
 }
224 224
 
225 225
 func (s *Server) postImagesLoad(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
226
-	return s.daemon.Repositories().Load(r.Body, w)
226
+	return s.daemon.Repositories(ctx).Load(r.Body, w)
227 227
 }
228 228
 
229 229
 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 *
256 256
 		return fmt.Errorf("Missing parameter")
257 257
 	}
258 258
 
259
-	imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
259
+	imageInspect, err := s.daemon.Repositories(ctx).Lookup(vars["name"])
260 260
 	if err != nil {
261 261
 		return err
262 262
 	}
... ...
@@ -364,7 +364,7 @@ func (s *Server) getImagesJSON(ctx context.Context, w http.ResponseWriter, r *ht
364 364
 	}
365 365
 
366 366
 	// FIXME: The filter parameter could just be a match filter
367
-	images, err := s.daemon.Repositories().Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
367
+	images, err := s.daemon.Repositories(ctx).Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
368 368
 	if err != nil {
369 369
 		return err
370 370
 	}
... ...
@@ -378,7 +378,7 @@ func (s *Server) getImagesHistory(ctx context.Context, w http.ResponseWriter, r
378 378
 	}
379 379
 
380 380
 	name := vars["name"]
381
-	history, err := s.daemon.Repositories().History(name)
381
+	history, err := s.daemon.Repositories(ctx).History(name)
382 382
 	if err != nil {
383 383
 		return err
384 384
 	}
... ...
@@ -398,7 +398,7 @@ func (s *Server) postImagesTag(ctx context.Context, w http.ResponseWriter, r *ht
398 398
 	tag := r.Form.Get("tag")
399 399
 	force := boolValue(r, "force")
400 400
 	name := vars["name"]
401
-	if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil {
401
+	if err := s.daemon.Repositories(ctx).Tag(repo, tag, name, force); err != nil {
402 402
 		return err
403 403
 	}
404 404
 	s.daemon.EventsService.Log(ctx, "tag", utils.ImageReference(repo, tag), "")
... ...
@@ -42,12 +42,12 @@ type Server struct {
42 42
 }
43 43
 
44 44
 // New returns a new instance of the server based on the specified configuration.
45
-func New(cfg *Config) *Server {
45
+func New(ctx context.Context, cfg *Config) *Server {
46 46
 	srv := &Server{
47 47
 		cfg:   cfg,
48 48
 		start: make(chan struct{}),
49 49
 	}
50
-	srv.router = createRouter(srv)
50
+	srv.router = createRouter(ctx, srv)
51 51
 	return srv
52 52
 }
53 53
 
... ...
@@ -291,7 +291,7 @@ func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
291 291
 	return
292 292
 }
293 293
 
294
-func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
294
+func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
295 295
 	return func(w http.ResponseWriter, r *http.Request) {
296 296
 		// log the handler generation
297 297
 		logrus.Debugf("Calling %s %s", localMethod, localRoute)
... ...
@@ -303,8 +303,6 @@ func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHan
303 303
 		// apply to all requests. Data that is specific to the
304 304
 		// immediate function being called should still be passed
305 305
 		// as 'args' on the function call.
306
-		ctx := context.Background()
307
-
308 306
 		reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
309 307
 		ctx = context.WithValue(ctx, context.RequestID, reqID)
310 308
 		handlerFunc := s.handleWithGlobalMiddlewares(localHandler)
... ...
@@ -318,7 +316,7 @@ func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHan
318 318
 
319 319
 // createRouter initializes the main router the server uses.
320 320
 // we keep enableCors just for legacy usage, need to be removed in the future
321
-func createRouter(s *Server) *mux.Router {
321
+func createRouter(ctx context.Context, s *Server) *mux.Router {
322 322
 	r := mux.NewRouter()
323 323
 	if os.Getenv("DEBUG") != "" {
324 324
 		profilerSetup(r, "/debug/")
... ...
@@ -398,7 +396,7 @@ func createRouter(s *Server) *mux.Router {
398 398
 			localMethod := method
399 399
 
400 400
 			// build the handler function
401
-			f := s.makeHTTPHandler(localMethod, localRoute, localFct)
401
+			f := s.makeHTTPHandler(ctx, localMethod, localRoute, localFct)
402 402
 
403 403
 			// add the new route
404 404
 			if localRoute == "" {
... ...
@@ -2,8 +2,12 @@
2 2
 
3 3
 package server
4 4
 
5
-func (s *Server) registerSubRouter() {
6
-	httpHandler := s.daemon.NetworkAPIRouter()
5
+import (
6
+	"github.com/docker/docker/context"
7
+)
8
+
9
+func (s *Server) registerSubRouter(ctx context.Context) {
10
+	httpHandler := s.daemon.NetworkAPIRouter(ctx)
7 11
 
8 12
 	subrouter := s.router.PathPrefix("/v{version:[0-9.]+}/networks").Subrouter()
9 13
 	subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler)
... ...
@@ -2,5 +2,9 @@
2 2
 
3 3
 package server
4 4
 
5
-func (s *Server) registerSubRouter() {
5
+import (
6
+	"github.com/docker/docker/context"
7
+)
8
+
9
+func (s *Server) registerSubRouter(ctx context.Context) {
6 10
 }
... ...
@@ -8,6 +8,7 @@ import (
8 8
 	"net/http"
9 9
 	"strconv"
10 10
 
11
+	"github.com/docker/docker/context"
11 12
 	"github.com/docker/docker/daemon"
12 13
 	"github.com/docker/docker/pkg/sockets"
13 14
 	"github.com/docker/libnetwork/portallocator"
... ...
@@ -63,10 +64,10 @@ func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
63 63
 // AcceptConnections allows clients to connect to the API server.
64 64
 // Referenced Daemon is notified about this server, and waits for the
65 65
 // daemon acknowledgement before the incoming connections are accepted.
66
-func (s *Server) AcceptConnections(d *daemon.Daemon) {
66
+func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
67 67
 	// Tell the init daemon we are accepting requests
68 68
 	s.daemon = d
69
-	s.registerSubRouter()
69
+	s.registerSubRouter(ctx)
70 70
 	go systemdDaemon.SdNotify("READY=1")
71 71
 	// close the lock so the listeners start accepting connections
72 72
 	select {
... ...
@@ -7,6 +7,7 @@ import (
7 7
 	"net"
8 8
 	"net/http"
9 9
 
10
+	"github.com/docker/docker/context"
10 11
 	"github.com/docker/docker/daemon"
11 12
 )
12 13
 
... ...
@@ -42,9 +43,9 @@ func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
42 42
 }
43 43
 
44 44
 // AcceptConnections allows router to start listening for the incoming requests.
45
-func (s *Server) AcceptConnections(d *daemon.Daemon) {
45
+func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
46 46
 	s.daemon = d
47
-	s.registerSubRouter()
47
+	s.registerSubRouter(ctx)
48 48
 	// close the lock so the listeners start accepting connections
49 49
 	select {
50 50
 	case <-s.start:
... ...
@@ -209,7 +209,7 @@ func from(ctx context.Context, b *builder, args []string, attributes map[string]
209 209
 		return nil
210 210
 	}
211 211
 
212
-	image, err := b.Daemon.Repositories().LookupImage(name)
212
+	image, err := b.Daemon.Repositories(ctx).LookupImage(name)
213 213
 	if b.Pull {
214 214
 		image, err = b.pullImage(ctx, name)
215 215
 		if err != nil {
... ...
@@ -217,7 +217,7 @@ func from(ctx context.Context, b *builder, args []string, attributes map[string]
217 217
 		}
218 218
 	}
219 219
 	if err != nil {
220
-		if b.Daemon.Graph().IsNotExist(err, name) {
220
+		if b.Daemon.Graph(ctx).IsNotExist(err, name) {
221 221
 			image, err = b.pullImage(ctx, name)
222 222
 		}
223 223
 
... ...
@@ -132,7 +132,7 @@ func (b *builder) commit(ctx context.Context, id string, autoCmd *stringutils.St
132 132
 	if err != nil {
133 133
 		return err
134 134
 	}
135
-	b.Daemon.Graph().Retain(b.id, image.ID)
135
+	b.Daemon.Graph(ctx).Retain(b.id, image.ID)
136 136
 	b.activeImages = append(b.activeImages, image.ID)
137 137
 	b.image = image.ID
138 138
 	return nil
... ...
@@ -516,11 +516,11 @@ func (b *builder) pullImage(ctx context.Context, name string) (*image.Image, err
516 516
 		OutStream:  ioutils.NopWriteCloser(b.OutOld),
517 517
 	}
518 518
 
519
-	if err := b.Daemon.Repositories().Pull(ctx, remote, tag, imagePullConfig); err != nil {
519
+	if err := b.Daemon.Repositories(ctx).Pull(ctx, remote, tag, imagePullConfig); err != nil {
520 520
 		return nil, err
521 521
 	}
522 522
 
523
-	image, err := b.Daemon.Repositories().LookupImage(name)
523
+	image, err := b.Daemon.Repositories(ctx).LookupImage(name)
524 524
 	if err != nil {
525 525
 		return nil, err
526 526
 	}
... ...
@@ -600,7 +600,7 @@ func (b *builder) probeCache(ctx context.Context) (bool, error) {
600 600
 	fmt.Fprintf(b.OutStream, " ---> Using cache\n")
601 601
 	logrus.Debugf("[BUILDER] Use cached version")
602 602
 	b.image = cache.ID
603
-	b.Daemon.Graph().Retain(b.id, cache.ID)
603
+	b.Daemon.Graph(ctx).Retain(b.id, cache.ID)
604 604
 	b.activeImages = append(b.activeImages, cache.ID)
605 605
 	return true, nil
606 606
 }
... ...
@@ -230,7 +230,7 @@ func Build(ctx context.Context, d *daemon.Daemon, buildConfig *Config) error {
230 230
 	}
231 231
 
232 232
 	defer func() {
233
-		builder.Daemon.Graph().Release(builder.id, builder.activeImages...)
233
+		builder.Daemon.Graph(ctx).Release(builder.id, builder.activeImages...)
234 234
 	}()
235 235
 
236 236
 	id, err := builder.Run(ctx, context)
... ...
@@ -238,7 +238,7 @@ func Build(ctx context.Context, d *daemon.Daemon, buildConfig *Config) error {
238 238
 		return err
239 239
 	}
240 240
 	if repoName != "" {
241
-		return d.Repositories().Tag(repoName, tag, id, true)
241
+		return d.Repositories(ctx).Tag(repoName, tag, id, true)
242 242
 	}
243 243
 	return nil
244 244
 }
... ...
@@ -30,7 +30,7 @@ func (daemon *Daemon) ContainerCreate(ctx context.Context, name string, config *
30 30
 
31 31
 	container, buildWarnings, err := daemon.Create(ctx, config, hostConfig, name)
32 32
 	if err != nil {
33
-		if daemon.Graph().IsNotExist(err, config.Image) {
33
+		if daemon.Graph(ctx).IsNotExist(err, config.Image) {
34 34
 			if strings.Contains(config.Image, "@") {
35 35
 				return types.ContainerCreateResponse{"", warnings}, derr.ErrorCodeNoSuchImageHash.WithArgs(config.Image)
36 36
 			}
... ...
@@ -253,7 +253,7 @@ func (daemon *Daemon) ensureName(container *Container) error {
253 253
 	return nil
254 254
 }
255 255
 
256
-func (daemon *Daemon) restore() error {
256
+func (daemon *Daemon) restore(ctx context.Context) error {
257 257
 	type cr struct {
258 258
 		container  *Container
259 259
 		registered bool
... ...
@@ -309,7 +309,6 @@ func (daemon *Daemon) restore() error {
309 309
 	}
310 310
 
311 311
 	group := sync.WaitGroup{}
312
-	ctx := context.Background()
313 312
 	for _, c := range containers {
314 313
 		group.Add(1)
315 314
 
... ...
@@ -574,7 +573,7 @@ func (daemon *Daemon) registerLink(parent, child *Container, alias string) error
574 574
 
575 575
 // NewDaemon sets up everything for the daemon to be able to service
576 576
 // requests from the webserver.
577
-func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
577
+func NewDaemon(ctx context.Context, config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
578 578
 	setDefaultMtu(config)
579 579
 
580 580
 	// Ensure we have compatible configuration options
... ...
@@ -642,7 +641,7 @@ func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo
642 642
 	// Ensure the graph driver is shutdown at a later point
643 643
 	defer func() {
644 644
 		if err != nil {
645
-			if err := d.Shutdown(context.Background()); err != nil {
645
+			if err := d.Shutdown(ctx); err != nil {
646 646
 				logrus.Error(err)
647 647
 			}
648 648
 		}
... ...
@@ -786,7 +785,7 @@ func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo
786 786
 
787 787
 	go d.execCommandGC()
788 788
 
789
-	if err := d.restore(); err != nil {
789
+	if err := d.restore(ctx); err != nil {
790 790
 		return nil, err
791 791
 	}
792 792
 
... ...
@@ -799,7 +798,7 @@ func (daemon *Daemon) Shutdown(ctx context.Context) error {
799 799
 	if daemon.containers != nil {
800 800
 		group := sync.WaitGroup{}
801 801
 		logrus.Debug("starting clean shutdown of all containers...")
802
-		for _, container := range daemon.List() {
802
+		for _, container := range daemon.List(ctx) {
803 803
 			c := container
804 804
 			if c.IsRunning() {
805 805
 				logrus.Debugf("stopping %s", c.ID)
... ...
@@ -974,12 +973,12 @@ func (daemon *Daemon) createRootfs(container *Container) error {
974 974
 // which need direct access to daemon.graph.
975 975
 // Once the tests switch to using engine and jobs, this method
976 976
 // can go away.
977
-func (daemon *Daemon) Graph() *graph.Graph {
977
+func (daemon *Daemon) Graph(ctx context.Context) *graph.Graph {
978 978
 	return daemon.graph
979 979
 }
980 980
 
981 981
 // Repositories returns all repositories.
982
-func (daemon *Daemon) Repositories() *graph.TagStore {
982
+func (daemon *Daemon) Repositories(ctx context.Context) *graph.TagStore {
983 983
 	return daemon.repositories
984 984
 }
985 985
 
... ...
@@ -993,13 +992,13 @@ func (daemon *Daemon) systemInitPath() string {
993 993
 
994 994
 // GraphDriver returns the currently used driver for processing
995 995
 // container layers.
996
-func (daemon *Daemon) GraphDriver() graphdriver.Driver {
996
+func (daemon *Daemon) GraphDriver(ctx context.Context) graphdriver.Driver {
997 997
 	return daemon.driver
998 998
 }
999 999
 
1000 1000
 // ExecutionDriver returns the currently used driver for creating and
1001 1001
 // starting execs in a container.
1002
-func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
1002
+func (daemon *Daemon) ExecutionDriver(ctx context.Context) execdriver.Driver {
1003 1003
 	return daemon.execDriver
1004 1004
 }
1005 1005
 
... ...
@@ -1013,7 +1012,7 @@ func (daemon *Daemon) containerGraph() *graphdb.Database {
1013 1013
 // returned if the parent image cannot be found.
1014 1014
 func (daemon *Daemon) ImageGetCached(ctx context.Context, imgID string, config *runconfig.Config) (*image.Image, error) {
1015 1015
 	// Retrieve all images
1016
-	images := daemon.Graph().Map()
1016
+	images := daemon.Graph(ctx).Map()
1017 1017
 
1018 1018
 	// Store the tree in a map of map (map[parentId][childId])
1019 1019
 	imageMap := make(map[string]map[string]struct{})
... ...
@@ -123,8 +123,8 @@ func verifyPlatformContainerSettings(ctx context.Context, daemon *Daemon, hostCo
123 123
 	warnings := []string{}
124 124
 	sysInfo := sysinfo.New(true)
125 125
 
126
-	if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
127
-		return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
126
+	if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver(ctx).Name(), "lxc") {
127
+		return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver(ctx).Name())
128 128
 	}
129 129
 
130 130
 	// memory subsystem checks and adjustments
... ...
@@ -492,7 +492,7 @@ func setupInitLayer(initLayer string) error {
492 492
 
493 493
 // NetworkAPIRouter implements a feature for server-experimental,
494 494
 // directly calling into libnetwork.
495
-func (daemon *Daemon) NetworkAPIRouter() func(w http.ResponseWriter, req *http.Request) {
495
+func (daemon *Daemon) NetworkAPIRouter(ctx context.Context) func(w http.ResponseWriter, req *http.Request) {
496 496
 	return nwapi.NewHTTPHandler(daemon.netController)
497 497
 }
498 498
 
... ...
@@ -54,7 +54,7 @@ import (
54 54
 func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDelete, error) {
55 55
 	records := []types.ImageDelete{}
56 56
 
57
-	img, err := daemon.Repositories().LookupImage(imageRef)
57
+	img, err := daemon.Repositories(ctx).LookupImage(imageRef)
58 58
 	if err != nil {
59 59
 		return nil, err
60 60
 	}
... ...
@@ -66,7 +66,7 @@ func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, p
66 66
 		// true, there are multiple repository references to this
67 67
 		// image, or there are no containers using the given reference.
68 68
 		if !(force || daemon.imageHasMultipleRepositoryReferences(ctx, img.ID)) {
69
-			if container := daemon.getContainerUsingImage(img.ID); container != nil {
69
+			if container := daemon.getContainerUsingImage(ctx, img.ID); container != nil {
70 70
 				// If we removed the repository reference then
71 71
 				// this image would remain "dangling" and since
72 72
 				// we really want to avoid that the client must
... ...
@@ -91,7 +91,7 @@ func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, p
91 91
 		// repository reference to the image then we will want to
92 92
 		// remove that reference.
93 93
 		// FIXME: Is this the behavior we want?
94
-		repoRefs := daemon.Repositories().ByID()[img.ID]
94
+		repoRefs := daemon.Repositories(ctx).ByID()[img.ID]
95 95
 		if len(repoRefs) == 1 {
96 96
 			parsedRef, err := daemon.removeImageRef(ctx, repoRefs[0])
97 97
 			if err != nil {
... ...
@@ -117,13 +117,13 @@ func isImageIDPrefix(imageID, possiblePrefix string) bool {
117 117
 // imageHasMultipleRepositoryReferences returns whether there are multiple
118 118
 // repository references to the given imageID.
119 119
 func (daemon *Daemon) imageHasMultipleRepositoryReferences(ctx context.Context, imageID string) bool {
120
-	return len(daemon.Repositories().ByID()[imageID]) > 1
120
+	return len(daemon.Repositories(ctx).ByID()[imageID]) > 1
121 121
 }
122 122
 
123 123
 // getContainerUsingImage returns a container that was created using the given
124 124
 // imageID. Returns nil if there is no such container.
125
-func (daemon *Daemon) getContainerUsingImage(imageID string) *Container {
126
-	for _, container := range daemon.List() {
125
+func (daemon *Daemon) getContainerUsingImage(ctx context.Context, imageID string) *Container {
126
+	for _, container := range daemon.List(ctx) {
127 127
 		if container.ImageID == imageID {
128 128
 			return container
129 129
 		}
... ...
@@ -146,7 +146,7 @@ func (daemon *Daemon) removeImageRef(ctx context.Context, repositoryRef string)
146 146
 	// Ignore the boolean value returned, as far as we're concerned, this
147 147
 	// is an idempotent operation and it's okay if the reference didn't
148 148
 	// exist in the first place.
149
-	_, err := daemon.Repositories().Delete(repository, ref)
149
+	_, err := daemon.Repositories(ctx).Delete(repository, ref)
150 150
 
151 151
 	return utils.ImageReference(repository, ref), err
152 152
 }
... ...
@@ -157,7 +157,7 @@ func (daemon *Daemon) removeImageRef(ctx context.Context, repositoryRef string)
157 157
 // daemon's event service. An "Untagged" types.ImageDelete is added to the
158 158
 // given list of records.
159 159
 func (daemon *Daemon) removeAllReferencesToImageID(ctx context.Context, imgID string, records *[]types.ImageDelete) error {
160
-	imageRefs := daemon.Repositories().ByID()[imgID]
160
+	imageRefs := daemon.Repositories(ctx).ByID()[imgID]
161 161
 
162 162
 	for _, imageRef := range imageRefs {
163 163
 		parsedRef, err := daemon.removeImageRef(ctx, imageRef)
... ...
@@ -224,7 +224,7 @@ func (daemon *Daemon) imageDeleteHelper(ctx context.Context, img *image.Image, r
224 224
 		return err
225 225
 	}
226 226
 
227
-	if err := daemon.Graph().Delete(img.ID); err != nil {
227
+	if err := daemon.Graph(ctx).Delete(img.ID); err != nil {
228 228
 		return err
229 229
 	}
230 230
 
... ...
@@ -238,7 +238,7 @@ func (daemon *Daemon) imageDeleteHelper(ctx context.Context, img *image.Image, r
238 238
 	// We need to prune the parent image. This means delete it if there are
239 239
 	// no tags/digests referencing it and there are no containers using it (
240 240
 	// either running or stopped).
241
-	parentImg, err := daemon.Graph().Get(img.Parent)
241
+	parentImg, err := daemon.Graph(ctx).Get(img.Parent)
242 242
 	if err != nil {
243 243
 		return derr.ErrorCodeImgNoParent.WithArgs(err)
244 244
 	}
... ...
@@ -271,7 +271,7 @@ func (daemon *Daemon) checkImageDeleteConflict(ctx context.Context, img *image.I
271 271
 
272 272
 func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
273 273
 	// Check if the image ID is being used by a pull or build.
274
-	if daemon.Graph().IsHeld(img.ID) {
274
+	if daemon.Graph(ctx).IsHeld(img.ID) {
275 275
 		return &imageDeleteConflict{
276 276
 			hard:    true,
277 277
 			imgID:   img.ID,
... ...
@@ -280,7 +280,7 @@ func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
280 280
 	}
281 281
 
282 282
 	// Check if the image has any descendent images.
283
-	if daemon.Graph().HasChildren(img) {
283
+	if daemon.Graph(ctx).HasChildren(img) {
284 284
 		return &imageDeleteConflict{
285 285
 			hard:    true,
286 286
 			imgID:   img.ID,
... ...
@@ -289,7 +289,7 @@ func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
289 289
 	}
290 290
 
291 291
 	// Check if any running container is using the image.
292
-	for _, container := range daemon.List() {
292
+	for _, container := range daemon.List(ctx) {
293 293
 		if !container.IsRunning() {
294 294
 			// Skip this until we check for soft conflicts later.
295 295
 			continue
... ...
@@ -309,7 +309,7 @@ func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *ima
309 309
 
310 310
 func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *image.Image) *imageDeleteConflict {
311 311
 	// Check if any repository tags/digest reference this image.
312
-	if daemon.Repositories().HasReferences(img) {
312
+	if daemon.Repositories(ctx).HasReferences(img) {
313 313
 		return &imageDeleteConflict{
314 314
 			imgID:   img.ID,
315 315
 			message: "image is referenced in one or more repositories",
... ...
@@ -317,7 +317,7 @@ func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *ima
317 317
 	}
318 318
 
319 319
 	// Check if any stopped containers reference this image.
320
-	for _, container := range daemon.List() {
320
+	for _, container := range daemon.List(ctx) {
321 321
 		if container.IsRunning() {
322 322
 			// Skip this as it was checked above in hard conflict conditions.
323 323
 			continue
... ...
@@ -338,5 +338,5 @@ func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *ima
338 338
 // that there are no repository references to the given image and it has no
339 339
 // child images.
340 340
 func (daemon *Daemon) imageIsDangling(ctx context.Context, img *image.Image) bool {
341
-	return !(daemon.Repositories().HasReferences(img) || daemon.Graph().HasChildren(img))
341
+	return !(daemon.Repositories(ctx).HasReferences(img) || daemon.Graph(ctx).HasChildren(img))
342 342
 }
... ...
@@ -20,7 +20,7 @@ import (
20 20
 
21 21
 // SystemInfo returns information about the host server the daemon is running on.
22 22
 func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
23
-	images := daemon.Graph().Map()
23
+	images := daemon.Graph(ctx).Map()
24 24
 	var imgcount int
25 25
 	if images == nil {
26 26
 		imgcount = 0
... ...
@@ -66,10 +66,10 @@ func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
66 66
 
67 67
 	v := &types.Info{
68 68
 		ID:                 daemon.ID,
69
-		Containers:         len(daemon.List()),
69
+		Containers:         len(daemon.List(ctx)),
70 70
 		Images:             imgcount,
71
-		Driver:             daemon.GraphDriver().String(),
72
-		DriverStatus:       daemon.GraphDriver().Status(),
71
+		Driver:             daemon.GraphDriver(ctx).String(),
72
+		DriverStatus:       daemon.GraphDriver(ctx).Status(),
73 73
 		IPv4Forwarding:     !sysInfo.IPv4ForwardingDisabled,
74 74
 		BridgeNfIptables:   !sysInfo.BridgeNfCallIptablesDisabled,
75 75
 		BridgeNfIP6tables:  !sysInfo.BridgeNfCallIP6tablesDisabled,
... ...
@@ -77,7 +77,7 @@ func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) {
77 77
 		NFd:                fileutils.GetTotalUsedFds(),
78 78
 		NGoroutines:        runtime.NumGoroutine(),
79 79
 		SystemTime:         time.Now().Format(time.RFC3339Nano),
80
-		ExecutionDriver:    daemon.ExecutionDriver().Name(),
80
+		ExecutionDriver:    daemon.ExecutionDriver(ctx).Name(),
81 81
 		LoggingDriver:      daemon.defaultLogConfig.Type,
82 82
 		NEventsListener:    daemon.EventsService.SubscribersCount(),
83 83
 		KernelVersion:      kernelVersion,
... ...
@@ -36,7 +36,7 @@ const (
36 36
 var errStopIteration = errors.New("container list iteration stopped")
37 37
 
38 38
 // List returns an array of all containers registered in the daemon.
39
-func (daemon *Daemon) List() []*Container {
39
+func (daemon *Daemon) List(ctx context.Context) []*Container {
40 40
 	return daemon.containers.List()
41 41
 }
42 42
 
... ...
@@ -93,7 +93,7 @@ func (daemon *Daemon) reduceContainers(ctx context.Context, config *ContainersCo
93 93
 		return nil, err
94 94
 	}
95 95
 
96
-	for _, container := range daemon.List() {
96
+	for _, container := range daemon.List(ctx) {
97 97
 		t, err := daemon.reducePsContainer(ctx, container, fctx, reducer)
98 98
 		if err != nil {
99 99
 			if err != errStopIteration {
... ...
@@ -160,11 +160,11 @@ func (daemon *Daemon) foldFilter(ctx context.Context, config *ContainersConfig)
160 160
 	var ancestorFilter bool
161 161
 	if ancestors, ok := psFilters["ancestor"]; ok {
162 162
 		ancestorFilter = true
163
-		byParents := daemon.Graph().ByParent()
163
+		byParents := daemon.Graph(ctx).ByParent()
164 164
 		// The idea is to walk the graph down the most "efficient" way.
165 165
 		for _, ancestor := range ancestors {
166 166
 			// First, get the imageId of the ancestor filter (yay)
167
-			image, err := daemon.Repositories().LookupImage(ancestor)
167
+			image, err := daemon.Repositories(ctx).LookupImage(ancestor)
168 168
 			if err != nil {
169 169
 				logrus.Warnf("Error while looking up for image %v", ancestor)
170 170
 				continue
... ...
@@ -293,7 +293,7 @@ func (daemon *Daemon) transformContainer(ctx context.Context, container *Contain
293 293
 		Names: lctx.names[container.ID],
294 294
 	}
295 295
 
296
-	img, err := daemon.Repositories().LookupImage(container.Config.Image)
296
+	img, err := daemon.Repositories(ctx).LookupImage(container.Config.Image)
297 297
 	if err != nil {
298 298
 		// If the image can no longer be found by its original reference,
299 299
 		// it makes sense to show the ID instead of a stale reference.
... ...
@@ -31,7 +31,7 @@ func (daemon *Daemon) ContainerTop(ctx context.Context, name string, psArgs stri
31 31
 		return nil, derr.ErrorCodeNotRunning.WithArgs(name)
32 32
 	}
33 33
 
34
-	pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID)
34
+	pids, err := daemon.ExecutionDriver(ctx).GetPidsForContainer(container.ID)
35 35
 	if err != nil {
36 36
 		return nil, err
37 37
 	}
... ...
@@ -151,6 +151,11 @@ func getGlobalFlag() (globalFlag *flag.Flag) {
151 151
 
152 152
 // CmdDaemon is the daemon command, called the raw arguments after `docker daemon`.
153 153
 func (cli *DaemonCli) CmdDaemon(args ...string) error {
154
+	// This may need to be made even more global - it all depends
155
+	// on whether we want the CLI to have a context object too.
156
+	// For now we'll leave it as a daemon-side object only.
157
+	ctx := context.Background()
158
+
154 159
 	// warn from uuid package when running the daemon
155 160
 	uuid.Loggerf = logrus.Warnf
156 161
 
... ...
@@ -225,7 +230,7 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
225 225
 		serverConfig.TLSConfig = tlsConfig
226 226
 	}
227 227
 
228
-	api := apiserver.New(serverConfig)
228
+	api := apiserver.New(ctx, serverConfig)
229 229
 
230 230
 	// The serve API routine never exits unless an error occurs
231 231
 	// We need to start it as a goroutine and wait on it so
... ...
@@ -246,7 +251,7 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
246 246
 	cli.TrustKeyPath = commonFlags.TrustKey
247 247
 
248 248
 	registryService := registry.NewService(cli.registryOptions)
249
-	d, err := daemon.NewDaemon(cli.Config, registryService)
249
+	d, err := daemon.NewDaemon(ctx, cli.Config, registryService)
250 250
 	if err != nil {
251 251
 		if pfile != nil {
252 252
 			if err := pfile.Remove(); err != nil {
... ...
@@ -261,14 +266,14 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
261 261
 	logrus.WithFields(logrus.Fields{
262 262
 		"version":     dockerversion.VERSION,
263 263
 		"commit":      dockerversion.GITCOMMIT,
264
-		"execdriver":  d.ExecutionDriver().Name(),
265
-		"graphdriver": d.GraphDriver().String(),
264
+		"execdriver":  d.ExecutionDriver(ctx).Name(),
265
+		"graphdriver": d.GraphDriver(ctx).String(),
266 266
 	}).Info("Docker daemon")
267 267
 
268 268
 	signal.Trap(func() {
269 269
 		api.Close()
270 270
 		<-serveAPIWait
271
-		shutdownDaemon(d, 15)
271
+		shutdownDaemon(ctx, d, 15)
272 272
 		if pfile != nil {
273 273
 			if err := pfile.Remove(); err != nil {
274 274
 				logrus.Error(err)
... ...
@@ -278,12 +283,12 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
278 278
 
279 279
 	// after the daemon is done setting up we can tell the api to start
280 280
 	// accepting connections with specified daemon
281
-	api.AcceptConnections(d)
281
+	api.AcceptConnections(ctx, d)
282 282
 
283 283
 	// Daemon is fully initialized and handling API traffic
284 284
 	// Wait for serve API to complete
285 285
 	errAPI := <-serveAPIWait
286
-	shutdownDaemon(d, 15)
286
+	shutdownDaemon(ctx, d, 15)
287 287
 	if errAPI != nil {
288 288
 		if pfile != nil {
289 289
 			if err := pfile.Remove(); err != nil {
... ...
@@ -298,10 +303,10 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
298 298
 // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
299 299
 // d.Shutdown() is waiting too long to kill container or worst it's
300 300
 // blocked there
301
-func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) {
301
+func shutdownDaemon(ctx context.Context, d *daemon.Daemon, timeout time.Duration) {
302 302
 	ch := make(chan struct{})
303 303
 	go func() {
304
-		d.Shutdown(context.Background())
304
+		d.Shutdown(ctx)
305 305
 		close(ch)
306 306
 	}()
307 307
 	select {