1// Package daemon exposes the functions that occur on the host server
2// that the Docker daemon is running.
3//
4// In implementing the various functions of the daemon, there is often
5// a method-specific struct for configuring the runtime behavior.
6package daemon // import "github.com/docker/docker/daemon"
7
8import (
9	"context"
10	"fmt"
11	"io/ioutil"
12	"net"
13	"os"
14	"path"
15	"path/filepath"
16	"runtime"
17	"strings"
18	"sync"
19	"time"
20
21	"github.com/docker/docker/api/types"
22	containertypes "github.com/docker/docker/api/types/container"
23	"github.com/docker/docker/api/types/swarm"
24	"github.com/docker/docker/builder"
25	"github.com/docker/docker/container"
26	"github.com/docker/docker/daemon/config"
27	"github.com/docker/docker/daemon/discovery"
28	"github.com/docker/docker/daemon/events"
29	"github.com/docker/docker/daemon/exec"
30	"github.com/docker/docker/daemon/images"
31	"github.com/docker/docker/daemon/logger"
32	"github.com/docker/docker/daemon/network"
33	"github.com/docker/docker/errdefs"
34	"github.com/sirupsen/logrus"
35	// register graph drivers
36	_ "github.com/docker/docker/daemon/graphdriver/register"
37	"github.com/docker/docker/daemon/stats"
38	dmetadata "github.com/docker/docker/distribution/metadata"
39	"github.com/docker/docker/dockerversion"
40	"github.com/docker/docker/image"
41	"github.com/docker/docker/layer"
42	"github.com/docker/docker/libcontainerd"
43	"github.com/docker/docker/migrate/v1"
44	"github.com/docker/docker/pkg/idtools"
45	"github.com/docker/docker/pkg/locker"
46	"github.com/docker/docker/pkg/plugingetter"
47	"github.com/docker/docker/pkg/sysinfo"
48	"github.com/docker/docker/pkg/system"
49	"github.com/docker/docker/pkg/truncindex"
50	"github.com/docker/docker/plugin"
51	pluginexec "github.com/docker/docker/plugin/executor/containerd"
52	refstore "github.com/docker/docker/reference"
53	"github.com/docker/docker/registry"
54	"github.com/docker/docker/runconfig"
55	volumesservice "github.com/docker/docker/volume/service"
56	"github.com/docker/libnetwork"
57	"github.com/docker/libnetwork/cluster"
58	nwconfig "github.com/docker/libnetwork/config"
59	"github.com/pkg/errors"
60)
61
62// ContainersNamespace is the name of the namespace used for users containers
63const ContainersNamespace = "moby"
64
65var (
66	errSystemNotSupported = errors.New("the Docker daemon is not supported on this platform")
67)
68
69// Daemon holds information about the Docker daemon.
70type Daemon struct {
71	ID                string
72	repository        string
73	containers        container.Store
74	containersReplica container.ViewDB
75	execCommands      *exec.Store
76	imageService      *images.ImageService
77	idIndex           *truncindex.TruncIndex
78	configStore       *config.Config
79	statsCollector    *stats.Collector
80	defaultLogConfig  containertypes.LogConfig
81	RegistryService   registry.Service
82	EventsService     *events.Events
83	netController     libnetwork.NetworkController
84	volumes           *volumesservice.VolumesService
85	discoveryWatcher  discovery.Reloader
86	root              string
87	seccompEnabled    bool
88	apparmorEnabled   bool
89	shutdown          bool
90	idMappings        *idtools.IDMappings
91	// TODO: move graphDrivers field to an InfoService
92	graphDrivers map[string]string // By operating system
93
94	PluginStore           *plugin.Store // todo: remove
95	pluginManager         *plugin.Manager
96	linkIndex             *linkIndex
97	containerd            libcontainerd.Client
98	defaultIsolation      containertypes.Isolation // Default isolation mode on Windows
99	clusterProvider       cluster.Provider
100	cluster               Cluster
101	genericResources      []swarm.GenericResource
102	metricsPluginListener net.Listener
103
104	machineMemory uint64
105
106	seccompProfile     []byte
107	seccompProfilePath string
108
109	diskUsageRunning int32
110	pruneRunning     int32
111	hosts            map[string]bool // hosts stores the addresses the daemon is listening on
112	startupDone      chan struct{}
113
114	attachmentStore       network.AttachmentStore
115	attachableNetworkLock *locker.Locker
116}
117
118// StoreHosts stores the addresses the daemon is listening on
119func (daemon *Daemon) StoreHosts(hosts []string) {
120	if daemon.hosts == nil {
121		daemon.hosts = make(map[string]bool)
122	}
123	for _, h := range hosts {
124		daemon.hosts[h] = true
125	}
126}
127
128// HasExperimental returns whether the experimental features of the daemon are enabled or not
129func (daemon *Daemon) HasExperimental() bool {
130	return daemon.configStore != nil && daemon.configStore.Experimental
131}
132
133func (daemon *Daemon) restore() error {
134	containers := make(map[string]*container.Container)
135
136	logrus.Info("Loading containers: start.")
137
138	dir, err := ioutil.ReadDir(daemon.repository)
139	if err != nil {
140		return err
141	}
142
143	for _, v := range dir {
144		id := v.Name()
145		container, err := daemon.load(id)
146		if err != nil {
147			logrus.Errorf("Failed to load container %v: %v", id, err)
148			continue
149		}
150		if !system.IsOSSupported(container.OS) {
151			logrus.Errorf("Failed to load container %v: %s (%q)", id, system.ErrNotSupportedOperatingSystem, container.OS)
152			continue
153		}
154		// Ignore the container if it does not support the current driver being used by the graph
155		currentDriverForContainerOS := daemon.graphDrivers[container.OS]
156		if (container.Driver == "" && currentDriverForContainerOS == "aufs") || container.Driver == currentDriverForContainerOS {
157			rwlayer, err := daemon.imageService.GetLayerByID(container.ID, container.OS)
158			if err != nil {
159				logrus.Errorf("Failed to load container mount %v: %v", id, err)
160				continue
161			}
162			container.RWLayer = rwlayer
163			logrus.Debugf("Loaded container %v, isRunning: %v", container.ID, container.IsRunning())
164
165			containers[container.ID] = container
166		} else {
167			logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
168		}
169	}
170
171	removeContainers := make(map[string]*container.Container)
172	restartContainers := make(map[*container.Container]chan struct{})
173	activeSandboxes := make(map[string]interface{})
174	for id, c := range containers {
175		if err := daemon.registerName(c); err != nil {
176			logrus.Errorf("Failed to register container name %s: %s", c.ID, err)
177			delete(containers, id)
178			continue
179		}
180		if err := daemon.Register(c); err != nil {
181			logrus.Errorf("Failed to register container %s: %s", c.ID, err)
182			delete(containers, id)
183			continue
184		}
185
186		// The LogConfig.Type is empty if the container was created before docker 1.12 with default log driver.
187		// We should rewrite it to use the daemon defaults.
188		// Fixes https://github.com/docker/docker/issues/22536
189		if c.HostConfig.LogConfig.Type == "" {
190			if err := daemon.mergeAndVerifyLogConfig(&c.HostConfig.LogConfig); err != nil {
191				logrus.Errorf("Failed to verify log config for container %s: %q", c.ID, err)
192				continue
193			}
194		}
195	}
196
197	var (
198		wg      sync.WaitGroup
199		mapLock sync.Mutex
200	)
201	for _, c := range containers {
202		wg.Add(1)
203		go func(c *container.Container) {
204			defer wg.Done()
205			daemon.backportMountSpec(c)
206			if err := daemon.checkpointAndSave(c); err != nil {
207				logrus.WithError(err).WithField("container", c.ID).Error("error saving backported mountspec to disk")
208			}
209
210			daemon.setStateCounter(c)
211
212			logrus.WithFields(logrus.Fields{
213				"container": c.ID,
214				"running":   c.IsRunning(),
215				"paused":    c.IsPaused(),
216			}).Debug("restoring container")
217
218			var (
219				err      error
220				alive    bool
221				ec       uint32
222				exitedAt time.Time
223			)
224
225			alive, _, err = daemon.containerd.Restore(context.Background(), c.ID, c.InitializeStdio)
226			if err != nil && !errdefs.IsNotFound(err) {
227				logrus.Errorf("Failed to restore container %s with containerd: %s", c.ID, err)
228				return
229			}
230			if !alive {
231				ec, exitedAt, err = daemon.containerd.DeleteTask(context.Background(), c.ID)
232				if err != nil && !errdefs.IsNotFound(err) {
233					logrus.WithError(err).Errorf("Failed to delete container %s from containerd", c.ID)
234					return
235				}
236			} else if !daemon.configStore.LiveRestoreEnabled {
237				if err := daemon.kill(c, c.StopSignal()); err != nil && !errdefs.IsNotFound(err) {
238					logrus.WithError(err).WithField("container", c.ID).Error("error shutting down container")
239					return
240				}
241			}
242
243			if c.IsRunning() || c.IsPaused() {
244				c.RestartManager().Cancel() // manually start containers because some need to wait for swarm networking
245
246				if c.IsPaused() && alive {
247					s, err := daemon.containerd.Status(context.Background(), c.ID)
248					if err != nil {
249						logrus.WithError(err).WithField("container", c.ID).
250							Errorf("Failed to get container status")
251					} else {
252						logrus.WithField("container", c.ID).WithField("state", s).
253							Info("restored container paused")
254						switch s {
255						case libcontainerd.StatusPaused, libcontainerd.StatusPausing:
256							// nothing to do
257						case libcontainerd.StatusStopped:
258							alive = false
259						case libcontainerd.StatusUnknown:
260							logrus.WithField("container", c.ID).
261								Error("Unknown status for container during restore")
262						default:
263							// running
264							c.Lock()
265							c.Paused = false
266							daemon.setStateCounter(c)
267							if err := c.CheckpointTo(daemon.containersReplica); err != nil {
268								logrus.WithError(err).WithField("container", c.ID).
269									Error("Failed to update stopped container state")
270							}
271							c.Unlock()
272						}
273					}
274				}
275
276				if !alive {
277					c.Lock()
278					c.SetStopped(&container.ExitStatus{ExitCode: int(ec), ExitedAt: exitedAt})
279					daemon.Cleanup(c)
280					if err := c.CheckpointTo(daemon.containersReplica); err != nil {
281						logrus.Errorf("Failed to update stopped container %s state: %v", c.ID, err)
282					}
283					c.Unlock()
284				}
285
286				// we call Mount and then Unmount to get BaseFs of the container
287				if err := daemon.Mount(c); err != nil {
288					// The mount is unlikely to fail. However, in case mount fails
289					// the container should be allowed to restore here. Some functionalities
290					// (like docker exec -u user) might be missing but container is able to be
291					// stopped/restarted/removed.
292					// See #29365 for related information.
293					// The error is only logged here.
294					logrus.Warnf("Failed to mount container on getting BaseFs path %v: %v", c.ID, err)
295				} else {
296					if err := daemon.Unmount(c); err != nil {
297						logrus.Warnf("Failed to umount container on getting BaseFs path %v: %v", c.ID, err)
298					}
299				}
300
301				c.ResetRestartManager(false)
302				if !c.HostConfig.NetworkMode.IsContainer() && c.IsRunning() {
303					options, err := daemon.buildSandboxOptions(c)
304					if err != nil {
305						logrus.Warnf("Failed build sandbox option to restore container %s: %v", c.ID, err)
306					}
307					mapLock.Lock()
308					activeSandboxes[c.NetworkSettings.SandboxID] = options
309					mapLock.Unlock()
310				}
311			}
312
313			// get list of containers we need to restart
314
315			// Do not autostart containers which
316			// has endpoints in a swarm scope
317			// network yet since the cluster is
318			// not initialized yet. We will start
319			// it after the cluster is
320			// initialized.
321			if daemon.configStore.AutoRestart && c.ShouldRestart() && !c.NetworkSettings.HasSwarmEndpoint && c.HasBeenStartedBefore {
322				mapLock.Lock()
323				restartContainers[c] = make(chan struct{})
324				mapLock.Unlock()
325			} else if c.HostConfig != nil && c.HostConfig.AutoRemove {
326				mapLock.Lock()
327				removeContainers[c.ID] = c
328				mapLock.Unlock()
329			}
330
331			c.Lock()
332			if c.RemovalInProgress {
333				// We probably crashed in the middle of a removal, reset
334				// the flag.
335				//
336				// We DO NOT remove the container here as we do not
337				// know if the user had requested for either the
338				// associated volumes, network links or both to also
339				// be removed. So we put the container in the "dead"
340				// state and leave further processing up to them.
341				logrus.Debugf("Resetting RemovalInProgress flag from %v", c.ID)
342				c.RemovalInProgress = false
343				c.Dead = true
344				if err := c.CheckpointTo(daemon.containersReplica); err != nil {
345					logrus.Errorf("Failed to update RemovalInProgress container %s state: %v", c.ID, err)
346				}
347			}
348			c.Unlock()
349		}(c)
350	}
351	wg.Wait()
352	daemon.netController, err = daemon.initNetworkController(daemon.configStore, activeSandboxes)
353	if err != nil {
354		return fmt.Errorf("Error initializing network controller: %v", err)
355	}
356
357	// Now that all the containers are registered, register the links
358	for _, c := range containers {
359		if err := daemon.registerLinks(c, c.HostConfig); err != nil {
360			logrus.Errorf("failed to register link for container %s: %v", c.ID, err)
361		}
362	}
363
364	group := sync.WaitGroup{}
365	for c, notifier := range restartContainers {
366		group.Add(1)
367
368		go func(c *container.Container, chNotify chan struct{}) {
369			defer group.Done()
370
371			logrus.Debugf("Starting container %s", c.ID)
372
373			// ignore errors here as this is a best effort to wait for children to be
374			//   running before we try to start the container
375			children := daemon.children(c)
376			timeout := time.After(5 * time.Second)
377			for _, child := range children {
378				if notifier, exists := restartContainers[child]; exists {
379					select {
380					case <-notifier:
381					case <-timeout:
382					}
383				}
384			}
385
386			// Make sure networks are available before starting
387			daemon.waitForNetworks(c)
388			if err := daemon.containerStart(c, "", "", true); err != nil {
389				logrus.Errorf("Failed to start container %s: %s", c.ID, err)
390			}
391			close(chNotify)
392		}(c, notifier)
393
394	}
395	group.Wait()
396
397	removeGroup := sync.WaitGroup{}
398	for id := range removeContainers {
399		removeGroup.Add(1)
400		go func(cid string) {
401			if err := daemon.ContainerRm(cid, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
402				logrus.Errorf("Failed to remove container %s: %s", cid, err)
403			}
404			removeGroup.Done()
405		}(id)
406	}
407	removeGroup.Wait()
408
409	// any containers that were started above would already have had this done,
410	// however we need to now prepare the mountpoints for the rest of the containers as well.
411	// This shouldn't cause any issue running on the containers that already had this run.
412	// This must be run after any containers with a restart policy so that containerized plugins
413	// can have a chance to be running before we try to initialize them.
414	for _, c := range containers {
415		// if the container has restart policy, do not
416		// prepare the mountpoints since it has been done on restarting.
417		// This is to speed up the daemon start when a restart container
418		// has a volume and the volume driver is not available.
419		if _, ok := restartContainers[c]; ok {
420			continue
421		} else if _, ok := removeContainers[c.ID]; ok {
422			// container is automatically removed, skip it.
423			continue
424		}
425
426		group.Add(1)
427		go func(c *container.Container) {
428			defer group.Done()
429			if err := daemon.prepareMountPoints(c); err != nil {
430				logrus.Error(err)
431			}
432		}(c)
433	}
434
435	group.Wait()
436
437	logrus.Info("Loading containers: done.")
438
439	return nil
440}
441
442// RestartSwarmContainers restarts any autostart container which has a
443// swarm endpoint.
444func (daemon *Daemon) RestartSwarmContainers() {
445	group := sync.WaitGroup{}
446	for _, c := range daemon.List() {
447		if !c.IsRunning() && !c.IsPaused() {
448			// Autostart all the containers which has a
449			// swarm endpoint now that the cluster is
450			// initialized.
451			if daemon.configStore.AutoRestart && c.ShouldRestart() && c.NetworkSettings.HasSwarmEndpoint && c.HasBeenStartedBefore {
452				group.Add(1)
453				go func(c *container.Container) {
454					defer group.Done()
455					if err := daemon.containerStart(c, "", "", true); err != nil {
456						logrus.Error(err)
457					}
458				}(c)
459			}
460		}
461
462	}
463	group.Wait()
464}
465
466// waitForNetworks is used during daemon initialization when starting up containers
467// It ensures that all of a container's networks are available before the daemon tries to start the container.
468// In practice it just makes sure the discovery service is available for containers which use a network that require discovery.
469func (daemon *Daemon) waitForNetworks(c *container.Container) {
470	if daemon.discoveryWatcher == nil {
471		return
472	}
473	// Make sure if the container has a network that requires discovery that the discovery service is available before starting
474	for netName := range c.NetworkSettings.Networks {
475		// If we get `ErrNoSuchNetwork` here, we can assume that it is due to discovery not being ready
476		// Most likely this is because the K/V store used for discovery is in a container and needs to be started
477		if _, err := daemon.netController.NetworkByName(netName); err != nil {
478			if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
479				continue
480			}
481			// use a longish timeout here due to some slowdowns in libnetwork if the k/v store is on anything other than --net=host
482			// FIXME: why is this slow???
483			logrus.Debugf("Container %s waiting for network to be ready", c.Name)
484			select {
485			case <-daemon.discoveryWatcher.ReadyCh():
486			case <-time.After(60 * time.Second):
487			}
488			return
489		}
490	}
491}
492
493func (daemon *Daemon) children(c *container.Container) map[string]*container.Container {
494	return daemon.linkIndex.children(c)
495}
496
497// parents returns the names of the parent containers of the container
498// with the given name.
499func (daemon *Daemon) parents(c *container.Container) map[string]*container.Container {
500	return daemon.linkIndex.parents(c)
501}
502
503func (daemon *Daemon) registerLink(parent, child *container.Container, alias string) error {
504	fullName := path.Join(parent.Name, alias)
505	if err := daemon.containersReplica.ReserveName(fullName, child.ID); err != nil {
506		if err == container.ErrNameReserved {
507			logrus.Warnf("error registering link for %s, to %s, as alias %s, ignoring: %v", parent.ID, child.ID, alias, err)
508			return nil
509		}
510		return err
511	}
512	daemon.linkIndex.link(parent, child, fullName)
513	return nil
514}
515
516// DaemonJoinsCluster informs the daemon has joined the cluster and provides
517// the handler to query the cluster component
518func (daemon *Daemon) DaemonJoinsCluster(clusterProvider cluster.Provider) {
519	daemon.setClusterProvider(clusterProvider)
520}
521
522// DaemonLeavesCluster informs the daemon has left the cluster
523func (daemon *Daemon) DaemonLeavesCluster() {
524	// Daemon is in charge of removing the attachable networks with
525	// connected containers when the node leaves the swarm
526	daemon.clearAttachableNetworks()
527	// We no longer need the cluster provider, stop it now so that
528	// the network agent will stop listening to cluster events.
529	daemon.setClusterProvider(nil)
530	// Wait for the networking cluster agent to stop
531	daemon.netController.AgentStopWait()
532	// Daemon is in charge of removing the ingress network when the
533	// node leaves the swarm. Wait for job to be done or timeout.
534	// This is called also on graceful daemon shutdown. We need to
535	// wait, because the ingress release has to happen before the
536	// network controller is stopped.
537	if done, err := daemon.ReleaseIngress(); err == nil {
538		select {
539		case <-done:
540		case <-time.After(5 * time.Second):
541			logrus.Warnf("timeout while waiting for ingress network removal")
542		}
543	} else {
544		logrus.Warnf("failed to initiate ingress network removal: %v", err)
545	}
546
547	daemon.attachmentStore.ClearAttachments()
548}
549
550// setClusterProvider sets a component for querying the current cluster state.
551func (daemon *Daemon) setClusterProvider(clusterProvider cluster.Provider) {
552	daemon.clusterProvider = clusterProvider
553	daemon.netController.SetClusterProvider(clusterProvider)
554	daemon.attachableNetworkLock = locker.New()
555}
556
557// IsSwarmCompatible verifies if the current daemon
558// configuration is compatible with the swarm mode
559func (daemon *Daemon) IsSwarmCompatible() error {
560	if daemon.configStore == nil {
561		return nil
562	}
563	return daemon.configStore.IsSwarmCompatible()
564}
565
566// NewDaemon sets up everything for the daemon to be able to service
567// requests from the webserver.
568func NewDaemon(config *config.Config, registryService registry.Service, containerdRemote libcontainerd.Remote, pluginStore *plugin.Store) (daemon *Daemon, err error) {
569	setDefaultMtu(config)
570
571	// Ensure that we have a correct root key limit for launching containers.
572	if err := ModifyRootKeyLimit(); err != nil {
573		logrus.Warnf("unable to modify root key limit, number of containers could be limited by this quota: %v", err)
574	}
575
576	// Ensure we have compatible and valid configuration options
577	if err := verifyDaemonSettings(config); err != nil {
578		return nil, err
579	}
580
581	// Do we have a disabled network?
582	config.DisableBridge = isBridgeNetworkDisabled(config)
583
584	// Verify the platform is supported as a daemon
585	if !platformSupported {
586		return nil, errSystemNotSupported
587	}
588
589	// Validate platform-specific requirements
590	if err := checkSystem(); err != nil {
591		return nil, err
592	}
593
594	idMappings, err := setupRemappedRoot(config)
595	if err != nil {
596		return nil, err
597	}
598	rootIDs := idMappings.RootPair()
599	if err := setupDaemonProcess(config); err != nil {
600		return nil, err
601	}
602
603	// set up the tmpDir to use a canonical path
604	tmp, err := prepareTempDir(config.Root, rootIDs)
605	if err != nil {
606		return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
607	}
608	realTmp, err := getRealPath(tmp)
609	if err != nil {
610		return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
611	}
612	if runtime.GOOS == "windows" {
613		if _, err := os.Stat(realTmp); err != nil && os.IsNotExist(err) {
614			if err := system.MkdirAll(realTmp, 0700, ""); err != nil {
615				return nil, fmt.Errorf("Unable to create the TempDir (%s): %s", realTmp, err)
616			}
617		}
618		os.Setenv("TEMP", realTmp)
619		os.Setenv("TMP", realTmp)
620	} else {
621		os.Setenv("TMPDIR", realTmp)
622	}
623
624	d := &Daemon{
625		configStore: config,
626		PluginStore: pluginStore,
627		startupDone: make(chan struct{}),
628	}
629	// Ensure the daemon is properly shutdown if there is a failure during
630	// initialization
631	defer func() {
632		if err != nil {
633			if err := d.Shutdown(); err != nil {
634				logrus.Error(err)
635			}
636		}
637	}()
638
639	if err := d.setGenericResources(config); err != nil {
640		return nil, err
641	}
642	// set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
643	// on Windows to dump Go routine stacks
644	stackDumpDir := config.Root
645	if execRoot := config.GetExecRoot(); execRoot != "" {
646		stackDumpDir = execRoot
647	}
648	d.setupDumpStackTrap(stackDumpDir)
649
650	if err := d.setupSeccompProfile(); err != nil {
651		return nil, err
652	}
653
654	// Set the default isolation mode (only applicable on Windows)
655	if err := d.setDefaultIsolation(); err != nil {
656		return nil, fmt.Errorf("error setting default isolation mode: %v", err)
657	}
658
659	if err := configureMaxThreads(config); err != nil {
660		logrus.Warnf("Failed to configure golang's threads limit: %v", err)
661	}
662
663	if err := ensureDefaultAppArmorProfile(); err != nil {
664		logrus.Errorf(err.Error())
665	}
666
667	daemonRepo := filepath.Join(config.Root, "containers")
668	if err := idtools.MkdirAllAndChown(daemonRepo, 0700, rootIDs); err != nil {
669		return nil, err
670	}
671
672	// Create the directory where we'll store the runtime scripts (i.e. in
673	// order to support runtimeArgs)
674	daemonRuntimes := filepath.Join(config.Root, "runtimes")
675	if err := system.MkdirAll(daemonRuntimes, 0700, ""); err != nil {
676		return nil, err
677	}
678	if err := d.loadRuntimes(); err != nil {
679		return nil, err
680	}
681
682	if runtime.GOOS == "windows" {
683		if err := system.MkdirAll(filepath.Join(config.Root, "credentialspecs"), 0, ""); err != nil {
684			return nil, err
685		}
686	}
687
688	// On Windows we don't support the environment variable, or a user supplied graphdriver
689	// as Windows has no choice in terms of which graphdrivers to use. It's a case of
690	// running Windows containers on Windows - windowsfilter, running Linux containers on Windows,
691	// lcow. Unix platforms however run a single graphdriver for all containers, and it can
692	// be set through an environment variable, a daemon start parameter, or chosen through
693	// initialization of the layerstore through driver priority order for example.
694	d.graphDrivers = make(map[string]string)
695	layerStores := make(map[string]layer.Store)
696	if runtime.GOOS == "windows" {
697		d.graphDrivers[runtime.GOOS] = "windowsfilter"
698		if system.LCOWSupported() {
699			d.graphDrivers["linux"] = "lcow"
700		}
701	} else {
702		driverName := os.Getenv("DOCKER_DRIVER")
703		if driverName == "" {
704			driverName = config.GraphDriver
705		} else {
706			logrus.Infof("Setting the storage driver from the $DOCKER_DRIVER environment variable (%s)", driverName)
707		}
708		d.graphDrivers[runtime.GOOS] = driverName // May still be empty. Layerstore init determines instead.
709	}
710
711	d.RegistryService = registryService
712	logger.RegisterPluginGetter(d.PluginStore)
713
714	metricsSockPath, err := d.listenMetricsSock()
715	if err != nil {
716		return nil, err
717	}
718	registerMetricsPluginCallback(d.PluginStore, metricsSockPath)
719
720	createPluginExec := func(m *plugin.Manager) (plugin.Executor, error) {
721		return pluginexec.New(getPluginExecRoot(config.Root), containerdRemote, m)
722	}
723
724	// Plugin system initialization should happen before restore. Do not change order.
725	d.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{
726		Root:               filepath.Join(config.Root, "plugins"),
727		ExecRoot:           getPluginExecRoot(config.Root),
728		Store:              d.PluginStore,
729		CreateExecutor:     createPluginExec,
730		RegistryService:    registryService,
731		LiveRestoreEnabled: config.LiveRestoreEnabled,
732		LogPluginEvent:     d.LogPluginEvent, // todo: make private
733		AuthzMiddleware:    config.AuthzMiddleware,
734	})
735	if err != nil {
736		return nil, errors.Wrap(err, "couldn't create plugin manager")
737	}
738
739	if err := d.setupDefaultLogConfig(); err != nil {
740		return nil, err
741	}
742
743	for operatingSystem, gd := range d.graphDrivers {
744		layerStores[operatingSystem], err = layer.NewStoreFromOptions(layer.StoreOptions{
745			Root: config.Root,
746			MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
747			GraphDriver:               gd,
748			GraphDriverOptions:        config.GraphOptions,
749			IDMappings:                idMappings,
750			PluginGetter:              d.PluginStore,
751			ExperimentalEnabled:       config.Experimental,
752			OS:                        operatingSystem,
753		})
754		if err != nil {
755			return nil, err
756		}
757	}
758
759	// As layerstore initialization may set the driver
760	for os := range d.graphDrivers {
761		d.graphDrivers[os] = layerStores[os].DriverName()
762	}
763
764	// Configure and validate the kernels security support. Note this is a Linux/FreeBSD
765	// operation only, so it is safe to pass *just* the runtime OS graphdriver.
766	if err := configureKernelSecuritySupport(config, d.graphDrivers[runtime.GOOS]); err != nil {
767		return nil, err
768	}
769
770	imageRoot := filepath.Join(config.Root, "image", d.graphDrivers[runtime.GOOS])
771	ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
772	if err != nil {
773		return nil, err
774	}
775
776	lgrMap := make(map[string]image.LayerGetReleaser)
777	for os, ls := range layerStores {
778		lgrMap[os] = ls
779	}
780	imageStore, err := image.NewImageStore(ifs, lgrMap)
781	if err != nil {
782		return nil, err
783	}
784
785	d.volumes, err = volumesservice.NewVolumeService(config.Root, d.PluginStore, rootIDs, d)
786	if err != nil {
787		return nil, err
788	}
789
790	trustKey, err := loadOrCreateTrustKey(config.TrustKeyPath)
791	if err != nil {
792		return nil, err
793	}
794
795	trustDir := filepath.Join(config.Root, "trust")
796
797	if err := system.MkdirAll(trustDir, 0700, ""); err != nil {
798		return nil, err
799	}
800
801	// We have a single tag/reference store for the daemon globally. However, it's
802	// stored under the graphdriver. On host platforms which only support a single
803	// container OS, but multiple selectable graphdrivers, this means depending on which
804	// graphdriver is chosen, the global reference store is under there. For
805	// platforms which support multiple container operating systems, this is slightly
806	// more problematic as where does the global ref store get located? Fortunately,
807	// for Windows, which is currently the only daemon supporting multiple container
808	// operating systems, the list of graphdrivers available isn't user configurable.
809	// For backwards compatibility, we just put it under the windowsfilter
810	// directory regardless.
811	refStoreLocation := filepath.Join(imageRoot, `repositories.json`)
812	rs, err := refstore.NewReferenceStore(refStoreLocation)
813	if err != nil {
814		return nil, fmt.Errorf("Couldn't create reference store repository: %s", err)
815	}
816
817	distributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, "distribution"))
818	if err != nil {
819		return nil, err
820	}
821
822	// No content-addressability migration on Windows as it never supported pre-CA
823	if runtime.GOOS != "windows" {
824		migrationStart := time.Now()
825		if err := v1.Migrate(config.Root, d.graphDrivers[runtime.GOOS], layerStores[runtime.GOOS], imageStore, rs, distributionMetadataStore); err != nil {
826			logrus.Errorf("Graph migration failed: %q. Your old graph data was found to be too inconsistent for upgrading to content-addressable storage. Some of the old data was probably not upgraded. We recommend starting over with a clean storage directory if possible.", err)
827		}
828		logrus.Infof("Graph migration to content-addressability took %.2f seconds", time.Since(migrationStart).Seconds())
829	}
830
831	// Discovery is only enabled when the daemon is launched with an address to advertise.  When
832	// initialized, the daemon is registered and we can store the discovery backend as it's read-only
833	if err := d.initDiscovery(config); err != nil {
834		return nil, err
835	}
836
837	sysInfo := sysinfo.New(false)
838	// Check if Devices cgroup is mounted, it is hard requirement for container security,
839	// on Linux.
840	if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled {
841		return nil, errors.New("Devices cgroup isn't mounted")
842	}
843
844	d.ID = trustKey.PublicKey().KeyID()
845	d.repository = daemonRepo
846	d.containers = container.NewMemoryStore()
847	if d.containersReplica, err = container.NewViewDB(); err != nil {
848		return nil, err
849	}
850	d.execCommands = exec.NewStore()
851	d.idIndex = truncindex.NewTruncIndex([]string{})
852	d.statsCollector = d.newStatsCollector(1 * time.Second)
853
854	d.EventsService = events.New()
855	d.root = config.Root
856	d.idMappings = idMappings
857	d.seccompEnabled = sysInfo.Seccomp
858	d.apparmorEnabled = sysInfo.AppArmor
859
860	d.linkIndex = newLinkIndex()
861
862	// TODO: imageStore, distributionMetadataStore, and ReferenceStore are only
863	// used above to run migration. They could be initialized in ImageService
864	// if migration is called from daemon/images. layerStore might move as well.
865	d.imageService = images.NewImageService(images.ImageServiceConfig{
866		ContainerStore:            d.containers,
867		DistributionMetadataStore: distributionMetadataStore,
868		EventsService:             d.EventsService,
869		ImageStore:                imageStore,
870		LayerStores:               layerStores,
871		MaxConcurrentDownloads:    *config.MaxConcurrentDownloads,
872		MaxConcurrentUploads:      *config.MaxConcurrentUploads,
873		ReferenceStore:            rs,
874		RegistryService:           registryService,
875		TrustKey:                  trustKey,
876	})
877
878	go d.execCommandGC()
879
880	d.containerd, err = containerdRemote.NewClient(ContainersNamespace, d)
881	if err != nil {
882		return nil, err
883	}
884
885	if err := d.restore(); err != nil {
886		return nil, err
887	}
888	close(d.startupDone)
889
890	// FIXME: this method never returns an error
891	info, _ := d.SystemInfo()
892
893	engineInfo.WithValues(
894		dockerversion.Version,
895		dockerversion.GitCommit,
896		info.Architecture,
897		info.Driver,
898		info.KernelVersion,
899		info.OperatingSystem,
900		info.OSType,
901		info.ID,
902	).Set(1)
903	engineCpus.Set(float64(info.NCPU))
904	engineMemory.Set(float64(info.MemTotal))
905
906	gd := ""
907	for os, driver := range d.graphDrivers {
908		if len(gd) > 0 {
909			gd += ", "
910		}
911		gd += driver
912		if len(d.graphDrivers) > 1 {
913			gd = fmt.Sprintf("%s (%s)", gd, os)
914		}
915	}
916	logrus.WithFields(logrus.Fields{
917		"version":        dockerversion.Version,
918		"commit":         dockerversion.GitCommit,
919		"graphdriver(s)": gd,
920	}).Info("Docker daemon")
921
922	return d, nil
923}
924
925// DistributionServices returns services controlling daemon storage
926func (daemon *Daemon) DistributionServices() images.DistributionServices {
927	return daemon.imageService.DistributionServices()
928}
929
930func (daemon *Daemon) waitForStartupDone() {
931	<-daemon.startupDone
932}
933
934func (daemon *Daemon) shutdownContainer(c *container.Container) error {
935	stopTimeout := c.StopTimeout()
936
937	// If container failed to exit in stopTimeout seconds of SIGTERM, then using the force
938	if err := daemon.containerStop(c, stopTimeout); err != nil {
939		return fmt.Errorf("Failed to stop container %s with error: %v", c.ID, err)
940	}
941
942	// Wait without timeout for the container to exit.
943	// Ignore the result.
944	<-c.Wait(context.Background(), container.WaitConditionNotRunning)
945	return nil
946}
947
948// ShutdownTimeout returns the timeout (in seconds) before containers are forcibly
949// killed during shutdown. The default timeout can be configured both on the daemon
950// and per container, and the longest timeout will be used. A grace-period of
951// 5 seconds is added to the configured timeout.
952//
953// A negative (-1) timeout means "indefinitely", which means that containers
954// are not forcibly killed, and the daemon shuts down after all containers exit.
955func (daemon *Daemon) ShutdownTimeout() int {
956	shutdownTimeout := daemon.configStore.ShutdownTimeout
957	if shutdownTimeout < 0 {
958		return -1
959	}
960	if daemon.containers == nil {
961		return shutdownTimeout
962	}
963
964	graceTimeout := 5
965	for _, c := range daemon.containers.List() {
966		stopTimeout := c.StopTimeout()
967		if stopTimeout < 0 {
968			return -1
969		}
970		if stopTimeout+graceTimeout > shutdownTimeout {
971			shutdownTimeout = stopTimeout + graceTimeout
972		}
973	}
974	return shutdownTimeout
975}
976
977// Shutdown stops the daemon.
978func (daemon *Daemon) Shutdown() error {
979	daemon.shutdown = true
980	// Keep mounts and networking running on daemon shutdown if
981	// we are to keep containers running and restore them.
982
983	if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
984		// check if there are any running containers, if none we should do some cleanup
985		if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
986			// metrics plugins still need some cleanup
987			daemon.cleanupMetricsPlugins()
988			return nil
989		}
990	}
991
992	if daemon.containers != nil {
993		logrus.Debugf("daemon configured with a %d seconds minimum shutdown timeout", daemon.configStore.ShutdownTimeout)
994		logrus.Debugf("start clean shutdown of all containers with a %d seconds timeout...", daemon.ShutdownTimeout())
995		daemon.containers.ApplyAll(func(c *container.Container) {
996			if !c.IsRunning() {
997				return
998			}
999			logrus.Debugf("stopping %s", c.ID)
1000			if err := daemon.shutdownContainer(c); err != nil {
1001				logrus.Errorf("Stop container error: %v", err)
1002				return
1003			}
1004			if mountid, err := daemon.imageService.GetLayerMountID(c.ID, c.OS); err == nil {
1005				daemon.cleanupMountsByID(mountid)
1006			}
1007			logrus.Debugf("container stopped %s", c.ID)
1008		})
1009	}
1010
1011	if daemon.volumes != nil {
1012		if err := daemon.volumes.Shutdown(); err != nil {
1013			logrus.Errorf("Error shutting down volume store: %v", err)
1014		}
1015	}
1016
1017	if daemon.imageService != nil {
1018		daemon.imageService.Cleanup()
1019	}
1020
1021	// If we are part of a cluster, clean up cluster's stuff
1022	if daemon.clusterProvider != nil {
1023		logrus.Debugf("start clean shutdown of cluster resources...")
1024		daemon.DaemonLeavesCluster()
1025	}
1026
1027	daemon.cleanupMetricsPlugins()
1028
1029	// Shutdown plugins after containers and layerstore. Don't change the order.
1030	daemon.pluginShutdown()
1031
1032	// trigger libnetwork Stop only if it's initialized
1033	if daemon.netController != nil {
1034		daemon.netController.Stop()
1035	}
1036
1037	return daemon.cleanupMounts()
1038}
1039
1040// Mount sets container.BaseFS
1041// (is it not set coming in? why is it unset?)
1042func (daemon *Daemon) Mount(container *container.Container) error {
1043	if container.RWLayer == nil {
1044		return errors.New("RWLayer of container " + container.ID + " is unexpectedly nil")
1045	}
1046	dir, err := container.RWLayer.Mount(container.GetMountLabel())
1047	if err != nil {
1048		return err
1049	}
1050	logrus.Debugf("container mounted via layerStore: %v", dir)
1051
1052	if container.BaseFS != nil && container.BaseFS.Path() != dir.Path() {
1053		// The mount path reported by the graph driver should always be trusted on Windows, since the
1054		// volume path for a given mounted layer may change over time.  This should only be an error
1055		// on non-Windows operating systems.
1056		if runtime.GOOS != "windows" {
1057			daemon.Unmount(container)
1058			return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
1059				daemon.imageService.GraphDriverForOS(container.OS), container.ID, container.BaseFS, dir)
1060		}
1061	}
1062	container.BaseFS = dir // TODO: combine these fields
1063	return nil
1064}
1065
1066// Unmount unsets the container base filesystem
1067func (daemon *Daemon) Unmount(container *container.Container) error {
1068	if container.RWLayer == nil {
1069		return errors.New("RWLayer of container " + container.ID + " is unexpectedly nil")
1070	}
1071	if err := container.RWLayer.Unmount(); err != nil {
1072		logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
1073		return err
1074	}
1075
1076	return nil
1077}
1078
1079// Subnets return the IPv4 and IPv6 subnets of networks that are manager by Docker.
1080func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {
1081	var v4Subnets []net.IPNet
1082	var v6Subnets []net.IPNet
1083
1084	managedNetworks := daemon.netController.Networks()
1085
1086	for _, managedNetwork := range managedNetworks {
1087		v4infos, v6infos := managedNetwork.Info().IpamInfo()
1088		for _, info := range v4infos {
1089			if info.IPAMData.Pool != nil {
1090				v4Subnets = append(v4Subnets, *info.IPAMData.Pool)
1091			}
1092		}
1093		for _, info := range v6infos {
1094			if info.IPAMData.Pool != nil {
1095				v6Subnets = append(v6Subnets, *info.IPAMData.Pool)
1096			}
1097		}
1098	}
1099
1100	return v4Subnets, v6Subnets
1101}
1102
1103// prepareTempDir prepares and returns the default directory to use
1104// for temporary files.
1105// If it doesn't exist, it is created. If it exists, its content is removed.
1106func prepareTempDir(rootDir string, rootIDs idtools.IDPair) (string, error) {
1107	var tmpDir string
1108	if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
1109		tmpDir = filepath.Join(rootDir, "tmp")
1110		newName := tmpDir + "-old"
1111		if err := os.Rename(tmpDir, newName); err == nil {
1112			go func() {
1113				if err := os.RemoveAll(newName); err != nil {
1114					logrus.Warnf("failed to delete old tmp directory: %s", newName)
1115				}
1116			}()
1117		} else if !os.IsNotExist(err) {
1118			logrus.Warnf("failed to rename %s for background deletion: %s. Deleting synchronously", tmpDir, err)
1119			if err := os.RemoveAll(tmpDir); err != nil {
1120				logrus.Warnf("failed to delete old tmp directory: %s", tmpDir)
1121			}
1122		}
1123	}
1124	// We don't remove the content of tmpdir if it's not the default,
1125	// it may hold things that do not belong to us.
1126	return tmpDir, idtools.MkdirAllAndChown(tmpDir, 0700, rootIDs)
1127}
1128
1129func (daemon *Daemon) setGenericResources(conf *config.Config) error {
1130	genericResources, err := config.ParseGenericResources(conf.NodeGenericResources)
1131	if err != nil {
1132		return err
1133	}
1134
1135	daemon.genericResources = genericResources
1136
1137	return nil
1138}
1139
1140func setDefaultMtu(conf *config.Config) {
1141	// do nothing if the config does not have the default 0 value.
1142	if conf.Mtu != 0 {
1143		return
1144	}
1145	conf.Mtu = config.DefaultNetworkMtu
1146}
1147
1148// IsShuttingDown tells whether the daemon is shutting down or not
1149func (daemon *Daemon) IsShuttingDown() bool {
1150	return daemon.shutdown
1151}
1152
1153// initDiscovery initializes the discovery watcher for this daemon.
1154func (daemon *Daemon) initDiscovery(conf *config.Config) error {
1155	advertise, err := config.ParseClusterAdvertiseSettings(conf.ClusterStore, conf.ClusterAdvertise)
1156	if err != nil {
1157		if err == discovery.ErrDiscoveryDisabled {
1158			return nil
1159		}
1160		return err
1161	}
1162
1163	conf.ClusterAdvertise = advertise
1164	discoveryWatcher, err := discovery.Init(conf.ClusterStore, conf.ClusterAdvertise, conf.ClusterOpts)
1165	if err != nil {
1166		return fmt.Errorf("discovery initialization failed (%v)", err)
1167	}
1168
1169	daemon.discoveryWatcher = discoveryWatcher
1170	return nil
1171}
1172
1173func isBridgeNetworkDisabled(conf *config.Config) bool {
1174	return conf.BridgeConfig.Iface == config.DisableNetworkBridge
1175}
1176
1177func (daemon *Daemon) networkOptions(dconfig *config.Config, pg plugingetter.PluginGetter, activeSandboxes map[string]interface{}) ([]nwconfig.Option, error) {
1178	options := []nwconfig.Option{}
1179	if dconfig == nil {
1180		return options, nil
1181	}
1182
1183	options = append(options, nwconfig.OptionExperimental(dconfig.Experimental))
1184	options = append(options, nwconfig.OptionDataDir(dconfig.Root))
1185	options = append(options, nwconfig.OptionExecRoot(dconfig.GetExecRoot()))
1186
1187	dd := runconfig.DefaultDaemonNetworkMode()
1188	dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
1189	options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
1190	options = append(options, nwconfig.OptionDefaultNetwork(dn))
1191
1192	if strings.TrimSpace(dconfig.ClusterStore) != "" {
1193		kv := strings.Split(dconfig.ClusterStore, "://")
1194		if len(kv) != 2 {
1195			return nil, errors.New("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
1196		}
1197		options = append(options, nwconfig.OptionKVProvider(kv[0]))
1198		options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
1199	}
1200	if len(dconfig.ClusterOpts) > 0 {
1201		options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
1202	}
1203
1204	if daemon.discoveryWatcher != nil {
1205		options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
1206	}
1207
1208	if dconfig.ClusterAdvertise != "" {
1209		options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
1210	}
1211
1212	options = append(options, nwconfig.OptionLabels(dconfig.Labels))
1213	options = append(options, driverOptions(dconfig)...)
1214
1215	if len(dconfig.NetworkConfig.DefaultAddressPools.Value()) > 0 {
1216		options = append(options, nwconfig.OptionDefaultAddressPoolConfig(dconfig.NetworkConfig.DefaultAddressPools.Value()))
1217	}
1218
1219	if daemon.configStore != nil && daemon.configStore.LiveRestoreEnabled && len(activeSandboxes) != 0 {
1220		options = append(options, nwconfig.OptionActiveSandboxes(activeSandboxes))
1221	}
1222
1223	if pg != nil {
1224		options = append(options, nwconfig.OptionPluginGetter(pg))
1225	}
1226
1227	options = append(options, nwconfig.OptionNetworkControlPlaneMTU(dconfig.NetworkControlPlaneMTU))
1228
1229	return options, nil
1230}
1231
1232// GetCluster returns the cluster
1233func (daemon *Daemon) GetCluster() Cluster {
1234	return daemon.cluster
1235}
1236
1237// SetCluster sets the cluster
1238func (daemon *Daemon) SetCluster(cluster Cluster) {
1239	daemon.cluster = cluster
1240}
1241
1242func (daemon *Daemon) pluginShutdown() {
1243	manager := daemon.pluginManager
1244	// Check for a valid manager object. In error conditions, daemon init can fail
1245	// and shutdown called, before plugin manager is initialized.
1246	if manager != nil {
1247		manager.Shutdown()
1248	}
1249}
1250
1251// PluginManager returns current pluginManager associated with the daemon
1252func (daemon *Daemon) PluginManager() *plugin.Manager { // set up before daemon to avoid this method
1253	return daemon.pluginManager
1254}
1255
1256// PluginGetter returns current pluginStore associated with the daemon
1257func (daemon *Daemon) PluginGetter() *plugin.Store {
1258	return daemon.PluginStore
1259}
1260
1261// CreateDaemonRoot creates the root for the daemon
1262func CreateDaemonRoot(config *config.Config) error {
1263	// get the canonical path to the Docker root directory
1264	var realRoot string
1265	if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
1266		realRoot = config.Root
1267	} else {
1268		realRoot, err = getRealPath(config.Root)
1269		if err != nil {
1270			return fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
1271		}
1272	}
1273
1274	idMappings, err := setupRemappedRoot(config)
1275	if err != nil {
1276		return err
1277	}
1278	return setupDaemonRoot(config, realRoot, idMappings.RootPair())
1279}
1280
1281// checkpointAndSave grabs a container lock to safely call container.CheckpointTo
1282func (daemon *Daemon) checkpointAndSave(container *container.Container) error {
1283	container.Lock()
1284	defer container.Unlock()
1285	if err := container.CheckpointTo(daemon.containersReplica); err != nil {
1286		return fmt.Errorf("Error saving container state: %v", err)
1287	}
1288	return nil
1289}
1290
1291// because the CLI sends a -1 when it wants to unset the swappiness value
1292// we need to clear it on the server side
1293func fixMemorySwappiness(resources *containertypes.Resources) {
1294	if resources.MemorySwappiness != nil && *resources.MemorySwappiness == -1 {
1295		resources.MemorySwappiness = nil
1296	}
1297}
1298
1299// GetAttachmentStore returns current attachment store associated with the daemon
1300func (daemon *Daemon) GetAttachmentStore() *network.AttachmentStore {
1301	return &daemon.attachmentStore
1302}
1303
1304// IDMappings returns uid/gid mappings for the builder
1305func (daemon *Daemon) IDMappings() *idtools.IDMappings {
1306	return daemon.idMappings
1307}
1308
1309// ImageService returns the Daemon's ImageService
1310func (daemon *Daemon) ImageService() *images.ImageService {
1311	return daemon.imageService
1312}
1313
1314// BuilderBackend returns the backend used by builder
1315func (daemon *Daemon) BuilderBackend() builder.Backend {
1316	return struct {
1317		*Daemon
1318		*images.ImageService
1319	}{daemon, daemon.imageService}
1320}
1321