daemon.go 43 KB

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