daemon.go 41 KB

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