daemon.go 48 KB

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