daemon.go 48 KB

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