daemon.go 41 KB

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