daemon.go 41 KB

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