daemon.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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/sirupsen/logrus"
  30. // register graph drivers
  31. _ "github.com/docker/docker/daemon/graphdriver/register"
  32. "github.com/docker/docker/daemon/initlayer"
  33. "github.com/docker/docker/daemon/stats"
  34. dmetadata "github.com/docker/docker/distribution/metadata"
  35. "github.com/docker/docker/distribution/xfer"
  36. "github.com/docker/docker/dockerversion"
  37. "github.com/docker/docker/image"
  38. "github.com/docker/docker/layer"
  39. "github.com/docker/docker/libcontainerd"
  40. "github.com/docker/docker/migrate/v1"
  41. "github.com/docker/docker/pkg/containerfs"
  42. "github.com/docker/docker/pkg/idtools"
  43. "github.com/docker/docker/pkg/plugingetter"
  44. "github.com/docker/docker/pkg/sysinfo"
  45. "github.com/docker/docker/pkg/system"
  46. "github.com/docker/docker/pkg/truncindex"
  47. "github.com/docker/docker/plugin"
  48. refstore "github.com/docker/docker/reference"
  49. "github.com/docker/docker/registry"
  50. "github.com/docker/docker/runconfig"
  51. volumedrivers "github.com/docker/docker/volume/drivers"
  52. "github.com/docker/docker/volume/local"
  53. "github.com/docker/docker/volume/store"
  54. "github.com/docker/libnetwork"
  55. "github.com/docker/libnetwork/cluster"
  56. nwconfig "github.com/docker/libnetwork/config"
  57. "github.com/docker/libtrust"
  58. "github.com/pkg/errors"
  59. )
  60. var (
  61. // DefaultRuntimeBinary is the default runtime to be used by
  62. // containerd if none is specified
  63. DefaultRuntimeBinary = "docker-runc"
  64. errSystemNotSupported = errors.New("the Docker daemon is not supported on this platform")
  65. )
  66. type daemonStore struct {
  67. graphDriver string
  68. imageRoot string
  69. imageStore image.Store
  70. layerStore layer.Store
  71. distributionMetadataStore dmetadata.Store
  72. }
  73. // Daemon holds information about the Docker daemon.
  74. type Daemon struct {
  75. ID string
  76. repository string
  77. containers container.Store
  78. containersReplica container.ViewDB
  79. execCommands *exec.Store
  80. downloadManager *xfer.LayerDownloadManager
  81. uploadManager *xfer.LayerUploadManager
  82. trustKey libtrust.PrivateKey
  83. idIndex *truncindex.TruncIndex
  84. configStore *config.Config
  85. statsCollector *stats.Collector
  86. defaultLogConfig containertypes.LogConfig
  87. RegistryService registry.Service
  88. EventsService *events.Events
  89. netController libnetwork.NetworkController
  90. volumes *store.VolumeStore
  91. discoveryWatcher discovery.Reloader
  92. root string
  93. seccompEnabled bool
  94. apparmorEnabled bool
  95. shutdown bool
  96. idMappings *idtools.IDMappings
  97. stores map[string]daemonStore // By container target platform
  98. referenceStore refstore.Store
  99. PluginStore *plugin.Store // todo: remove
  100. pluginManager *plugin.Manager
  101. linkIndex *linkIndex
  102. containerd libcontainerd.Client
  103. containerdRemote libcontainerd.Remote
  104. defaultIsolation containertypes.Isolation // Default isolation mode on Windows
  105. clusterProvider cluster.Provider
  106. cluster Cluster
  107. genericResources []swarm.GenericResource
  108. metricsPluginListener net.Listener
  109. machineMemory uint64
  110. seccompProfile []byte
  111. seccompProfilePath string
  112. diskUsageRunning int32
  113. pruneRunning int32
  114. hosts map[string]bool // hosts stores the addresses the daemon is listening on
  115. startupDone chan struct{}
  116. }
  117. // StoreHosts stores the addresses the daemon is listening on
  118. func (daemon *Daemon) StoreHosts(hosts []string) {
  119. if daemon.hosts == nil {
  120. daemon.hosts = make(map[string]bool)
  121. }
  122. for _, h := range hosts {
  123. daemon.hosts[h] = true
  124. }
  125. }
  126. // HasExperimental returns whether the experimental features of the daemon are enabled or not
  127. func (daemon *Daemon) HasExperimental() bool {
  128. if daemon.configStore != nil && daemon.configStore.Experimental {
  129. return true
  130. }
  131. return false
  132. }
  133. func (daemon *Daemon) restore() error {
  134. containers := make(map[string]*container.Container)
  135. logrus.Info("Loading containers: start.")
  136. dir, err := ioutil.ReadDir(daemon.repository)
  137. if err != nil {
  138. return err
  139. }
  140. for _, v := range dir {
  141. id := v.Name()
  142. container, err := daemon.load(id)
  143. if err != nil {
  144. logrus.Errorf("Failed to load container %v: %v", id, err)
  145. continue
  146. }
  147. // Ignore the container if it does not support the current driver being used by the graph
  148. currentDriverForContainerPlatform := daemon.stores[container.Platform].graphDriver
  149. if (container.Driver == "" && currentDriverForContainerPlatform == "aufs") || container.Driver == currentDriverForContainerPlatform {
  150. rwlayer, err := daemon.stores[container.Platform].layerStore.GetRWLayer(container.ID)
  151. if err != nil {
  152. logrus.Errorf("Failed to load container mount %v: %v", id, err)
  153. continue
  154. }
  155. container.RWLayer = rwlayer
  156. logrus.Debugf("Loaded container %v", container.ID)
  157. containers[container.ID] = container
  158. } else {
  159. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  160. }
  161. }
  162. removeContainers := make(map[string]*container.Container)
  163. restartContainers := make(map[*container.Container]chan struct{})
  164. activeSandboxes := make(map[string]interface{})
  165. for id, c := range containers {
  166. if err := daemon.registerName(c); err != nil {
  167. logrus.Errorf("Failed to register container 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. }
  447. // setClusterProvider sets a component for querying the current cluster state.
  448. func (daemon *Daemon) setClusterProvider(clusterProvider cluster.Provider) {
  449. daemon.clusterProvider = clusterProvider
  450. daemon.netController.SetClusterProvider(clusterProvider)
  451. }
  452. // IsSwarmCompatible verifies if the current daemon
  453. // configuration is compatible with the swarm mode
  454. func (daemon *Daemon) IsSwarmCompatible() error {
  455. if daemon.configStore == nil {
  456. return nil
  457. }
  458. return daemon.configStore.IsSwarmCompatible()
  459. }
  460. // NewDaemon sets up everything for the daemon to be able to service
  461. // requests from the webserver.
  462. func NewDaemon(config *config.Config, registryService registry.Service, containerdRemote libcontainerd.Remote, pluginStore *plugin.Store) (daemon *Daemon, err error) {
  463. setDefaultMtu(config)
  464. // Ensure that we have a correct root key limit for launching containers.
  465. if err := ModifyRootKeyLimit(); err != nil {
  466. logrus.Warnf("unable to modify root key limit, number of containers could be limited by this quota: %v", err)
  467. }
  468. // Ensure we have compatible and valid configuration options
  469. if err := verifyDaemonSettings(config); err != nil {
  470. return nil, err
  471. }
  472. // Do we have a disabled network?
  473. config.DisableBridge = isBridgeNetworkDisabled(config)
  474. // Verify the platform is supported as a daemon
  475. if !platformSupported {
  476. return nil, errSystemNotSupported
  477. }
  478. // Validate platform-specific requirements
  479. if err := checkSystem(); err != nil {
  480. return nil, err
  481. }
  482. idMappings, err := setupRemappedRoot(config)
  483. if err != nil {
  484. return nil, err
  485. }
  486. rootIDs := idMappings.RootPair()
  487. if err := setupDaemonProcess(config); err != nil {
  488. return nil, err
  489. }
  490. // set up the tmpDir to use a canonical path
  491. tmp, err := prepareTempDir(config.Root, rootIDs)
  492. if err != nil {
  493. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  494. }
  495. realTmp, err := getRealPath(tmp)
  496. if err != nil {
  497. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  498. }
  499. os.Setenv("TMPDIR", realTmp)
  500. d := &Daemon{
  501. configStore: config,
  502. startupDone: make(chan struct{}),
  503. }
  504. // Ensure the daemon is properly shutdown if there is a failure during
  505. // initialization
  506. defer func() {
  507. if err != nil {
  508. if err := d.Shutdown(); err != nil {
  509. logrus.Error(err)
  510. }
  511. }
  512. }()
  513. if err := d.setGenericResources(config); err != nil {
  514. return nil, err
  515. }
  516. // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
  517. // on Windows to dump Go routine stacks
  518. stackDumpDir := config.Root
  519. if execRoot := config.GetExecRoot(); execRoot != "" {
  520. stackDumpDir = execRoot
  521. }
  522. d.setupDumpStackTrap(stackDumpDir)
  523. if err := d.setupSeccompProfile(); err != nil {
  524. return nil, err
  525. }
  526. // Set the default isolation mode (only applicable on Windows)
  527. if err := d.setDefaultIsolation(); err != nil {
  528. return nil, fmt.Errorf("error setting default isolation mode: %v", err)
  529. }
  530. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  531. if err := configureMaxThreads(config); err != nil {
  532. logrus.Warnf("Failed to configure golang's threads limit: %v", err)
  533. }
  534. if err := ensureDefaultAppArmorProfile(); err != nil {
  535. logrus.Errorf(err.Error())
  536. }
  537. daemonRepo := filepath.Join(config.Root, "containers")
  538. if err := idtools.MkdirAllAndChown(daemonRepo, 0700, rootIDs); err != nil && !os.IsExist(err) {
  539. return nil, err
  540. }
  541. if runtime.GOOS == "windows" {
  542. if err := system.MkdirAll(filepath.Join(config.Root, "credentialspecs"), 0, ""); err != nil && !os.IsExist(err) {
  543. return nil, err
  544. }
  545. }
  546. // On Windows we don't support the environment variable, or a user supplied graphdriver
  547. // as Windows has no choice in terms of which graphdrivers to use. It's a case of
  548. // running Windows containers on Windows - windowsfilter, running Linux containers on Windows,
  549. // lcow. Unix platforms however run a single graphdriver for all containers, and it can
  550. // be set through an environment variable, a daemon start parameter, or chosen through
  551. // initialization of the layerstore through driver priority order for example.
  552. d.stores = make(map[string]daemonStore)
  553. if runtime.GOOS == "windows" {
  554. d.stores["windows"] = daemonStore{graphDriver: "windowsfilter"}
  555. if system.LCOWSupported() {
  556. d.stores["linux"] = daemonStore{graphDriver: "lcow"}
  557. }
  558. } else {
  559. driverName := os.Getenv("DOCKER_DRIVER")
  560. if driverName == "" {
  561. driverName = config.GraphDriver
  562. } else {
  563. logrus.Infof("Setting the storage driver from the $DOCKER_DRIVER environment variable (%s)", driverName)
  564. }
  565. d.stores[runtime.GOOS] = daemonStore{graphDriver: driverName} // May still be empty. Layerstore init determines instead.
  566. }
  567. d.RegistryService = registryService
  568. d.PluginStore = pluginStore
  569. logger.RegisterPluginGetter(d.PluginStore)
  570. metricsSockPath, err := d.listenMetricsSock()
  571. if err != nil {
  572. return nil, err
  573. }
  574. registerMetricsPluginCallback(d.PluginStore, metricsSockPath)
  575. // Plugin system initialization should happen before restore. Do not change order.
  576. d.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{
  577. Root: filepath.Join(config.Root, "plugins"),
  578. ExecRoot: getPluginExecRoot(config.Root),
  579. Store: d.PluginStore,
  580. Executor: containerdRemote,
  581. RegistryService: registryService,
  582. LiveRestoreEnabled: config.LiveRestoreEnabled,
  583. LogPluginEvent: d.LogPluginEvent, // todo: make private
  584. AuthzMiddleware: config.AuthzMiddleware,
  585. })
  586. if err != nil {
  587. return nil, errors.Wrap(err, "couldn't create plugin manager")
  588. }
  589. var graphDrivers []string
  590. for platform, ds := range d.stores {
  591. ls, err := layer.NewStoreFromOptions(layer.StoreOptions{
  592. StorePath: config.Root,
  593. MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
  594. GraphDriver: ds.graphDriver,
  595. GraphDriverOptions: config.GraphOptions,
  596. IDMappings: idMappings,
  597. PluginGetter: d.PluginStore,
  598. ExperimentalEnabled: config.Experimental,
  599. Platform: platform,
  600. })
  601. if err != nil {
  602. return nil, err
  603. }
  604. ds.graphDriver = ls.DriverName() // As layerstore may set the driver
  605. ds.layerStore = ls
  606. d.stores[platform] = ds
  607. graphDrivers = append(graphDrivers, ls.DriverName())
  608. }
  609. // Configure and validate the kernels security support
  610. if err := configureKernelSecuritySupport(config, graphDrivers); err != nil {
  611. return nil, err
  612. }
  613. logrus.Debugf("Max Concurrent Downloads: %d", *config.MaxConcurrentDownloads)
  614. lsMap := make(map[string]layer.Store)
  615. for platform, ds := range d.stores {
  616. lsMap[platform] = ds.layerStore
  617. }
  618. d.downloadManager = xfer.NewLayerDownloadManager(lsMap, *config.MaxConcurrentDownloads)
  619. logrus.Debugf("Max Concurrent Uploads: %d", *config.MaxConcurrentUploads)
  620. d.uploadManager = xfer.NewLayerUploadManager(*config.MaxConcurrentUploads)
  621. for platform, ds := range d.stores {
  622. imageRoot := filepath.Join(config.Root, "image", ds.graphDriver)
  623. ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
  624. if err != nil {
  625. return nil, err
  626. }
  627. var is image.Store
  628. is, err = image.NewImageStore(ifs, platform, ds.layerStore)
  629. if err != nil {
  630. return nil, err
  631. }
  632. ds.imageRoot = imageRoot
  633. ds.imageStore = is
  634. d.stores[platform] = ds
  635. }
  636. // Configure the volumes driver
  637. volStore, err := d.configureVolumes(rootIDs)
  638. if err != nil {
  639. return nil, err
  640. }
  641. trustKey, err := loadOrCreateTrustKey(config.TrustKeyPath)
  642. if err != nil {
  643. return nil, err
  644. }
  645. trustDir := filepath.Join(config.Root, "trust")
  646. if err := system.MkdirAll(trustDir, 0700, ""); err != nil {
  647. return nil, err
  648. }
  649. eventsService := events.New()
  650. // We have a single tag/reference store for the daemon globally. However, it's
  651. // stored under the graphdriver. On host platforms which only support a single
  652. // container OS, but multiple selectable graphdrivers, this means depending on which
  653. // graphdriver is chosen, the global reference store is under there. For
  654. // platforms which support multiple container operating systems, this is slightly
  655. // more problematic as where does the global ref store get located? Fortunately,
  656. // for Windows, which is currently the only daemon supporting multiple container
  657. // operating systems, the list of graphdrivers available isn't user configurable.
  658. // For backwards compatibility, we just put it under the windowsfilter
  659. // directory regardless.
  660. refStoreLocation := filepath.Join(d.stores[runtime.GOOS].imageRoot, `repositories.json`)
  661. rs, err := refstore.NewReferenceStore(refStoreLocation)
  662. if err != nil {
  663. return nil, fmt.Errorf("Couldn't create reference store repository: %s", err)
  664. }
  665. d.referenceStore = rs
  666. for platform, ds := range d.stores {
  667. dms, err := dmetadata.NewFSMetadataStore(filepath.Join(ds.imageRoot, "distribution"), platform)
  668. if err != nil {
  669. return nil, err
  670. }
  671. ds.distributionMetadataStore = dms
  672. d.stores[platform] = ds
  673. // No content-addressability migration on Windows as it never supported pre-CA
  674. if runtime.GOOS != "windows" {
  675. migrationStart := time.Now()
  676. if err := v1.Migrate(config.Root, ds.graphDriver, ds.layerStore, ds.imageStore, rs, dms); err != nil {
  677. 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)
  678. }
  679. logrus.Infof("Graph migration to content-addressability took %.2f seconds", time.Since(migrationStart).Seconds())
  680. }
  681. }
  682. // Discovery is only enabled when the daemon is launched with an address to advertise. When
  683. // initialized, the daemon is registered and we can store the discovery backend as it's read-only
  684. if err := d.initDiscovery(config); err != nil {
  685. return nil, err
  686. }
  687. sysInfo := sysinfo.New(false)
  688. // Check if Devices cgroup is mounted, it is hard requirement for container security,
  689. // on Linux.
  690. if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled {
  691. return nil, errors.New("Devices cgroup isn't mounted")
  692. }
  693. d.ID = trustKey.PublicKey().KeyID()
  694. d.repository = daemonRepo
  695. d.containers = container.NewMemoryStore()
  696. if d.containersReplica, err = container.NewViewDB(); err != nil {
  697. return nil, err
  698. }
  699. d.execCommands = exec.NewStore()
  700. d.trustKey = trustKey
  701. d.idIndex = truncindex.NewTruncIndex([]string{})
  702. d.statsCollector = d.newStatsCollector(1 * time.Second)
  703. d.defaultLogConfig = containertypes.LogConfig{
  704. Type: config.LogConfig.Type,
  705. Config: config.LogConfig.Config,
  706. }
  707. d.EventsService = eventsService
  708. d.volumes = volStore
  709. d.root = config.Root
  710. d.idMappings = idMappings
  711. d.seccompEnabled = sysInfo.Seccomp
  712. d.apparmorEnabled = sysInfo.AppArmor
  713. d.linkIndex = newLinkIndex()
  714. d.containerdRemote = containerdRemote
  715. go d.execCommandGC()
  716. d.containerd, err = containerdRemote.Client(d)
  717. if err != nil {
  718. return nil, err
  719. }
  720. if err := d.restore(); err != nil {
  721. return nil, err
  722. }
  723. close(d.startupDone)
  724. // FIXME: this method never returns an error
  725. info, _ := d.SystemInfo()
  726. engineInfo.WithValues(
  727. dockerversion.Version,
  728. dockerversion.GitCommit,
  729. info.Architecture,
  730. info.Driver,
  731. info.KernelVersion,
  732. info.OperatingSystem,
  733. info.OSType,
  734. info.ID,
  735. ).Set(1)
  736. engineCpus.Set(float64(info.NCPU))
  737. engineMemory.Set(float64(info.MemTotal))
  738. gd := ""
  739. for platform, ds := range d.stores {
  740. if len(gd) > 0 {
  741. gd += ", "
  742. }
  743. gd += ds.graphDriver
  744. if len(d.stores) > 1 {
  745. gd = fmt.Sprintf("%s (%s)", gd, platform)
  746. }
  747. }
  748. logrus.WithFields(logrus.Fields{
  749. "version": dockerversion.Version,
  750. "commit": dockerversion.GitCommit,
  751. "graphdriver(s)": gd,
  752. }).Info("Docker daemon")
  753. return d, nil
  754. }
  755. func (daemon *Daemon) waitForStartupDone() {
  756. <-daemon.startupDone
  757. }
  758. func (daemon *Daemon) shutdownContainer(c *container.Container) error {
  759. stopTimeout := c.StopTimeout()
  760. // If container failed to exit in stopTimeout seconds of SIGTERM, then using the force
  761. if err := daemon.containerStop(c, stopTimeout); err != nil {
  762. return fmt.Errorf("Failed to stop container %s with error: %v", c.ID, err)
  763. }
  764. // Wait without timeout for the container to exit.
  765. // Ignore the result.
  766. <-c.Wait(context.Background(), container.WaitConditionNotRunning)
  767. return nil
  768. }
  769. // ShutdownTimeout returns the shutdown timeout based on the max stopTimeout of the containers,
  770. // and is limited by daemon's ShutdownTimeout.
  771. func (daemon *Daemon) ShutdownTimeout() int {
  772. // By default we use daemon's ShutdownTimeout.
  773. shutdownTimeout := daemon.configStore.ShutdownTimeout
  774. graceTimeout := 5
  775. if daemon.containers != nil {
  776. for _, c := range daemon.containers.List() {
  777. if shutdownTimeout >= 0 {
  778. stopTimeout := c.StopTimeout()
  779. if stopTimeout < 0 {
  780. shutdownTimeout = -1
  781. } else {
  782. if stopTimeout+graceTimeout > shutdownTimeout {
  783. shutdownTimeout = stopTimeout + graceTimeout
  784. }
  785. }
  786. }
  787. }
  788. }
  789. return shutdownTimeout
  790. }
  791. // Shutdown stops the daemon.
  792. func (daemon *Daemon) Shutdown() error {
  793. daemon.shutdown = true
  794. // Keep mounts and networking running on daemon shutdown if
  795. // we are to keep containers running and restore them.
  796. if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
  797. // check if there are any running containers, if none we should do some cleanup
  798. if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
  799. // metrics plugins still need some cleanup
  800. daemon.cleanupMetricsPlugins()
  801. return nil
  802. }
  803. }
  804. if daemon.containers != nil {
  805. logrus.Debugf("start clean shutdown of all containers with a %d seconds timeout...", daemon.configStore.ShutdownTimeout)
  806. daemon.containers.ApplyAll(func(c *container.Container) {
  807. if !c.IsRunning() {
  808. return
  809. }
  810. logrus.Debugf("stopping %s", c.ID)
  811. if err := daemon.shutdownContainer(c); err != nil {
  812. logrus.Errorf("Stop container error: %v", err)
  813. return
  814. }
  815. if mountid, err := daemon.stores[c.Platform].layerStore.GetMountID(c.ID); err == nil {
  816. daemon.cleanupMountsByID(mountid)
  817. }
  818. logrus.Debugf("container stopped %s", c.ID)
  819. })
  820. }
  821. if daemon.volumes != nil {
  822. if err := daemon.volumes.Shutdown(); err != nil {
  823. logrus.Errorf("Error shutting down volume store: %v", err)
  824. }
  825. }
  826. for platform, ds := range daemon.stores {
  827. if ds.layerStore != nil {
  828. if err := ds.layerStore.Cleanup(); err != nil {
  829. logrus.Errorf("Error during layer Store.Cleanup(): %v %s", err, platform)
  830. }
  831. }
  832. }
  833. // If we are part of a cluster, clean up cluster's stuff
  834. if daemon.clusterProvider != nil {
  835. logrus.Debugf("start clean shutdown of cluster resources...")
  836. daemon.DaemonLeavesCluster()
  837. }
  838. daemon.cleanupMetricsPlugins()
  839. // Shutdown plugins after containers and layerstore. Don't change the order.
  840. daemon.pluginShutdown()
  841. // trigger libnetwork Stop only if it's initialized
  842. if daemon.netController != nil {
  843. daemon.netController.Stop()
  844. }
  845. if err := daemon.cleanupMounts(); err != nil {
  846. return err
  847. }
  848. return nil
  849. }
  850. // Mount sets container.BaseFS
  851. // (is it not set coming in? why is it unset?)
  852. func (daemon *Daemon) Mount(container *container.Container) error {
  853. dir, err := container.RWLayer.Mount(container.GetMountLabel())
  854. if err != nil {
  855. return err
  856. }
  857. logrus.Debugf("container mounted via layerStore: %v", dir)
  858. if container.BaseFS != nil && container.BaseFS.Path() != dir.Path() {
  859. // The mount path reported by the graph driver should always be trusted on Windows, since the
  860. // volume path for a given mounted layer may change over time. This should only be an error
  861. // on non-Windows operating systems.
  862. if runtime.GOOS != "windows" {
  863. daemon.Unmount(container)
  864. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  865. daemon.GraphDriverName(container.Platform), container.ID, container.BaseFS, dir)
  866. }
  867. }
  868. container.BaseFS = dir // TODO: combine these fields
  869. return nil
  870. }
  871. // Unmount unsets the container base filesystem
  872. func (daemon *Daemon) Unmount(container *container.Container) error {
  873. if err := container.RWLayer.Unmount(); err != nil {
  874. logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
  875. return err
  876. }
  877. return nil
  878. }
  879. // Subnets return the IPv4 and IPv6 subnets of networks that are manager by Docker.
  880. func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {
  881. var v4Subnets []net.IPNet
  882. var v6Subnets []net.IPNet
  883. managedNetworks := daemon.netController.Networks()
  884. for _, managedNetwork := range managedNetworks {
  885. v4infos, v6infos := managedNetwork.Info().IpamInfo()
  886. for _, info := range v4infos {
  887. if info.IPAMData.Pool != nil {
  888. v4Subnets = append(v4Subnets, *info.IPAMData.Pool)
  889. }
  890. }
  891. for _, info := range v6infos {
  892. if info.IPAMData.Pool != nil {
  893. v6Subnets = append(v6Subnets, *info.IPAMData.Pool)
  894. }
  895. }
  896. }
  897. return v4Subnets, v6Subnets
  898. }
  899. // GraphDriverName returns the name of the graph driver used by the layer.Store
  900. func (daemon *Daemon) GraphDriverName(platform string) string {
  901. return daemon.stores[platform].layerStore.DriverName()
  902. }
  903. // prepareTempDir prepares and returns the default directory to use
  904. // for temporary files.
  905. // If it doesn't exist, it is created. If it exists, its content is removed.
  906. func prepareTempDir(rootDir string, rootIDs idtools.IDPair) (string, error) {
  907. var tmpDir string
  908. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  909. tmpDir = filepath.Join(rootDir, "tmp")
  910. newName := tmpDir + "-old"
  911. if err := os.Rename(tmpDir, newName); err == nil {
  912. go func() {
  913. if err := os.RemoveAll(newName); err != nil {
  914. logrus.Warnf("failed to delete old tmp directory: %s", newName)
  915. }
  916. }()
  917. } else {
  918. logrus.Warnf("failed to rename %s for background deletion: %s. Deleting synchronously", tmpDir, err)
  919. if err := os.RemoveAll(tmpDir); err != nil {
  920. logrus.Warnf("failed to delete old tmp directory: %s", tmpDir)
  921. }
  922. }
  923. }
  924. // We don't remove the content of tmpdir if it's not the default,
  925. // it may hold things that do not belong to us.
  926. return tmpDir, idtools.MkdirAllAndChown(tmpDir, 0700, rootIDs)
  927. }
  928. func (daemon *Daemon) setupInitLayer(initPath containerfs.ContainerFS) error {
  929. rootIDs := daemon.idMappings.RootPair()
  930. return initlayer.Setup(initPath, rootIDs)
  931. }
  932. func (daemon *Daemon) setGenericResources(conf *config.Config) error {
  933. genericResources, err := config.ParseGenericResources(conf.NodeGenericResources)
  934. if err != nil {
  935. return err
  936. }
  937. daemon.genericResources = genericResources
  938. return nil
  939. }
  940. func setDefaultMtu(conf *config.Config) {
  941. // do nothing if the config does not have the default 0 value.
  942. if conf.Mtu != 0 {
  943. return
  944. }
  945. conf.Mtu = config.DefaultNetworkMtu
  946. }
  947. func (daemon *Daemon) configureVolumes(rootIDs idtools.IDPair) (*store.VolumeStore, error) {
  948. volumesDriver, err := local.New(daemon.configStore.Root, rootIDs)
  949. if err != nil {
  950. return nil, err
  951. }
  952. volumedrivers.RegisterPluginGetter(daemon.PluginStore)
  953. if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) {
  954. return nil, errors.New("local volume driver could not be registered")
  955. }
  956. return store.New(daemon.configStore.Root)
  957. }
  958. // IsShuttingDown tells whether the daemon is shutting down or not
  959. func (daemon *Daemon) IsShuttingDown() bool {
  960. return daemon.shutdown
  961. }
  962. // initDiscovery initializes the discovery watcher for this daemon.
  963. func (daemon *Daemon) initDiscovery(conf *config.Config) error {
  964. advertise, err := config.ParseClusterAdvertiseSettings(conf.ClusterStore, conf.ClusterAdvertise)
  965. if err != nil {
  966. if err == discovery.ErrDiscoveryDisabled {
  967. return nil
  968. }
  969. return err
  970. }
  971. conf.ClusterAdvertise = advertise
  972. discoveryWatcher, err := discovery.Init(conf.ClusterStore, conf.ClusterAdvertise, conf.ClusterOpts)
  973. if err != nil {
  974. return fmt.Errorf("discovery initialization failed (%v)", err)
  975. }
  976. daemon.discoveryWatcher = discoveryWatcher
  977. return nil
  978. }
  979. func isBridgeNetworkDisabled(conf *config.Config) bool {
  980. return conf.BridgeConfig.Iface == config.DisableNetworkBridge
  981. }
  982. func (daemon *Daemon) networkOptions(dconfig *config.Config, pg plugingetter.PluginGetter, activeSandboxes map[string]interface{}) ([]nwconfig.Option, error) {
  983. options := []nwconfig.Option{}
  984. if dconfig == nil {
  985. return options, nil
  986. }
  987. options = append(options, nwconfig.OptionExperimental(dconfig.Experimental))
  988. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  989. options = append(options, nwconfig.OptionExecRoot(dconfig.GetExecRoot()))
  990. dd := runconfig.DefaultDaemonNetworkMode()
  991. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  992. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  993. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  994. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  995. kv := strings.Split(dconfig.ClusterStore, "://")
  996. if len(kv) != 2 {
  997. return nil, errors.New("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  998. }
  999. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  1000. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  1001. }
  1002. if len(dconfig.ClusterOpts) > 0 {
  1003. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  1004. }
  1005. if daemon.discoveryWatcher != nil {
  1006. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  1007. }
  1008. if dconfig.ClusterAdvertise != "" {
  1009. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  1010. }
  1011. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  1012. options = append(options, driverOptions(dconfig)...)
  1013. if daemon.configStore != nil && daemon.configStore.LiveRestoreEnabled && len(activeSandboxes) != 0 {
  1014. options = append(options, nwconfig.OptionActiveSandboxes(activeSandboxes))
  1015. }
  1016. if pg != nil {
  1017. options = append(options, nwconfig.OptionPluginGetter(pg))
  1018. }
  1019. options = append(options, nwconfig.OptionNetworkControlPlaneMTU(dconfig.NetworkControlPlaneMTU))
  1020. return options, nil
  1021. }
  1022. func copyBlkioEntry(entries []*containerd.BlkioStatsEntry) []types.BlkioStatEntry {
  1023. out := make([]types.BlkioStatEntry, len(entries))
  1024. for i, re := range entries {
  1025. out[i] = types.BlkioStatEntry{
  1026. Major: re.Major,
  1027. Minor: re.Minor,
  1028. Op: re.Op,
  1029. Value: re.Value,
  1030. }
  1031. }
  1032. return out
  1033. }
  1034. // GetCluster returns the cluster
  1035. func (daemon *Daemon) GetCluster() Cluster {
  1036. return daemon.cluster
  1037. }
  1038. // SetCluster sets the cluster
  1039. func (daemon *Daemon) SetCluster(cluster Cluster) {
  1040. daemon.cluster = cluster
  1041. }
  1042. func (daemon *Daemon) pluginShutdown() {
  1043. manager := daemon.pluginManager
  1044. // Check for a valid manager object. In error conditions, daemon init can fail
  1045. // and shutdown called, before plugin manager is initialized.
  1046. if manager != nil {
  1047. manager.Shutdown()
  1048. }
  1049. }
  1050. // PluginManager returns current pluginManager associated with the daemon
  1051. func (daemon *Daemon) PluginManager() *plugin.Manager { // set up before daemon to avoid this method
  1052. return daemon.pluginManager
  1053. }
  1054. // PluginGetter returns current pluginStore associated with the daemon
  1055. func (daemon *Daemon) PluginGetter() *plugin.Store {
  1056. return daemon.PluginStore
  1057. }
  1058. // CreateDaemonRoot creates the root for the daemon
  1059. func CreateDaemonRoot(config *config.Config) error {
  1060. // get the canonical path to the Docker root directory
  1061. var realRoot string
  1062. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  1063. realRoot = config.Root
  1064. } else {
  1065. realRoot, err = getRealPath(config.Root)
  1066. if err != nil {
  1067. return fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  1068. }
  1069. }
  1070. idMappings, err := setupRemappedRoot(config)
  1071. if err != nil {
  1072. return err
  1073. }
  1074. return setupDaemonRoot(config, realRoot, idMappings.RootPair())
  1075. }
  1076. // checkpointAndSave grabs a container lock to safely call container.CheckpointTo
  1077. func (daemon *Daemon) checkpointAndSave(container *container.Container) error {
  1078. container.Lock()
  1079. defer container.Unlock()
  1080. if err := container.CheckpointTo(daemon.containersReplica); err != nil {
  1081. return fmt.Errorf("Error saving container state: %v", err)
  1082. }
  1083. return nil
  1084. }
  1085. // because the CLI sends a -1 when it wants to unset the swappiness value
  1086. // we need to clear it on the server side
  1087. func fixMemorySwappiness(resources *containertypes.Resources) {
  1088. if resources.MemorySwappiness != nil && *resources.MemorySwappiness == -1 {
  1089. resources.MemorySwappiness = nil
  1090. }
  1091. }