daemon.go 52 KB

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