daemon.go 51 KB

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