daemon.go 51 KB

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