daemon.go 48 KB

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