daemon.go 51 KB

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