daemon.go 50 KB

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