daemon.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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
  7. import (
  8. "context"
  9. "fmt"
  10. "io/ioutil"
  11. "net"
  12. "os"
  13. "path"
  14. "path/filepath"
  15. "runtime"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Sirupsen/logrus"
  20. containerd "github.com/containerd/containerd/api/grpc/types"
  21. "github.com/docker/docker/api"
  22. "github.com/docker/docker/api/types"
  23. containertypes "github.com/docker/docker/api/types/container"
  24. "github.com/docker/docker/container"
  25. "github.com/docker/docker/daemon/config"
  26. "github.com/docker/docker/daemon/discovery"
  27. "github.com/docker/docker/daemon/events"
  28. "github.com/docker/docker/daemon/exec"
  29. "github.com/docker/docker/daemon/logger"
  30. // register graph drivers
  31. _ "github.com/docker/docker/daemon/graphdriver/register"
  32. "github.com/docker/docker/daemon/initlayer"
  33. "github.com/docker/docker/daemon/stats"
  34. dmetadata "github.com/docker/docker/distribution/metadata"
  35. "github.com/docker/docker/distribution/xfer"
  36. "github.com/docker/docker/dockerversion"
  37. "github.com/docker/docker/image"
  38. "github.com/docker/docker/layer"
  39. "github.com/docker/docker/libcontainerd"
  40. "github.com/docker/docker/migrate/v1"
  41. "github.com/docker/docker/pkg/fileutils"
  42. "github.com/docker/docker/pkg/idtools"
  43. "github.com/docker/docker/pkg/plugingetter"
  44. "github.com/docker/docker/pkg/registrar"
  45. "github.com/docker/docker/pkg/signal"
  46. "github.com/docker/docker/pkg/sysinfo"
  47. "github.com/docker/docker/pkg/system"
  48. "github.com/docker/docker/pkg/truncindex"
  49. "github.com/docker/docker/plugin"
  50. refstore "github.com/docker/docker/reference"
  51. "github.com/docker/docker/registry"
  52. "github.com/docker/docker/runconfig"
  53. volumedrivers "github.com/docker/docker/volume/drivers"
  54. "github.com/docker/docker/volume/local"
  55. "github.com/docker/docker/volume/store"
  56. "github.com/docker/libnetwork"
  57. "github.com/docker/libnetwork/cluster"
  58. nwconfig "github.com/docker/libnetwork/config"
  59. "github.com/docker/libtrust"
  60. "github.com/pkg/errors"
  61. )
  62. var (
  63. // DefaultRuntimeBinary is the default runtime to be used by
  64. // containerd if none is specified
  65. DefaultRuntimeBinary = "docker-runc"
  66. errSystemNotSupported = errors.New("The Docker daemon is not supported on this platform.")
  67. )
  68. // Daemon holds information about the Docker daemon.
  69. type Daemon struct {
  70. ID string
  71. repository string
  72. containers container.Store
  73. execCommands *exec.Store
  74. referenceStore refstore.Store
  75. downloadManager *xfer.LayerDownloadManager
  76. uploadManager *xfer.LayerUploadManager
  77. distributionMetadataStore dmetadata.Store
  78. trustKey libtrust.PrivateKey
  79. idIndex *truncindex.TruncIndex
  80. configStore *config.Config
  81. statsCollector *stats.Collector
  82. defaultLogConfig containertypes.LogConfig
  83. RegistryService registry.Service
  84. EventsService *events.Events
  85. netController libnetwork.NetworkController
  86. volumes *store.VolumeStore
  87. discoveryWatcher discovery.Reloader
  88. root string
  89. seccompEnabled bool
  90. apparmorEnabled bool
  91. shutdown bool
  92. uidMaps []idtools.IDMap
  93. gidMaps []idtools.IDMap
  94. layerStore layer.Store
  95. imageStore image.Store
  96. PluginStore *plugin.Store // todo: remove
  97. pluginManager *plugin.Manager
  98. nameIndex *registrar.Registrar
  99. linkIndex *linkIndex
  100. containerd libcontainerd.Client
  101. containerdRemote libcontainerd.Remote
  102. defaultIsolation containertypes.Isolation // Default isolation mode on Windows
  103. clusterProvider cluster.Provider
  104. cluster Cluster
  105. metricsPluginListener net.Listener
  106. machineMemory uint64
  107. seccompProfile []byte
  108. seccompProfilePath string
  109. diskUsageRunning int32
  110. pruneRunning int32
  111. }
  112. // HasExperimental returns whether the experimental features of the daemon are enabled or not
  113. func (daemon *Daemon) HasExperimental() bool {
  114. if daemon.configStore != nil && daemon.configStore.Experimental {
  115. return true
  116. }
  117. return false
  118. }
  119. func (daemon *Daemon) restore() error {
  120. var (
  121. currentDriver = daemon.GraphDriverName()
  122. containers = make(map[string]*container.Container)
  123. )
  124. logrus.Info("Loading containers: start.")
  125. dir, err := ioutil.ReadDir(daemon.repository)
  126. if err != nil {
  127. return err
  128. }
  129. for _, v := range dir {
  130. id := v.Name()
  131. container, err := daemon.load(id)
  132. if err != nil {
  133. logrus.Errorf("Failed to load container %v: %v", id, err)
  134. continue
  135. }
  136. // Ignore the container if it does not support the current driver being used by the graph
  137. if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
  138. rwlayer, err := daemon.layerStore.GetRWLayer(container.ID)
  139. if err != nil {
  140. logrus.Errorf("Failed to load container mount %v: %v", id, err)
  141. continue
  142. }
  143. container.RWLayer = rwlayer
  144. logrus.Debugf("Loaded container %v", container.ID)
  145. containers[container.ID] = container
  146. } else {
  147. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  148. }
  149. }
  150. removeContainers := make(map[string]*container.Container)
  151. restartContainers := make(map[*container.Container]chan struct{})
  152. activeSandboxes := make(map[string]interface{})
  153. for id, c := range containers {
  154. if err := daemon.registerName(c); err != nil {
  155. logrus.Errorf("Failed to register container %s: %s", c.ID, err)
  156. delete(containers, id)
  157. continue
  158. }
  159. daemon.Register(c)
  160. // verify that all volumes valid and have been migrated from the pre-1.7 layout
  161. if err := daemon.verifyVolumesInfo(c); err != nil {
  162. // don't skip the container due to error
  163. logrus.Errorf("Failed to verify volumes for container '%s': %v", c.ID, err)
  164. }
  165. // The LogConfig.Type is empty if the container was created before docker 1.12 with default log driver.
  166. // We should rewrite it to use the daemon defaults.
  167. // Fixes https://github.com/docker/docker/issues/22536
  168. if c.HostConfig.LogConfig.Type == "" {
  169. if err := daemon.mergeAndVerifyLogConfig(&c.HostConfig.LogConfig); err != nil {
  170. logrus.Errorf("Failed to verify log config for container %s: %q", c.ID, err)
  171. continue
  172. }
  173. }
  174. }
  175. var wg sync.WaitGroup
  176. var mapLock sync.Mutex
  177. for _, c := range containers {
  178. wg.Add(1)
  179. go func(c *container.Container) {
  180. defer wg.Done()
  181. daemon.backportMountSpec(c)
  182. if err := c.ToDiskLocking(); err != nil {
  183. logrus.WithError(err).WithField("container", c.ID).Error("error saving backported mountspec to disk")
  184. }
  185. daemon.setStateCounter(c)
  186. if c.IsRunning() || c.IsPaused() {
  187. c.RestartManager().Cancel() // manually start containers because some need to wait for swarm networking
  188. if err := daemon.containerd.Restore(c.ID, c.InitializeStdio); err != nil {
  189. logrus.Errorf("Failed to restore %s with containerd: %s", c.ID, err)
  190. return
  191. }
  192. // we call Mount and then Unmount to get BaseFs of the container
  193. if err := daemon.Mount(c); err != nil {
  194. // The mount is unlikely to fail. However, in case mount fails
  195. // the container should be allowed to restore here. Some functionalities
  196. // (like docker exec -u user) might be missing but container is able to be
  197. // stopped/restarted/removed.
  198. // See #29365 for related information.
  199. // The error is only logged here.
  200. logrus.Warnf("Failed to mount container on getting BaseFs path %v: %v", c.ID, err)
  201. } else {
  202. if err := daemon.Unmount(c); err != nil {
  203. logrus.Warnf("Failed to umount container on getting BaseFs path %v: %v", c.ID, err)
  204. }
  205. }
  206. c.ResetRestartManager(false)
  207. if !c.HostConfig.NetworkMode.IsContainer() && c.IsRunning() {
  208. options, err := daemon.buildSandboxOptions(c)
  209. if err != nil {
  210. logrus.Warnf("Failed build sandbox option to restore container %s: %v", c.ID, err)
  211. }
  212. mapLock.Lock()
  213. activeSandboxes[c.NetworkSettings.SandboxID] = options
  214. mapLock.Unlock()
  215. }
  216. }
  217. // fixme: only if not running
  218. // get list of containers we need to restart
  219. if !c.IsRunning() && !c.IsPaused() {
  220. // Do not autostart containers which
  221. // has endpoints in a swarm scope
  222. // network yet since the cluster is
  223. // not initialized yet. We will start
  224. // it after the cluster is
  225. // initialized.
  226. if daemon.configStore.AutoRestart && c.ShouldRestart() && !c.NetworkSettings.HasSwarmEndpoint {
  227. mapLock.Lock()
  228. restartContainers[c] = make(chan struct{})
  229. mapLock.Unlock()
  230. } else if c.HostConfig != nil && c.HostConfig.AutoRemove {
  231. mapLock.Lock()
  232. removeContainers[c.ID] = c
  233. mapLock.Unlock()
  234. }
  235. }
  236. if c.RemovalInProgress {
  237. // We probably crashed in the middle of a removal, reset
  238. // the flag.
  239. //
  240. // We DO NOT remove the container here as we do not
  241. // know if the user had requested for either the
  242. // associated volumes, network links or both to also
  243. // be removed. So we put the container in the "dead"
  244. // state and leave further processing up to them.
  245. logrus.Debugf("Resetting RemovalInProgress flag from %v", c.ID)
  246. c.ResetRemovalInProgress()
  247. c.SetDead()
  248. c.ToDisk()
  249. }
  250. }(c)
  251. }
  252. wg.Wait()
  253. daemon.netController, err = daemon.initNetworkController(daemon.configStore, activeSandboxes)
  254. if err != nil {
  255. return fmt.Errorf("Error initializing network controller: %v", err)
  256. }
  257. // Now that all the containers are registered, register the links
  258. for _, c := range containers {
  259. if err := daemon.registerLinks(c, c.HostConfig); err != nil {
  260. logrus.Errorf("failed to register link for container %s: %v", c.ID, err)
  261. }
  262. }
  263. group := sync.WaitGroup{}
  264. for c, notifier := range restartContainers {
  265. group.Add(1)
  266. go func(c *container.Container, chNotify chan struct{}) {
  267. defer group.Done()
  268. logrus.Debugf("Starting container %s", c.ID)
  269. // ignore errors here as this is a best effort to wait for children to be
  270. // running before we try to start the container
  271. children := daemon.children(c)
  272. timeout := time.After(5 * time.Second)
  273. for _, child := range children {
  274. if notifier, exists := restartContainers[child]; exists {
  275. select {
  276. case <-notifier:
  277. case <-timeout:
  278. }
  279. }
  280. }
  281. // Make sure networks are available before starting
  282. daemon.waitForNetworks(c)
  283. if err := daemon.containerStart(c, "", "", true); err != nil {
  284. logrus.Errorf("Failed to start container %s: %s", c.ID, err)
  285. }
  286. close(chNotify)
  287. }(c, notifier)
  288. }
  289. group.Wait()
  290. removeGroup := sync.WaitGroup{}
  291. for id := range removeContainers {
  292. removeGroup.Add(1)
  293. go func(cid string) {
  294. if err := daemon.ContainerRm(cid, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
  295. logrus.Errorf("Failed to remove container %s: %s", cid, err)
  296. }
  297. removeGroup.Done()
  298. }(id)
  299. }
  300. removeGroup.Wait()
  301. // any containers that were started above would already have had this done,
  302. // however we need to now prepare the mountpoints for the rest of the containers as well.
  303. // This shouldn't cause any issue running on the containers that already had this run.
  304. // This must be run after any containers with a restart policy so that containerized plugins
  305. // can have a chance to be running before we try to initialize them.
  306. for _, c := range containers {
  307. // if the container has restart policy, do not
  308. // prepare the mountpoints since it has been done on restarting.
  309. // This is to speed up the daemon start when a restart container
  310. // has a volume and the volume driver is not available.
  311. if _, ok := restartContainers[c]; ok {
  312. continue
  313. } else if _, ok := removeContainers[c.ID]; ok {
  314. // container is automatically removed, skip it.
  315. continue
  316. }
  317. group.Add(1)
  318. go func(c *container.Container) {
  319. defer group.Done()
  320. if err := daemon.prepareMountPoints(c); err != nil {
  321. logrus.Error(err)
  322. }
  323. }(c)
  324. }
  325. group.Wait()
  326. logrus.Info("Loading containers: done.")
  327. return nil
  328. }
  329. // RestartSwarmContainers restarts any autostart container which has a
  330. // swarm endpoint.
  331. func (daemon *Daemon) RestartSwarmContainers() {
  332. group := sync.WaitGroup{}
  333. for _, c := range daemon.List() {
  334. if !c.IsRunning() && !c.IsPaused() {
  335. // Autostart all the containers which has a
  336. // swarm endpoint now that the cluster is
  337. // initialized.
  338. if daemon.configStore.AutoRestart && c.ShouldRestart() && c.NetworkSettings.HasSwarmEndpoint {
  339. group.Add(1)
  340. go func(c *container.Container) {
  341. defer group.Done()
  342. if err := daemon.containerStart(c, "", "", true); err != nil {
  343. logrus.Error(err)
  344. }
  345. }(c)
  346. }
  347. }
  348. }
  349. group.Wait()
  350. }
  351. // waitForNetworks is used during daemon initialization when starting up containers
  352. // It ensures that all of a container's networks are available before the daemon tries to start the container.
  353. // In practice it just makes sure the discovery service is available for containers which use a network that require discovery.
  354. func (daemon *Daemon) waitForNetworks(c *container.Container) {
  355. if daemon.discoveryWatcher == nil {
  356. return
  357. }
  358. // Make sure if the container has a network that requires discovery that the discovery service is available before starting
  359. for netName := range c.NetworkSettings.Networks {
  360. // If we get `ErrNoSuchNetwork` here, we can assume that it is due to discovery not being ready
  361. // Most likely this is because the K/V store used for discovery is in a container and needs to be started
  362. if _, err := daemon.netController.NetworkByName(netName); err != nil {
  363. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  364. continue
  365. }
  366. // use a longish timeout here due to some slowdowns in libnetwork if the k/v store is on anything other than --net=host
  367. // FIXME: why is this slow???
  368. logrus.Debugf("Container %s waiting for network to be ready", c.Name)
  369. select {
  370. case <-daemon.discoveryWatcher.ReadyCh():
  371. case <-time.After(60 * time.Second):
  372. }
  373. return
  374. }
  375. }
  376. }
  377. func (daemon *Daemon) children(c *container.Container) map[string]*container.Container {
  378. return daemon.linkIndex.children(c)
  379. }
  380. // parents returns the names of the parent containers of the container
  381. // with the given name.
  382. func (daemon *Daemon) parents(c *container.Container) map[string]*container.Container {
  383. return daemon.linkIndex.parents(c)
  384. }
  385. func (daemon *Daemon) registerLink(parent, child *container.Container, alias string) error {
  386. fullName := path.Join(parent.Name, alias)
  387. if err := daemon.nameIndex.Reserve(fullName, child.ID); err != nil {
  388. if err == registrar.ErrNameReserved {
  389. logrus.Warnf("error registering link for %s, to %s, as alias %s, ignoring: %v", parent.ID, child.ID, alias, err)
  390. return nil
  391. }
  392. return err
  393. }
  394. daemon.linkIndex.link(parent, child, fullName)
  395. return nil
  396. }
  397. // DaemonJoinsCluster informs the daemon has joined the cluster and provides
  398. // the handler to query the cluster component
  399. func (daemon *Daemon) DaemonJoinsCluster(clusterProvider cluster.Provider) {
  400. daemon.setClusterProvider(clusterProvider)
  401. }
  402. // DaemonLeavesCluster informs the daemon has left the cluster
  403. func (daemon *Daemon) DaemonLeavesCluster() {
  404. // Daemon is in charge of removing the attachable networks with
  405. // connected containers when the node leaves the swarm
  406. daemon.clearAttachableNetworks()
  407. // We no longer need the cluster provider, stop it now so that
  408. // the network agent will stop listening to cluster events.
  409. daemon.setClusterProvider(nil)
  410. // Wait for the networking cluster agent to stop
  411. daemon.netController.AgentStopWait()
  412. // Daemon is in charge of removing the ingress network when the
  413. // node leaves the swarm. Wait for job to be done or timeout.
  414. // This is called also on graceful daemon shutdown. We need to
  415. // wait, because the ingress release has to happen before the
  416. // network controller is stopped.
  417. if done, err := daemon.ReleaseIngress(); err == nil {
  418. select {
  419. case <-done:
  420. case <-time.After(5 * time.Second):
  421. logrus.Warnf("timeout while waiting for ingress network removal")
  422. }
  423. } else {
  424. logrus.Warnf("failed to initiate ingress network removal: %v", err)
  425. }
  426. }
  427. // setClusterProvider sets a component for querying the current cluster state.
  428. func (daemon *Daemon) setClusterProvider(clusterProvider cluster.Provider) {
  429. daemon.clusterProvider = clusterProvider
  430. daemon.netController.SetClusterProvider(clusterProvider)
  431. }
  432. // IsSwarmCompatible verifies if the current daemon
  433. // configuration is compatible with the swarm mode
  434. func (daemon *Daemon) IsSwarmCompatible() error {
  435. if daemon.configStore == nil {
  436. return nil
  437. }
  438. return daemon.configStore.IsSwarmCompatible()
  439. }
  440. // NewDaemon sets up everything for the daemon to be able to service
  441. // requests from the webserver.
  442. func NewDaemon(config *config.Config, registryService registry.Service, containerdRemote libcontainerd.Remote, pluginStore *plugin.Store) (daemon *Daemon, err error) {
  443. setDefaultMtu(config)
  444. // Ensure that we have a correct root key limit for launching containers.
  445. if err := ModifyRootKeyLimit(); err != nil {
  446. logrus.Warnf("unable to modify root key limit, number of containers could be limited by this quota: %v", err)
  447. }
  448. // Ensure we have compatible and valid configuration options
  449. if err := verifyDaemonSettings(config); err != nil {
  450. return nil, err
  451. }
  452. // Do we have a disabled network?
  453. config.DisableBridge = isBridgeNetworkDisabled(config)
  454. // Verify the platform is supported as a daemon
  455. if !platformSupported {
  456. return nil, errSystemNotSupported
  457. }
  458. // Validate platform-specific requirements
  459. if err := checkSystem(); err != nil {
  460. return nil, err
  461. }
  462. uidMaps, gidMaps, err := setupRemappedRoot(config)
  463. if err != nil {
  464. return nil, err
  465. }
  466. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  467. if err != nil {
  468. return nil, err
  469. }
  470. if err := setupDaemonProcess(config); err != nil {
  471. return nil, err
  472. }
  473. // set up the tmpDir to use a canonical path
  474. tmp, err := prepareTempDir(config.Root, rootUID, rootGID)
  475. if err != nil {
  476. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  477. }
  478. realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
  479. if err != nil {
  480. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  481. }
  482. os.Setenv("TMPDIR", realTmp)
  483. d := &Daemon{configStore: config}
  484. // Ensure the daemon is properly shutdown if there is a failure during
  485. // initialization
  486. defer func() {
  487. if err != nil {
  488. if err := d.Shutdown(); err != nil {
  489. logrus.Error(err)
  490. }
  491. }
  492. }()
  493. // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
  494. // on Windows to dump Go routine stacks
  495. stackDumpDir := config.Root
  496. if execRoot := config.GetExecRoot(); execRoot != "" {
  497. stackDumpDir = execRoot
  498. }
  499. d.setupDumpStackTrap(stackDumpDir)
  500. if err := d.setupSeccompProfile(); err != nil {
  501. return nil, err
  502. }
  503. // Set the default isolation mode (only applicable on Windows)
  504. if err := d.setDefaultIsolation(); err != nil {
  505. return nil, fmt.Errorf("error setting default isolation mode: %v", err)
  506. }
  507. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  508. if err := configureMaxThreads(config); err != nil {
  509. logrus.Warnf("Failed to configure golang's threads limit: %v", err)
  510. }
  511. if err := ensureDefaultAppArmorProfile(); err != nil {
  512. logrus.Errorf(err.Error())
  513. }
  514. daemonRepo := filepath.Join(config.Root, "containers")
  515. if err := idtools.MkdirAllAs(daemonRepo, 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  516. return nil, err
  517. }
  518. if runtime.GOOS == "windows" {
  519. if err := system.MkdirAll(filepath.Join(config.Root, "credentialspecs"), 0); err != nil && !os.IsExist(err) {
  520. return nil, err
  521. }
  522. }
  523. driverName := os.Getenv("DOCKER_DRIVER")
  524. if driverName == "" {
  525. driverName = config.GraphDriver
  526. }
  527. d.RegistryService = registryService
  528. d.PluginStore = pluginStore
  529. logger.RegisterPluginGetter(d.PluginStore)
  530. metricsSockPath, err := d.listenMetricsSock()
  531. if err != nil {
  532. return nil, err
  533. }
  534. registerMetricsPluginCallback(d.PluginStore, metricsSockPath)
  535. // Plugin system initialization should happen before restore. Do not change order.
  536. d.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{
  537. Root: filepath.Join(config.Root, "plugins"),
  538. ExecRoot: getPluginExecRoot(config.Root),
  539. Store: d.PluginStore,
  540. Executor: containerdRemote,
  541. RegistryService: registryService,
  542. LiveRestoreEnabled: config.LiveRestoreEnabled,
  543. LogPluginEvent: d.LogPluginEvent, // todo: make private
  544. AuthzMiddleware: config.AuthzMiddleware,
  545. })
  546. if err != nil {
  547. return nil, errors.Wrap(err, "couldn't create plugin manager")
  548. }
  549. d.layerStore, err = layer.NewStoreFromOptions(layer.StoreOptions{
  550. StorePath: config.Root,
  551. MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
  552. GraphDriver: driverName,
  553. GraphDriverOptions: config.GraphOptions,
  554. UIDMaps: uidMaps,
  555. GIDMaps: gidMaps,
  556. PluginGetter: d.PluginStore,
  557. ExperimentalEnabled: config.Experimental,
  558. })
  559. if err != nil {
  560. return nil, err
  561. }
  562. graphDriver := d.layerStore.DriverName()
  563. imageRoot := filepath.Join(config.Root, "image", graphDriver)
  564. // Configure and validate the kernels security support
  565. if err := configureKernelSecuritySupport(config, graphDriver); err != nil {
  566. return nil, err
  567. }
  568. logrus.Debugf("Max Concurrent Downloads: %d", *config.MaxConcurrentDownloads)
  569. d.downloadManager = xfer.NewLayerDownloadManager(d.layerStore, *config.MaxConcurrentDownloads)
  570. logrus.Debugf("Max Concurrent Uploads: %d", *config.MaxConcurrentUploads)
  571. d.uploadManager = xfer.NewLayerUploadManager(*config.MaxConcurrentUploads)
  572. ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
  573. if err != nil {
  574. return nil, err
  575. }
  576. d.imageStore, err = image.NewImageStore(ifs, d.layerStore)
  577. if err != nil {
  578. return nil, err
  579. }
  580. // Configure the volumes driver
  581. volStore, err := d.configureVolumes(rootUID, rootGID)
  582. if err != nil {
  583. return nil, err
  584. }
  585. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  586. if err != nil {
  587. return nil, err
  588. }
  589. trustDir := filepath.Join(config.Root, "trust")
  590. if err := system.MkdirAll(trustDir, 0700); err != nil {
  591. return nil, err
  592. }
  593. distributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, "distribution"))
  594. if err != nil {
  595. return nil, err
  596. }
  597. eventsService := events.New()
  598. referenceStore, err := refstore.NewReferenceStore(filepath.Join(imageRoot, "repositories.json"))
  599. if err != nil {
  600. return nil, fmt.Errorf("Couldn't create Tag store repositories: %s", err)
  601. }
  602. migrationStart := time.Now()
  603. if err := v1.Migrate(config.Root, graphDriver, d.layerStore, d.imageStore, referenceStore, distributionMetadataStore); err != nil {
  604. logrus.Errorf("Graph migration failed: %q. Your old graph data was found to be too inconsistent for upgrading to content-addressable storage. Some of the old data was probably not upgraded. We recommend starting over with a clean storage directory if possible.", err)
  605. }
  606. logrus.Infof("Graph migration to content-addressability took %.2f seconds", time.Since(migrationStart).Seconds())
  607. // Discovery is only enabled when the daemon is launched with an address to advertise. When
  608. // initialized, the daemon is registered and we can store the discovery backend as it's read-only
  609. if err := d.initDiscovery(config); err != nil {
  610. return nil, err
  611. }
  612. sysInfo := sysinfo.New(false)
  613. // Check if Devices cgroup is mounted, it is hard requirement for container security,
  614. // on Linux.
  615. if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled {
  616. return nil, errors.New("Devices cgroup isn't mounted")
  617. }
  618. d.ID = trustKey.PublicKey().KeyID()
  619. d.repository = daemonRepo
  620. d.containers = container.NewMemoryStore()
  621. d.execCommands = exec.NewStore()
  622. d.referenceStore = referenceStore
  623. d.distributionMetadataStore = distributionMetadataStore
  624. d.trustKey = trustKey
  625. d.idIndex = truncindex.NewTruncIndex([]string{})
  626. d.statsCollector = d.newStatsCollector(1 * time.Second)
  627. d.defaultLogConfig = containertypes.LogConfig{
  628. Type: config.LogConfig.Type,
  629. Config: config.LogConfig.Config,
  630. }
  631. d.EventsService = eventsService
  632. d.volumes = volStore
  633. d.root = config.Root
  634. d.uidMaps = uidMaps
  635. d.gidMaps = gidMaps
  636. d.seccompEnabled = sysInfo.Seccomp
  637. d.apparmorEnabled = sysInfo.AppArmor
  638. d.nameIndex = registrar.NewRegistrar()
  639. d.linkIndex = newLinkIndex()
  640. d.containerdRemote = containerdRemote
  641. go d.execCommandGC()
  642. d.containerd, err = containerdRemote.Client(d)
  643. if err != nil {
  644. return nil, err
  645. }
  646. if err := d.restore(); err != nil {
  647. return nil, err
  648. }
  649. // FIXME: this method never returns an error
  650. info, _ := d.SystemInfo()
  651. engineInfo.WithValues(
  652. dockerversion.Version,
  653. dockerversion.GitCommit,
  654. info.Architecture,
  655. info.Driver,
  656. info.KernelVersion,
  657. info.OperatingSystem,
  658. info.OSType,
  659. info.ID,
  660. ).Set(1)
  661. engineCpus.Set(float64(info.NCPU))
  662. engineMemory.Set(float64(info.MemTotal))
  663. return d, nil
  664. }
  665. func (daemon *Daemon) shutdownContainer(c *container.Container) error {
  666. stopTimeout := c.StopTimeout()
  667. // TODO(windows): Handle docker restart with paused containers
  668. if c.IsPaused() {
  669. // To terminate a process in freezer cgroup, we should send
  670. // SIGTERM to this process then unfreeze it, and the process will
  671. // force to terminate immediately.
  672. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpausing it", c.ID)
  673. sig, ok := signal.SignalMap["TERM"]
  674. if !ok {
  675. return errors.New("System does not support SIGTERM")
  676. }
  677. if err := daemon.kill(c, int(sig)); err != nil {
  678. return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err)
  679. }
  680. if err := daemon.containerUnpause(c); err != nil {
  681. return fmt.Errorf("Failed to unpause container %s with error: %v", c.ID, err)
  682. }
  683. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(stopTimeout)*time.Second)
  684. defer cancel()
  685. // Wait with timeout for container to exit.
  686. if status := <-c.Wait(ctx, container.WaitConditionNotRunning); status.Err() != nil {
  687. logrus.Debugf("container %s failed to exit in %d second of SIGTERM, sending SIGKILL to force", c.ID, stopTimeout)
  688. sig, ok := signal.SignalMap["KILL"]
  689. if !ok {
  690. return errors.New("System does not support SIGKILL")
  691. }
  692. if err := daemon.kill(c, int(sig)); err != nil {
  693. logrus.Errorf("Failed to SIGKILL container %s", c.ID)
  694. }
  695. // Wait for exit again without a timeout.
  696. // Explicitly ignore the result.
  697. _ = <-c.Wait(context.Background(), container.WaitConditionNotRunning)
  698. return status.Err()
  699. }
  700. }
  701. // If container failed to exit in stopTimeout seconds of SIGTERM, then using the force
  702. if err := daemon.containerStop(c, stopTimeout); err != nil {
  703. return fmt.Errorf("Failed to stop container %s with error: %v", c.ID, err)
  704. }
  705. // Wait without timeout for the container to exit.
  706. // Ignore the result.
  707. _ = <-c.Wait(context.Background(), container.WaitConditionNotRunning)
  708. return nil
  709. }
  710. // ShutdownTimeout returns the shutdown timeout based on the max stopTimeout of the containers,
  711. // and is limited by daemon's ShutdownTimeout.
  712. func (daemon *Daemon) ShutdownTimeout() int {
  713. // By default we use daemon's ShutdownTimeout.
  714. shutdownTimeout := daemon.configStore.ShutdownTimeout
  715. graceTimeout := 5
  716. if daemon.containers != nil {
  717. for _, c := range daemon.containers.List() {
  718. if shutdownTimeout >= 0 {
  719. stopTimeout := c.StopTimeout()
  720. if stopTimeout < 0 {
  721. shutdownTimeout = -1
  722. } else {
  723. if stopTimeout+graceTimeout > shutdownTimeout {
  724. shutdownTimeout = stopTimeout + graceTimeout
  725. }
  726. }
  727. }
  728. }
  729. }
  730. return shutdownTimeout
  731. }
  732. // Shutdown stops the daemon.
  733. func (daemon *Daemon) Shutdown() error {
  734. daemon.shutdown = true
  735. // Keep mounts and networking running on daemon shutdown if
  736. // we are to keep containers running and restore them.
  737. if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
  738. // check if there are any running containers, if none we should do some cleanup
  739. if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
  740. // metrics plugins still need some cleanup
  741. daemon.cleanupMetricsPlugins()
  742. return nil
  743. }
  744. }
  745. if daemon.containers != nil {
  746. logrus.Debugf("start clean shutdown of all containers with a %d seconds timeout...", daemon.configStore.ShutdownTimeout)
  747. daemon.containers.ApplyAll(func(c *container.Container) {
  748. if !c.IsRunning() {
  749. return
  750. }
  751. logrus.Debugf("stopping %s", c.ID)
  752. if err := daemon.shutdownContainer(c); err != nil {
  753. logrus.Errorf("Stop container error: %v", err)
  754. return
  755. }
  756. if mountid, err := daemon.layerStore.GetMountID(c.ID); err == nil {
  757. daemon.cleanupMountsByID(mountid)
  758. }
  759. logrus.Debugf("container stopped %s", c.ID)
  760. })
  761. }
  762. if daemon.volumes != nil {
  763. if err := daemon.volumes.Shutdown(); err != nil {
  764. logrus.Errorf("Error shutting down volume store: %v", err)
  765. }
  766. }
  767. if daemon.layerStore != nil {
  768. if err := daemon.layerStore.Cleanup(); err != nil {
  769. logrus.Errorf("Error during layer Store.Cleanup(): %v", err)
  770. }
  771. }
  772. // If we are part of a cluster, clean up cluster's stuff
  773. if daemon.clusterProvider != nil {
  774. logrus.Debugf("start clean shutdown of cluster resources...")
  775. daemon.DaemonLeavesCluster()
  776. }
  777. daemon.cleanupMetricsPlugins()
  778. // Shutdown plugins after containers and layerstore. Don't change the order.
  779. daemon.pluginShutdown()
  780. // trigger libnetwork Stop only if it's initialized
  781. if daemon.netController != nil {
  782. daemon.netController.Stop()
  783. }
  784. if err := daemon.cleanupMounts(); err != nil {
  785. return err
  786. }
  787. return nil
  788. }
  789. // Mount sets container.BaseFS
  790. // (is it not set coming in? why is it unset?)
  791. func (daemon *Daemon) Mount(container *container.Container) error {
  792. dir, err := container.RWLayer.Mount(container.GetMountLabel())
  793. if err != nil {
  794. return err
  795. }
  796. logrus.Debugf("container mounted via layerStore: %v", dir)
  797. if container.BaseFS != dir {
  798. // The mount path reported by the graph driver should always be trusted on Windows, since the
  799. // volume path for a given mounted layer may change over time. This should only be an error
  800. // on non-Windows operating systems.
  801. if container.BaseFS != "" && runtime.GOOS != "windows" {
  802. daemon.Unmount(container)
  803. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  804. daemon.GraphDriverName(), container.ID, container.BaseFS, dir)
  805. }
  806. }
  807. container.BaseFS = dir // TODO: combine these fields
  808. return nil
  809. }
  810. // Unmount unsets the container base filesystem
  811. func (daemon *Daemon) Unmount(container *container.Container) error {
  812. if err := container.RWLayer.Unmount(); err != nil {
  813. logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
  814. return err
  815. }
  816. return nil
  817. }
  818. // Subnets return the IPv4 and IPv6 subnets of networks that are manager by Docker.
  819. func (daemon *Daemon) Subnets() ([]net.IPNet, []net.IPNet) {
  820. var v4Subnets []net.IPNet
  821. var v6Subnets []net.IPNet
  822. managedNetworks := daemon.netController.Networks()
  823. for _, managedNetwork := range managedNetworks {
  824. v4infos, v6infos := managedNetwork.Info().IpamInfo()
  825. for _, info := range v4infos {
  826. if info.IPAMData.Pool != nil {
  827. v4Subnets = append(v4Subnets, *info.IPAMData.Pool)
  828. }
  829. }
  830. for _, info := range v6infos {
  831. if info.IPAMData.Pool != nil {
  832. v6Subnets = append(v6Subnets, *info.IPAMData.Pool)
  833. }
  834. }
  835. }
  836. return v4Subnets, v6Subnets
  837. }
  838. // GraphDriverName returns the name of the graph driver used by the layer.Store
  839. func (daemon *Daemon) GraphDriverName() string {
  840. return daemon.layerStore.DriverName()
  841. }
  842. // GetUIDGIDMaps returns the current daemon's user namespace settings
  843. // for the full uid and gid maps which will be applied to containers
  844. // started in this instance.
  845. func (daemon *Daemon) GetUIDGIDMaps() ([]idtools.IDMap, []idtools.IDMap) {
  846. return daemon.uidMaps, daemon.gidMaps
  847. }
  848. // GetRemappedUIDGID returns the current daemon's uid and gid values
  849. // if user namespaces are in use for this daemon instance. If not
  850. // this function will return "real" root values of 0, 0.
  851. func (daemon *Daemon) GetRemappedUIDGID() (int, int) {
  852. uid, gid, _ := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps)
  853. return uid, gid
  854. }
  855. // prepareTempDir prepares and returns the default directory to use
  856. // for temporary files.
  857. // If it doesn't exist, it is created. If it exists, its content is removed.
  858. func prepareTempDir(rootDir string, rootUID, rootGID int) (string, error) {
  859. var tmpDir string
  860. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  861. tmpDir = filepath.Join(rootDir, "tmp")
  862. newName := tmpDir + "-old"
  863. if err := os.Rename(tmpDir, newName); err == nil {
  864. go func() {
  865. if err := os.RemoveAll(newName); err != nil {
  866. logrus.Warnf("failed to delete old tmp directory: %s", newName)
  867. }
  868. }()
  869. } else {
  870. logrus.Warnf("failed to rename %s for background deletion: %s. Deleting synchronously", tmpDir, err)
  871. if err := os.RemoveAll(tmpDir); err != nil {
  872. logrus.Warnf("failed to delete old tmp directory: %s", tmpDir)
  873. }
  874. }
  875. }
  876. // We don't remove the content of tmpdir if it's not the default,
  877. // it may hold things that do not belong to us.
  878. return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID)
  879. }
  880. func (daemon *Daemon) setupInitLayer(initPath string) error {
  881. rootUID, rootGID := daemon.GetRemappedUIDGID()
  882. return initlayer.Setup(initPath, rootUID, rootGID)
  883. }
  884. func setDefaultMtu(conf *config.Config) {
  885. // do nothing if the config does not have the default 0 value.
  886. if conf.Mtu != 0 {
  887. return
  888. }
  889. conf.Mtu = config.DefaultNetworkMtu
  890. }
  891. func (daemon *Daemon) configureVolumes(rootUID, rootGID int) (*store.VolumeStore, error) {
  892. volumesDriver, err := local.New(daemon.configStore.Root, rootUID, rootGID)
  893. if err != nil {
  894. return nil, err
  895. }
  896. volumedrivers.RegisterPluginGetter(daemon.PluginStore)
  897. if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) {
  898. return nil, errors.New("local volume driver could not be registered")
  899. }
  900. return store.New(daemon.configStore.Root)
  901. }
  902. // IsShuttingDown tells whether the daemon is shutting down or not
  903. func (daemon *Daemon) IsShuttingDown() bool {
  904. return daemon.shutdown
  905. }
  906. // initDiscovery initializes the discovery watcher for this daemon.
  907. func (daemon *Daemon) initDiscovery(conf *config.Config) error {
  908. advertise, err := config.ParseClusterAdvertiseSettings(conf.ClusterStore, conf.ClusterAdvertise)
  909. if err != nil {
  910. if err == discovery.ErrDiscoveryDisabled {
  911. return nil
  912. }
  913. return err
  914. }
  915. conf.ClusterAdvertise = advertise
  916. discoveryWatcher, err := discovery.Init(conf.ClusterStore, conf.ClusterAdvertise, conf.ClusterOpts)
  917. if err != nil {
  918. return fmt.Errorf("discovery initialization failed (%v)", err)
  919. }
  920. daemon.discoveryWatcher = discoveryWatcher
  921. return nil
  922. }
  923. func isBridgeNetworkDisabled(conf *config.Config) bool {
  924. return conf.BridgeConfig.Iface == config.DisableNetworkBridge
  925. }
  926. func (daemon *Daemon) networkOptions(dconfig *config.Config, pg plugingetter.PluginGetter, activeSandboxes map[string]interface{}) ([]nwconfig.Option, error) {
  927. options := []nwconfig.Option{}
  928. if dconfig == nil {
  929. return options, nil
  930. }
  931. options = append(options, nwconfig.OptionExperimental(dconfig.Experimental))
  932. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  933. options = append(options, nwconfig.OptionExecRoot(dconfig.GetExecRoot()))
  934. dd := runconfig.DefaultDaemonNetworkMode()
  935. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  936. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  937. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  938. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  939. kv := strings.Split(dconfig.ClusterStore, "://")
  940. if len(kv) != 2 {
  941. return nil, errors.New("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  942. }
  943. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  944. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  945. }
  946. if len(dconfig.ClusterOpts) > 0 {
  947. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  948. }
  949. if daemon.discoveryWatcher != nil {
  950. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  951. }
  952. if dconfig.ClusterAdvertise != "" {
  953. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  954. }
  955. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  956. options = append(options, driverOptions(dconfig)...)
  957. if daemon.configStore != nil && daemon.configStore.LiveRestoreEnabled && len(activeSandboxes) != 0 {
  958. options = append(options, nwconfig.OptionActiveSandboxes(activeSandboxes))
  959. }
  960. if pg != nil {
  961. options = append(options, nwconfig.OptionPluginGetter(pg))
  962. }
  963. return options, nil
  964. }
  965. func copyBlkioEntry(entries []*containerd.BlkioStatsEntry) []types.BlkioStatEntry {
  966. out := make([]types.BlkioStatEntry, len(entries))
  967. for i, re := range entries {
  968. out[i] = types.BlkioStatEntry{
  969. Major: re.Major,
  970. Minor: re.Minor,
  971. Op: re.Op,
  972. Value: re.Value,
  973. }
  974. }
  975. return out
  976. }
  977. // GetCluster returns the cluster
  978. func (daemon *Daemon) GetCluster() Cluster {
  979. return daemon.cluster
  980. }
  981. // SetCluster sets the cluster
  982. func (daemon *Daemon) SetCluster(cluster Cluster) {
  983. daemon.cluster = cluster
  984. }
  985. func (daemon *Daemon) pluginShutdown() {
  986. manager := daemon.pluginManager
  987. // Check for a valid manager object. In error conditions, daemon init can fail
  988. // and shutdown called, before plugin manager is initialized.
  989. if manager != nil {
  990. manager.Shutdown()
  991. }
  992. }
  993. // PluginManager returns current pluginManager associated with the daemon
  994. func (daemon *Daemon) PluginManager() *plugin.Manager { // set up before daemon to avoid this method
  995. return daemon.pluginManager
  996. }
  997. // PluginGetter returns current pluginStore associated with the daemon
  998. func (daemon *Daemon) PluginGetter() *plugin.Store {
  999. return daemon.PluginStore
  1000. }
  1001. // CreateDaemonRoot creates the root for the daemon
  1002. func CreateDaemonRoot(config *config.Config) error {
  1003. // get the canonical path to the Docker root directory
  1004. var realRoot string
  1005. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  1006. realRoot = config.Root
  1007. } else {
  1008. realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
  1009. if err != nil {
  1010. return fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  1011. }
  1012. }
  1013. uidMaps, gidMaps, err := setupRemappedRoot(config)
  1014. if err != nil {
  1015. return err
  1016. }
  1017. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  1018. if err != nil {
  1019. return err
  1020. }
  1021. if err := setupDaemonRoot(config, realRoot, rootUID, rootGID); err != nil {
  1022. return err
  1023. }
  1024. return nil
  1025. }