daemon.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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.
  6. package daemon
  7. import (
  8. "context"
  9. "fmt"
  10. "io/ioutil"
  11. "net"
  12. "os"
  13. "path"
  14. "path/filepath"
  15. "runtime"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Sirupsen/logrus"
  20. containerd "github.com/containerd/containerd/api/grpc/types"
  21. "github.com/docker/docker/api"
  22. "github.com/docker/docker/api/types"
  23. containertypes "github.com/docker/docker/api/types/container"
  24. "github.com/docker/docker/container"
  25. "github.com/docker/docker/daemon/config"
  26. "github.com/docker/docker/daemon/discovery"
  27. "github.com/docker/docker/daemon/events"
  28. "github.com/docker/docker/daemon/exec"
  29. "github.com/docker/docker/daemon/logger"
  30. // register graph drivers
  31. _ "github.com/docker/docker/daemon/graphdriver/register"
  32. "github.com/docker/docker/daemon/initlayer"
  33. "github.com/docker/docker/daemon/stats"
  34. dmetadata "github.com/docker/docker/distribution/metadata"
  35. "github.com/docker/docker/distribution/xfer"
  36. "github.com/docker/docker/dockerversion"
  37. "github.com/docker/docker/image"
  38. "github.com/docker/docker/layer"
  39. "github.com/docker/docker/libcontainerd"
  40. "github.com/docker/docker/migrate/v1"
  41. "github.com/docker/docker/pkg/idtools"
  42. "github.com/docker/docker/pkg/plugingetter"
  43. "github.com/docker/docker/pkg/registrar"
  44. "github.com/docker/docker/pkg/signal"
  45. "github.com/docker/docker/pkg/sysinfo"
  46. "github.com/docker/docker/pkg/system"
  47. "github.com/docker/docker/pkg/truncindex"
  48. "github.com/docker/docker/plugin"
  49. refstore "github.com/docker/docker/reference"
  50. "github.com/docker/docker/registry"
  51. "github.com/docker/docker/runconfig"
  52. volumedrivers "github.com/docker/docker/volume/drivers"
  53. "github.com/docker/docker/volume/local"
  54. "github.com/docker/docker/volume/store"
  55. "github.com/docker/libnetwork"
  56. "github.com/docker/libnetwork/cluster"
  57. nwconfig "github.com/docker/libnetwork/config"
  58. "github.com/docker/libtrust"
  59. "github.com/pkg/errors"
  60. )
  61. var (
  62. // DefaultRuntimeBinary is the default runtime to be used by
  63. // containerd if none is specified
  64. DefaultRuntimeBinary = "docker-runc"
  65. errSystemNotSupported = errors.New("The Docker daemon is not supported on this platform.")
  66. )
  67. type daemonStore struct {
  68. graphDriver string
  69. imageRoot string
  70. imageStore image.Store
  71. layerStore layer.Store
  72. distributionMetadataStore dmetadata.Store
  73. referenceStore refstore.Store
  74. }
  75. // Daemon holds information about the Docker daemon.
  76. type Daemon struct {
  77. ID string
  78. repository string
  79. containers container.Store
  80. execCommands *exec.Store
  81. downloadManager *xfer.LayerDownloadManager
  82. uploadManager *xfer.LayerUploadManager
  83. trustKey libtrust.PrivateKey
  84. idIndex *truncindex.TruncIndex
  85. configStore *config.Config
  86. statsCollector *stats.Collector
  87. defaultLogConfig containertypes.LogConfig
  88. RegistryService registry.Service
  89. EventsService *events.Events
  90. netController libnetwork.NetworkController
  91. volumes *store.VolumeStore
  92. discoveryWatcher discovery.Reloader
  93. root string
  94. seccompEnabled bool
  95. apparmorEnabled bool
  96. shutdown bool
  97. idMappings *idtools.IDMappings
  98. stores map[string]daemonStore // By container target platform
  99. PluginStore *plugin.Store // todo: remove
  100. pluginManager *plugin.Manager
  101. nameIndex *registrar.Registrar
  102. linkIndex *linkIndex
  103. containerd libcontainerd.Client
  104. containerdRemote libcontainerd.Remote
  105. defaultIsolation containertypes.Isolation // Default isolation mode on Windows
  106. clusterProvider cluster.Provider
  107. cluster Cluster
  108. metricsPluginListener net.Listener
  109. machineMemory uint64
  110. seccompProfile []byte
  111. seccompProfilePath string
  112. diskUsageRunning int32
  113. pruneRunning int32
  114. hosts map[string]bool // hosts stores the addresses the daemon is listening on
  115. startupDone chan struct{}
  116. }
  117. // StoreHosts stores the addresses the daemon is listening on
  118. func (daemon *Daemon) StoreHosts(hosts []string) {
  119. if daemon.hosts == nil {
  120. daemon.hosts = make(map[string]bool)
  121. }
  122. for _, h := range hosts {
  123. daemon.hosts[h] = true
  124. }
  125. }
  126. // HasExperimental returns whether the experimental features of the daemon are enabled or not
  127. func (daemon *Daemon) HasExperimental() bool {
  128. if daemon.configStore != nil && daemon.configStore.Experimental {
  129. return true
  130. }
  131. return false
  132. }
  133. func (daemon *Daemon) restore() error {
  134. containers := make(map[string]*container.Container)
  135. logrus.Info("Loading containers: start.")
  136. dir, err := ioutil.ReadDir(daemon.repository)
  137. if err != nil {
  138. return err
  139. }
  140. for _, v := range dir {
  141. id := v.Name()
  142. container, err := daemon.load(id)
  143. if err != nil {
  144. logrus.Errorf("Failed to load container %v: %v", id, err)
  145. continue
  146. }
  147. // Ignore the container if it does not support the current driver being used by the graph
  148. currentDriverForContainerPlatform := daemon.stores[container.Platform].graphDriver
  149. if (container.Driver == "" && currentDriverForContainerPlatform == "aufs") || container.Driver == currentDriverForContainerPlatform {
  150. rwlayer, err := daemon.stores[container.Platform].layerStore.GetRWLayer(container.ID)
  151. if err != nil {
  152. logrus.Errorf("Failed to load container mount %v: %v", id, err)
  153. continue
  154. }
  155. container.RWLayer = rwlayer
  156. logrus.Debugf("Loaded container %v", container.ID)
  157. containers[container.ID] = container
  158. } else {
  159. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  160. }
  161. }
  162. removeContainers := make(map[string]*container.Container)
  163. restartContainers := make(map[*container.Container]chan struct{})
  164. activeSandboxes := make(map[string]interface{})
  165. for id, c := range containers {
  166. if err := daemon.registerName(c); err != nil {
  167. logrus.Errorf("Failed to register container %s: %s", c.ID, err)
  168. delete(containers, id)
  169. continue
  170. }
  171. daemon.Register(c)
  172. // verify that all volumes valid and have been migrated from the pre-1.7 layout
  173. if err := daemon.verifyVolumesInfo(c); err != nil {
  174. // don't skip the container due to error
  175. logrus.Errorf("Failed to verify volumes for container '%s': %v", c.ID, err)
  176. }
  177. // The LogConfig.Type is empty if the container was created before docker 1.12 with default log driver.
  178. // We should rewrite it to use the daemon defaults.
  179. // Fixes https://github.com/docker/docker/issues/22536
  180. if c.HostConfig.LogConfig.Type == "" {
  181. if err := daemon.mergeAndVerifyLogConfig(&c.HostConfig.LogConfig); err != nil {
  182. logrus.Errorf("Failed to verify log config for container %s: %q", c.ID, err)
  183. continue
  184. }
  185. }
  186. }
  187. var wg sync.WaitGroup
  188. var mapLock sync.Mutex
  189. for _, c := range containers {
  190. wg.Add(1)
  191. go func(c *container.Container) {
  192. defer wg.Done()
  193. daemon.backportMountSpec(c)
  194. if err := c.ToDiskLocking(); err != nil {
  195. logrus.WithError(err).WithField("container", c.ID).Error("error saving backported mountspec to disk")
  196. }
  197. daemon.setStateCounter(c)
  198. if c.IsRunning() || c.IsPaused() {
  199. c.RestartManager().Cancel() // manually start containers because some need to wait for swarm networking
  200. if err := daemon.containerd.Restore(c.ID, c.InitializeStdio); err != nil {
  201. logrus.Errorf("Failed to restore %s with containerd: %s", c.ID, err)
  202. return
  203. }
  204. // we call Mount and then Unmount to get BaseFs of the container
  205. if err := daemon.Mount(c); err != nil {
  206. // The mount is unlikely to fail. However, in case mount fails
  207. // the container should be allowed to restore here. Some functionalities
  208. // (like docker exec -u user) might be missing but container is able to be
  209. // stopped/restarted/removed.
  210. // See #29365 for related information.
  211. // The error is only logged here.
  212. logrus.Warnf("Failed to mount container on getting BaseFs path %v: %v", c.ID, err)
  213. } else {
  214. if err := daemon.Unmount(c); err != nil {
  215. logrus.Warnf("Failed to umount container on getting BaseFs path %v: %v", c.ID, err)
  216. }
  217. }
  218. c.ResetRestartManager(false)
  219. if !c.HostConfig.NetworkMode.IsContainer() && c.IsRunning() {
  220. options, err := daemon.buildSandboxOptions(c)
  221. if err != nil {
  222. logrus.Warnf("Failed build sandbox option to restore container %s: %v", c.ID, err)
  223. }
  224. mapLock.Lock()
  225. activeSandboxes[c.NetworkSettings.SandboxID] = options
  226. mapLock.Unlock()
  227. }
  228. }
  229. // fixme: only if not running
  230. // get list of containers we need to restart
  231. if !c.IsRunning() && !c.IsPaused() {
  232. // Do not autostart containers which
  233. // has endpoints in a swarm scope
  234. // network yet since the cluster is
  235. // not initialized yet. We will start
  236. // it after the cluster is
  237. // initialized.
  238. if daemon.configStore.AutoRestart && c.ShouldRestart() && !c.NetworkSettings.HasSwarmEndpoint {
  239. mapLock.Lock()
  240. restartContainers[c] = make(chan struct{})
  241. mapLock.Unlock()
  242. } else if c.HostConfig != nil && c.HostConfig.AutoRemove {
  243. mapLock.Lock()
  244. removeContainers[c.ID] = c
  245. mapLock.Unlock()
  246. }
  247. }
  248. if c.RemovalInProgress {
  249. // We probably crashed in the middle of a removal, reset
  250. // the flag.
  251. //
  252. // We DO NOT remove the container here as we do not
  253. // know if the user had requested for either the
  254. // associated volumes, network links or both to also
  255. // be removed. So we put the container in the "dead"
  256. // state and leave further processing up to them.
  257. logrus.Debugf("Resetting RemovalInProgress flag from %v", c.ID)
  258. c.ResetRemovalInProgress()
  259. c.SetDead()
  260. c.ToDisk()
  261. }
  262. }(c)
  263. }
  264. wg.Wait()
  265. daemon.netController, err = daemon.initNetworkController(daemon.configStore, activeSandboxes)
  266. if err != nil {
  267. return fmt.Errorf("Error initializing network controller: %v", err)
  268. }
  269. // Now that all the containers are registered, register the links
  270. for _, c := range containers {
  271. if err := daemon.registerLinks(c, c.HostConfig); err != nil {
  272. logrus.Errorf("failed to register link for container %s: %v", c.ID, err)
  273. }
  274. }
  275. group := sync.WaitGroup{}
  276. for c, notifier := range restartContainers {
  277. group.Add(1)
  278. go func(c *container.Container, chNotify chan struct{}) {
  279. defer group.Done()
  280. logrus.Debugf("Starting container %s", c.ID)
  281. // ignore errors here as this is a best effort to wait for children to be
  282. // running before we try to start the container
  283. children := daemon.children(c)
  284. timeout := time.After(5 * time.Second)
  285. for _, child := range children {
  286. if notifier, exists := restartContainers[child]; exists {
  287. select {
  288. case <-notifier:
  289. case <-timeout:
  290. }
  291. }
  292. }
  293. // Make sure networks are available before starting
  294. daemon.waitForNetworks(c)
  295. if err := daemon.containerStart(c, "", "", true); err != nil {
  296. logrus.Errorf("Failed to start container %s: %s", c.ID, err)
  297. }
  298. close(chNotify)
  299. }(c, notifier)
  300. }
  301. group.Wait()
  302. removeGroup := sync.WaitGroup{}
  303. for id := range removeContainers {
  304. removeGroup.Add(1)
  305. go func(cid string) {
  306. if err := daemon.ContainerRm(cid, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
  307. logrus.Errorf("Failed to remove container %s: %s", cid, err)
  308. }
  309. removeGroup.Done()
  310. }(id)
  311. }
  312. removeGroup.Wait()
  313. // any containers that were started above would already have had this done,
  314. // however we need to now prepare the mountpoints for the rest of the containers as well.
  315. // This shouldn't cause any issue running on the containers that already had this run.
  316. // This must be run after any containers with a restart policy so that containerized plugins
  317. // can have a chance to be running before we try to initialize them.
  318. for _, c := range containers {
  319. // if the container has restart policy, do not
  320. // prepare the mountpoints since it has been done on restarting.
  321. // This is to speed up the daemon start when a restart container
  322. // has a volume and the volume driver is not available.
  323. if _, ok := restartContainers[c]; ok {
  324. continue
  325. } else if _, ok := removeContainers[c.ID]; ok {
  326. // container is automatically removed, skip it.
  327. continue
  328. }
  329. group.Add(1)
  330. go func(c *container.Container) {
  331. defer group.Done()
  332. if err := daemon.prepareMountPoints(c); err != nil {
  333. logrus.Error(err)
  334. }
  335. }(c)
  336. }
  337. group.Wait()
  338. logrus.Info("Loading containers: done.")
  339. return nil
  340. }
  341. // RestartSwarmContainers restarts any autostart container which has a
  342. // swarm endpoint.
  343. func (daemon *Daemon) RestartSwarmContainers() {
  344. group := sync.WaitGroup{}
  345. for _, c := range daemon.List() {
  346. if !c.IsRunning() && !c.IsPaused() {
  347. // Autostart all the containers which has a
  348. // swarm endpoint now that the cluster is
  349. // initialized.
  350. if daemon.configStore.AutoRestart && c.ShouldRestart() && c.NetworkSettings.HasSwarmEndpoint {
  351. group.Add(1)
  352. go func(c *container.Container) {
  353. defer group.Done()
  354. if err := daemon.containerStart(c, "", "", true); err != nil {
  355. logrus.Error(err)
  356. }
  357. }(c)
  358. }
  359. }
  360. }
  361. group.Wait()
  362. }
  363. // waitForNetworks is used during daemon initialization when starting up containers
  364. // It ensures that all of a container's networks are available before the daemon tries to start the container.
  365. // In practice it just makes sure the discovery service is available for containers which use a network that require discovery.
  366. func (daemon *Daemon) waitForNetworks(c *container.Container) {
  367. if daemon.discoveryWatcher == nil {
  368. return
  369. }
  370. // Make sure if the container has a network that requires discovery that the discovery service is available before starting
  371. for netName := range c.NetworkSettings.Networks {
  372. // If we get `ErrNoSuchNetwork` here, we can assume that it is due to discovery not being ready
  373. // Most likely this is because the K/V store used for discovery is in a container and needs to be started
  374. if _, err := daemon.netController.NetworkByName(netName); err != nil {
  375. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  376. continue
  377. }
  378. // use a longish timeout here due to some slowdowns in libnetwork if the k/v store is on anything other than --net=host
  379. // FIXME: why is this slow???
  380. logrus.Debugf("Container %s waiting for network to be ready", c.Name)
  381. select {
  382. case <-daemon.discoveryWatcher.ReadyCh():
  383. case <-time.After(60 * time.Second):
  384. }
  385. return
  386. }
  387. }
  388. }
  389. func (daemon *Daemon) children(c *container.Container) map[string]*container.Container {
  390. return daemon.linkIndex.children(c)
  391. }
  392. // parents returns the names of the parent containers of the container
  393. // with the given name.
  394. func (daemon *Daemon) parents(c *container.Container) map[string]*container.Container {
  395. return daemon.linkIndex.parents(c)
  396. }
  397. func (daemon *Daemon) registerLink(parent, child *container.Container, alias string) error {
  398. fullName := path.Join(parent.Name, alias)
  399. if err := daemon.nameIndex.Reserve(fullName, child.ID); err != nil {
  400. if err == registrar.ErrNameReserved {
  401. logrus.Warnf("error registering link for %s, to %s, as alias %s, ignoring: %v", parent.ID, child.ID, alias, err)
  402. return nil
  403. }
  404. return err
  405. }
  406. daemon.linkIndex.link(parent, child, fullName)
  407. return nil
  408. }
  409. // DaemonJoinsCluster informs the daemon has joined the cluster and provides
  410. // the handler to query the cluster component
  411. func (daemon *Daemon) DaemonJoinsCluster(clusterProvider cluster.Provider) {
  412. daemon.setClusterProvider(clusterProvider)
  413. }
  414. // DaemonLeavesCluster informs the daemon has left the cluster
  415. func (daemon *Daemon) DaemonLeavesCluster() {
  416. // Daemon is in charge of removing the attachable networks with
  417. // connected containers when the node leaves the swarm
  418. daemon.clearAttachableNetworks()
  419. // We no longer need the cluster provider, stop it now so that
  420. // the network agent will stop listening to cluster events.
  421. daemon.setClusterProvider(nil)
  422. // Wait for the networking cluster agent to stop
  423. daemon.netController.AgentStopWait()
  424. // Daemon is in charge of removing the ingress network when the
  425. // node leaves the swarm. Wait for job to be done or timeout.
  426. // This is called also on graceful daemon shutdown. We need to
  427. // wait, because the ingress release has to happen before the
  428. // network controller is stopped.
  429. if done, err := daemon.ReleaseIngress(); err == nil {
  430. select {
  431. case <-done:
  432. case <-time.After(5 * time.Second):
  433. logrus.Warnf("timeout while waiting for ingress network removal")
  434. }
  435. } else {
  436. logrus.Warnf("failed to initiate ingress network removal: %v", err)
  437. }
  438. }
  439. // setClusterProvider sets a component for querying the current cluster state.
  440. func (daemon *Daemon) setClusterProvider(clusterProvider cluster.Provider) {
  441. daemon.clusterProvider = clusterProvider
  442. daemon.netController.SetClusterProvider(clusterProvider)
  443. }
  444. // IsSwarmCompatible verifies if the current daemon
  445. // configuration is compatible with the swarm mode
  446. func (daemon *Daemon) IsSwarmCompatible() error {
  447. if daemon.configStore == nil {
  448. return nil
  449. }
  450. return daemon.configStore.IsSwarmCompatible()
  451. }
  452. // NewDaemon sets up everything for the daemon to be able to service
  453. // requests from the webserver.
  454. func NewDaemon(config *config.Config, registryService registry.Service, containerdRemote libcontainerd.Remote, pluginStore *plugin.Store) (daemon *Daemon, err error) {
  455. setDefaultMtu(config)
  456. // Ensure that we have a correct root key limit for launching containers.
  457. if err := ModifyRootKeyLimit(); err != nil {
  458. logrus.Warnf("unable to modify root key limit, number of containers could be limited by this quota: %v", err)
  459. }
  460. // Ensure we have compatible and valid configuration options
  461. if err := verifyDaemonSettings(config); err != nil {
  462. return nil, err
  463. }
  464. // Do we have a disabled network?
  465. config.DisableBridge = isBridgeNetworkDisabled(config)
  466. // Verify the platform is supported as a daemon
  467. if !platformSupported {
  468. return nil, errSystemNotSupported
  469. }
  470. // Validate platform-specific requirements
  471. if err := checkSystem(); err != nil {
  472. return nil, err
  473. }
  474. idMappings, err := setupRemappedRoot(config)
  475. if err != nil {
  476. return nil, err
  477. }
  478. rootIDs := idMappings.RootPair()
  479. if err := setupDaemonProcess(config); err != nil {
  480. return nil, err
  481. }
  482. // set up the tmpDir to use a canonical path
  483. tmp, err := prepareTempDir(config.Root, rootIDs)
  484. if err != nil {
  485. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  486. }
  487. realTmp, err := getRealPath(tmp)
  488. if err != nil {
  489. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  490. }
  491. os.Setenv("TMPDIR", realTmp)
  492. d := &Daemon{
  493. configStore: config,
  494. startupDone: make(chan struct{}),
  495. }
  496. // Ensure the daemon is properly shutdown if there is a failure during
  497. // initialization
  498. defer func() {
  499. if err != nil {
  500. if err := d.Shutdown(); err != nil {
  501. logrus.Error(err)
  502. }
  503. }
  504. }()
  505. // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
  506. // on Windows to dump Go routine stacks
  507. stackDumpDir := config.Root
  508. if execRoot := config.GetExecRoot(); execRoot != "" {
  509. stackDumpDir = execRoot
  510. }
  511. d.setupDumpStackTrap(stackDumpDir)
  512. if err := d.setupSeccompProfile(); err != nil {
  513. return nil, err
  514. }
  515. // Set the default isolation mode (only applicable on Windows)
  516. if err := d.setDefaultIsolation(); err != nil {
  517. return nil, fmt.Errorf("error setting default isolation mode: %v", err)
  518. }
  519. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  520. if err := configureMaxThreads(config); err != nil {
  521. logrus.Warnf("Failed to configure golang's threads limit: %v", err)
  522. }
  523. if err := ensureDefaultAppArmorProfile(); err != nil {
  524. logrus.Errorf(err.Error())
  525. }
  526. daemonRepo := filepath.Join(config.Root, "containers")
  527. if err := idtools.MkdirAllAndChown(daemonRepo, 0700, rootIDs); err != nil && !os.IsExist(err) {
  528. return nil, err
  529. }
  530. if runtime.GOOS == "windows" {
  531. if err := system.MkdirAll(filepath.Join(config.Root, "credentialspecs"), 0, ""); err != nil && !os.IsExist(err) {
  532. return nil, err
  533. }
  534. }
  535. // On Windows we don't support the environment variable, or a user supplied graphdriver
  536. // as Windows has no choice in terms of which graphdrivers to use. It's a case of
  537. // running Windows containers on Windows - windowsfilter, running Linux containers on Windows,
  538. // lcow. Unix platforms however run a single graphdriver for all containers, and it can
  539. // be set through an environment variable, a daemon start parameter, or chosen through
  540. // initialization of the layerstore through driver priority order for example.
  541. d.stores = make(map[string]daemonStore)
  542. if runtime.GOOS == "windows" {
  543. d.stores["windows"] = daemonStore{graphDriver: "windowsfilter"}
  544. if system.LCOWSupported() {
  545. d.stores["linux"] = daemonStore{graphDriver: "lcow"}
  546. }
  547. } else {
  548. driverName := os.Getenv("DOCKER_DRIVER")
  549. if driverName == "" {
  550. driverName = config.GraphDriver
  551. }
  552. d.stores[runtime.GOOS] = daemonStore{graphDriver: driverName} // May still be empty. Layerstore init determines instead.
  553. }
  554. d.RegistryService = registryService
  555. d.PluginStore = pluginStore
  556. logger.RegisterPluginGetter(d.PluginStore)
  557. metricsSockPath, err := d.listenMetricsSock()
  558. if err != nil {
  559. return nil, err
  560. }
  561. registerMetricsPluginCallback(d.PluginStore, metricsSockPath)
  562. // Plugin system initialization should happen before restore. Do not change order.
  563. d.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{
  564. Root: filepath.Join(config.Root, "plugins"),
  565. ExecRoot: getPluginExecRoot(config.Root),
  566. Store: d.PluginStore,
  567. Executor: containerdRemote,
  568. RegistryService: registryService,
  569. LiveRestoreEnabled: config.LiveRestoreEnabled,
  570. LogPluginEvent: d.LogPluginEvent, // todo: make private
  571. AuthzMiddleware: config.AuthzMiddleware,
  572. })
  573. if err != nil {
  574. return nil, errors.Wrap(err, "couldn't create plugin manager")
  575. }
  576. var graphDrivers []string
  577. for platform, ds := range d.stores {
  578. ls, err := layer.NewStoreFromOptions(layer.StoreOptions{
  579. StorePath: config.Root,
  580. MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
  581. GraphDriver: ds.graphDriver,
  582. GraphDriverOptions: config.GraphOptions,
  583. IDMappings: idMappings,
  584. PluginGetter: d.PluginStore,
  585. ExperimentalEnabled: config.Experimental,
  586. Platform: platform,
  587. })
  588. if err != nil {
  589. return nil, err
  590. }
  591. ds.graphDriver = ls.DriverName() // As layerstore may set the driver
  592. ds.layerStore = ls
  593. d.stores[platform] = ds
  594. graphDrivers = append(graphDrivers, ls.DriverName())
  595. }
  596. // Configure and validate the kernels security support
  597. if err := configureKernelSecuritySupport(config, graphDrivers); err != nil {
  598. return nil, err
  599. }
  600. logrus.Debugf("Max Concurrent Downloads: %d", *config.MaxConcurrentDownloads)
  601. lsMap := make(map[string]layer.Store)
  602. for platform, ds := range d.stores {
  603. lsMap[platform] = ds.layerStore
  604. }
  605. d.downloadManager = xfer.NewLayerDownloadManager(lsMap, *config.MaxConcurrentDownloads)
  606. logrus.Debugf("Max Concurrent Uploads: %d", *config.MaxConcurrentUploads)
  607. d.uploadManager = xfer.NewLayerUploadManager(*config.MaxConcurrentUploads)
  608. for platform, ds := range d.stores {
  609. imageRoot := filepath.Join(config.Root, "image", ds.graphDriver)
  610. ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
  611. if err != nil {
  612. return nil, err
  613. }
  614. var is image.Store
  615. is, err = image.NewImageStore(ifs, platform, ds.layerStore)
  616. if err != nil {
  617. return nil, err
  618. }
  619. ds.imageRoot = imageRoot
  620. ds.imageStore = is
  621. d.stores[platform] = ds
  622. }
  623. // Configure the volumes driver
  624. volStore, err := d.configureVolumes(rootIDs)
  625. if err != nil {
  626. return nil, err
  627. }
  628. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  629. if err != nil {
  630. return nil, err
  631. }
  632. trustDir := filepath.Join(config.Root, "trust")
  633. if err := system.MkdirAll(trustDir, 0700, ""); err != nil {
  634. return nil, err
  635. }
  636. eventsService := events.New()
  637. for platform, ds := range d.stores {
  638. dms, err := dmetadata.NewFSMetadataStore(filepath.Join(ds.imageRoot, "distribution"), platform)
  639. if err != nil {
  640. return nil, err
  641. }
  642. rs, err := refstore.NewReferenceStore(filepath.Join(ds.imageRoot, "repositories.json"), platform)
  643. if err != nil {
  644. return nil, fmt.Errorf("Couldn't create Tag store repositories: %s", err)
  645. }
  646. ds.distributionMetadataStore = dms
  647. ds.referenceStore = rs
  648. d.stores[platform] = ds
  649. // No content-addressability migration on Windows as it never supported pre-CA
  650. if runtime.GOOS != "windows" {
  651. migrationStart := time.Now()
  652. if err := v1.Migrate(config.Root, ds.graphDriver, ds.layerStore, ds.imageStore, rs, dms); err != nil {
  653. 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)
  654. }
  655. logrus.Infof("Graph migration to content-addressability took %.2f seconds", time.Since(migrationStart).Seconds())
  656. }
  657. }
  658. // Discovery is only enabled when the daemon is launched with an address to advertise. When
  659. // initialized, the daemon is registered and we can store the discovery backend as it's read-only
  660. if err := d.initDiscovery(config); err != nil {
  661. return nil, err
  662. }
  663. sysInfo := sysinfo.New(false)
  664. // Check if Devices cgroup is mounted, it is hard requirement for container security,
  665. // on Linux.
  666. if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled {
  667. return nil, errors.New("Devices cgroup isn't mounted")
  668. }
  669. d.ID = trustKey.PublicKey().KeyID()
  670. d.repository = daemonRepo
  671. d.containers = container.NewMemoryStore()
  672. d.execCommands = exec.NewStore()
  673. d.trustKey = trustKey
  674. d.idIndex = truncindex.NewTruncIndex([]string{})
  675. d.statsCollector = d.newStatsCollector(1 * time.Second)
  676. d.defaultLogConfig = containertypes.LogConfig{
  677. Type: config.LogConfig.Type,
  678. Config: config.LogConfig.Config,
  679. }
  680. d.EventsService = eventsService
  681. d.volumes = volStore
  682. d.root = config.Root
  683. d.idMappings = idMappings
  684. d.seccompEnabled = sysInfo.Seccomp
  685. d.apparmorEnabled = sysInfo.AppArmor
  686. d.nameIndex = registrar.NewRegistrar()
  687. d.linkIndex = newLinkIndex()
  688. d.containerdRemote = containerdRemote
  689. go d.execCommandGC()
  690. d.containerd, err = containerdRemote.Client(d)
  691. if err != nil {
  692. return nil, err
  693. }
  694. if err := d.restore(); err != nil {
  695. return nil, err
  696. }
  697. close(d.startupDone)
  698. // FIXME: this method never returns an error
  699. info, _ := d.SystemInfo()
  700. engineInfo.WithValues(
  701. dockerversion.Version,
  702. dockerversion.GitCommit,
  703. info.Architecture,
  704. info.Driver,
  705. info.KernelVersion,
  706. info.OperatingSystem,
  707. info.OSType,
  708. info.ID,
  709. ).Set(1)
  710. engineCpus.Set(float64(info.NCPU))
  711. engineMemory.Set(float64(info.MemTotal))
  712. gd := ""
  713. for platform, ds := range d.stores {
  714. if len(gd) > 0 {
  715. gd += ", "
  716. }
  717. gd += ds.graphDriver
  718. if len(d.stores) > 1 {
  719. gd = fmt.Sprintf("%s (%s)", gd, platform)
  720. }
  721. }
  722. logrus.WithFields(logrus.Fields{
  723. "version": dockerversion.Version,
  724. "commit": dockerversion.GitCommit,
  725. "graphdriver(s)": gd,
  726. }).Info("Docker daemon")
  727. return d, nil
  728. }
  729. func (daemon *Daemon) waitForStartupDone() {
  730. <-daemon.startupDone
  731. }
  732. func (daemon *Daemon) shutdownContainer(c *container.Container) error {
  733. stopTimeout := c.StopTimeout()
  734. // TODO(windows): Handle docker restart with paused containers
  735. if c.IsPaused() {
  736. // To terminate a process in freezer cgroup, we should send
  737. // SIGTERM to this process then unfreeze it, and the process will
  738. // force to terminate immediately.
  739. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpausing it", c.ID)
  740. sig, ok := signal.SignalMap["TERM"]
  741. if !ok {
  742. return errors.New("System does not support SIGTERM")
  743. }
  744. if err := daemon.kill(c, int(sig)); err != nil {
  745. return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err)
  746. }
  747. if err := daemon.containerUnpause(c); err != nil {
  748. return fmt.Errorf("Failed to unpause container %s with error: %v", c.ID, err)
  749. }
  750. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(stopTimeout)*time.Second)
  751. defer cancel()
  752. // Wait with timeout for container to exit.
  753. if status := <-c.Wait(ctx, container.WaitConditionNotRunning); status.Err() != nil {
  754. logrus.Debugf("container %s failed to exit in %d second of SIGTERM, sending SIGKILL to force", c.ID, stopTimeout)
  755. sig, ok := signal.SignalMap["KILL"]
  756. if !ok {
  757. return errors.New("System does not support SIGKILL")
  758. }
  759. if err := daemon.kill(c, int(sig)); err != nil {
  760. logrus.Errorf("Failed to SIGKILL container %s", c.ID)
  761. }
  762. // Wait for exit again without a timeout.
  763. // Explicitly ignore the result.
  764. _ = <-c.Wait(context.Background(), container.WaitConditionNotRunning)
  765. return status.Err()
  766. }
  767. }
  768. // If container failed to exit in stopTimeout seconds of SIGTERM, then using the force
  769. if err := daemon.containerStop(c, stopTimeout); err != nil {
  770. return fmt.Errorf("Failed to stop container %s with error: %v", c.ID, err)
  771. }
  772. // Wait without timeout for the container to exit.
  773. // Ignore the result.
  774. _ = <-c.Wait(context.Background(), container.WaitConditionNotRunning)
  775. return nil
  776. }
  777. // ShutdownTimeout returns the shutdown timeout based on the max stopTimeout of the containers,
  778. // and is limited by daemon's ShutdownTimeout.
  779. func (daemon *Daemon) ShutdownTimeout() int {
  780. // By default we use daemon's ShutdownTimeout.
  781. shutdownTimeout := daemon.configStore.ShutdownTimeout
  782. graceTimeout := 5
  783. if daemon.containers != nil {
  784. for _, c := range daemon.containers.List() {
  785. if shutdownTimeout >= 0 {
  786. stopTimeout := c.StopTimeout()
  787. if stopTimeout < 0 {
  788. shutdownTimeout = -1
  789. } else {
  790. if stopTimeout+graceTimeout > shutdownTimeout {
  791. shutdownTimeout = stopTimeout + graceTimeout
  792. }
  793. }
  794. }
  795. }
  796. }
  797. return shutdownTimeout
  798. }
  799. // Shutdown stops the daemon.
  800. func (daemon *Daemon) Shutdown() error {
  801. daemon.shutdown = true
  802. // Keep mounts and networking running on daemon shutdown if
  803. // we are to keep containers running and restore them.
  804. if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
  805. // check if there are any running containers, if none we should do some cleanup
  806. if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
  807. // metrics plugins still need some cleanup
  808. daemon.cleanupMetricsPlugins()
  809. return nil
  810. }
  811. }
  812. if daemon.containers != nil {
  813. logrus.Debugf("start clean shutdown of all containers with a %d seconds timeout...", daemon.configStore.ShutdownTimeout)
  814. daemon.containers.ApplyAll(func(c *container.Container) {
  815. if !c.IsRunning() {
  816. return
  817. }
  818. logrus.Debugf("stopping %s", c.ID)
  819. if err := daemon.shutdownContainer(c); err != nil {
  820. logrus.Errorf("Stop container error: %v", err)
  821. return
  822. }
  823. if mountid, err := daemon.stores[c.Platform].layerStore.GetMountID(c.ID); err == nil {
  824. daemon.cleanupMountsByID(mountid)
  825. }
  826. logrus.Debugf("container stopped %s", c.ID)
  827. })
  828. }
  829. if daemon.volumes != nil {
  830. if err := daemon.volumes.Shutdown(); err != nil {
  831. logrus.Errorf("Error shutting down volume store: %v", err)
  832. }
  833. }
  834. for platform, ds := range daemon.stores {
  835. if ds.layerStore != nil {
  836. if err := ds.layerStore.Cleanup(); err != nil {
  837. logrus.Errorf("Error during layer Store.Cleanup(): %v %s", err, platform)
  838. }
  839. }
  840. }
  841. // If we are part of a cluster, clean up cluster's stuff
  842. if daemon.clusterProvider != nil {
  843. logrus.Debugf("start clean shutdown of cluster resources...")
  844. daemon.DaemonLeavesCluster()
  845. }
  846. daemon.cleanupMetricsPlugins()
  847. // Shutdown plugins after containers and layerstore. Don't change the order.
  848. daemon.pluginShutdown()
  849. // trigger libnetwork Stop only if it's initialized
  850. if daemon.netController != nil {
  851. daemon.netController.Stop()
  852. }
  853. if err := daemon.cleanupMounts(); err != nil {
  854. return err
  855. }
  856. return nil
  857. }
  858. // Mount sets container.BaseFS
  859. // (is it not set coming in? why is it unset?)
  860. func (daemon *Daemon) Mount(container *container.Container) error {
  861. dir, err := container.RWLayer.Mount(container.GetMountLabel())
  862. if err != nil {
  863. return err
  864. }
  865. logrus.Debugf("container mounted via layerStore: %v", dir)
  866. if container.BaseFS != dir {
  867. // The mount path reported by the graph driver should always be trusted on Windows, since the
  868. // volume path for a given mounted layer may change over time. This should only be an error
  869. // on non-Windows operating systems.
  870. if container.BaseFS != "" && runtime.GOOS != "windows" {
  871. daemon.Unmount(container)
  872. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  873. daemon.GraphDriverName(container.Platform), container.ID, container.BaseFS, dir)
  874. }
  875. }
  876. container.BaseFS = dir // TODO: combine these fields
  877. return nil
  878. }
  879. // Unmount unsets the container base filesystem
  880. func (daemon *Daemon) Unmount(container *container.Container) error {
  881. if err := container.RWLayer.Unmount(); err != nil {
  882. logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
  883. return err
  884. }
  885. return nil
  886. }
  887. // Subnets return the IPv4 and IPv6 subnets of networks that are manager by Docker.
  888. func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {
  889. var v4Subnets []net.IPNet
  890. var v6Subnets []net.IPNet
  891. managedNetworks := daemon.netController.Networks()
  892. for _, managedNetwork := range managedNetworks {
  893. v4infos, v6infos := managedNetwork.Info().IpamInfo()
  894. for _, info := range v4infos {
  895. if info.IPAMData.Pool != nil {
  896. v4Subnets = append(v4Subnets, *info.IPAMData.Pool)
  897. }
  898. }
  899. for _, info := range v6infos {
  900. if info.IPAMData.Pool != nil {
  901. v6Subnets = append(v6Subnets, *info.IPAMData.Pool)
  902. }
  903. }
  904. }
  905. return v4Subnets, v6Subnets
  906. }
  907. // GraphDriverName returns the name of the graph driver used by the layer.Store
  908. func (daemon *Daemon) GraphDriverName(platform string) string {
  909. return daemon.stores[platform].layerStore.DriverName()
  910. }
  911. // prepareTempDir prepares and returns the default directory to use
  912. // for temporary files.
  913. // If it doesn't exist, it is created. If it exists, its content is removed.
  914. func prepareTempDir(rootDir string, rootIDs idtools.IDPair) (string, error) {
  915. var tmpDir string
  916. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  917. tmpDir = filepath.Join(rootDir, "tmp")
  918. newName := tmpDir + "-old"
  919. if err := os.Rename(tmpDir, newName); err == nil {
  920. go func() {
  921. if err := os.RemoveAll(newName); err != nil {
  922. logrus.Warnf("failed to delete old tmp directory: %s", newName)
  923. }
  924. }()
  925. } else {
  926. logrus.Warnf("failed to rename %s for background deletion: %s. Deleting synchronously", tmpDir, err)
  927. if err := os.RemoveAll(tmpDir); err != nil {
  928. logrus.Warnf("failed to delete old tmp directory: %s", tmpDir)
  929. }
  930. }
  931. }
  932. // We don't remove the content of tmpdir if it's not the default,
  933. // it may hold things that do not belong to us.
  934. return tmpDir, idtools.MkdirAllAndChown(tmpDir, 0700, rootIDs)
  935. }
  936. func (daemon *Daemon) setupInitLayer(initPath string) error {
  937. rootIDs := daemon.idMappings.RootPair()
  938. return initlayer.Setup(initPath, rootIDs)
  939. }
  940. func setDefaultMtu(conf *config.Config) {
  941. // do nothing if the config does not have the default 0 value.
  942. if conf.Mtu != 0 {
  943. return
  944. }
  945. conf.Mtu = config.DefaultNetworkMtu
  946. }
  947. func (daemon *Daemon) configureVolumes(rootIDs idtools.IDPair) (*store.VolumeStore, error) {
  948. volumesDriver, err := local.New(daemon.configStore.Root, rootIDs)
  949. if err != nil {
  950. return nil, err
  951. }
  952. volumedrivers.RegisterPluginGetter(daemon.PluginStore)
  953. if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) {
  954. return nil, errors.New("local volume driver could not be registered")
  955. }
  956. return store.New(daemon.configStore.Root)
  957. }
  958. // IsShuttingDown tells whether the daemon is shutting down or not
  959. func (daemon *Daemon) IsShuttingDown() bool {
  960. return daemon.shutdown
  961. }
  962. // initDiscovery initializes the discovery watcher for this daemon.
  963. func (daemon *Daemon) initDiscovery(conf *config.Config) error {
  964. advertise, err := config.ParseClusterAdvertiseSettings(conf.ClusterStore, conf.ClusterAdvertise)
  965. if err != nil {
  966. if err == discovery.ErrDiscoveryDisabled {
  967. return nil
  968. }
  969. return err
  970. }
  971. conf.ClusterAdvertise = advertise
  972. discoveryWatcher, err := discovery.Init(conf.ClusterStore, conf.ClusterAdvertise, conf.ClusterOpts)
  973. if err != nil {
  974. return fmt.Errorf("discovery initialization failed (%v)", err)
  975. }
  976. daemon.discoveryWatcher = discoveryWatcher
  977. return nil
  978. }
  979. func isBridgeNetworkDisabled(conf *config.Config) bool {
  980. return conf.BridgeConfig.Iface == config.DisableNetworkBridge
  981. }
  982. func (daemon *Daemon) networkOptions(dconfig *config.Config, pg plugingetter.PluginGetter, activeSandboxes map[string]interface{}) ([]nwconfig.Option, error) {
  983. options := []nwconfig.Option{}
  984. if dconfig == nil {
  985. return options, nil
  986. }
  987. options = append(options, nwconfig.OptionExperimental(dconfig.Experimental))
  988. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  989. options = append(options, nwconfig.OptionExecRoot(dconfig.GetExecRoot()))
  990. dd := runconfig.DefaultDaemonNetworkMode()
  991. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  992. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  993. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  994. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  995. kv := strings.Split(dconfig.ClusterStore, "://")
  996. if len(kv) != 2 {
  997. return nil, errors.New("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  998. }
  999. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  1000. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  1001. }
  1002. if len(dconfig.ClusterOpts) > 0 {
  1003. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  1004. }
  1005. if daemon.discoveryWatcher != nil {
  1006. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  1007. }
  1008. if dconfig.ClusterAdvertise != "" {
  1009. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  1010. }
  1011. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  1012. options = append(options, driverOptions(dconfig)...)
  1013. if daemon.configStore != nil && daemon.configStore.LiveRestoreEnabled && len(activeSandboxes) != 0 {
  1014. options = append(options, nwconfig.OptionActiveSandboxes(activeSandboxes))
  1015. }
  1016. if pg != nil {
  1017. options = append(options, nwconfig.OptionPluginGetter(pg))
  1018. }
  1019. return options, nil
  1020. }
  1021. func copyBlkioEntry(entries []*containerd.BlkioStatsEntry) []types.BlkioStatEntry {
  1022. out := make([]types.BlkioStatEntry, len(entries))
  1023. for i, re := range entries {
  1024. out[i] = types.BlkioStatEntry{
  1025. Major: re.Major,
  1026. Minor: re.Minor,
  1027. Op: re.Op,
  1028. Value: re.Value,
  1029. }
  1030. }
  1031. return out
  1032. }
  1033. // GetCluster returns the cluster
  1034. func (daemon *Daemon) GetCluster() Cluster {
  1035. return daemon.cluster
  1036. }
  1037. // SetCluster sets the cluster
  1038. func (daemon *Daemon) SetCluster(cluster Cluster) {
  1039. daemon.cluster = cluster
  1040. }
  1041. func (daemon *Daemon) pluginShutdown() {
  1042. manager := daemon.pluginManager
  1043. // Check for a valid manager object. In error conditions, daemon init can fail
  1044. // and shutdown called, before plugin manager is initialized.
  1045. if manager != nil {
  1046. manager.Shutdown()
  1047. }
  1048. }
  1049. // PluginManager returns current pluginManager associated with the daemon
  1050. func (daemon *Daemon) PluginManager() *plugin.Manager { // set up before daemon to avoid this method
  1051. return daemon.pluginManager
  1052. }
  1053. // PluginGetter returns current pluginStore associated with the daemon
  1054. func (daemon *Daemon) PluginGetter() *plugin.Store {
  1055. return daemon.PluginStore
  1056. }
  1057. // CreateDaemonRoot creates the root for the daemon
  1058. func CreateDaemonRoot(config *config.Config) error {
  1059. // get the canonical path to the Docker root directory
  1060. var realRoot string
  1061. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  1062. realRoot = config.Root
  1063. } else {
  1064. realRoot, err = getRealPath(config.Root)
  1065. if err != nil {
  1066. return fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  1067. }
  1068. }
  1069. idMappings, err := setupRemappedRoot(config)
  1070. if err != nil {
  1071. return err
  1072. }
  1073. return setupDaemonRoot(config, realRoot, idMappings.RootPair())
  1074. }