daemon.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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. "encoding/json"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "os"
  14. "path"
  15. "path/filepath"
  16. "runtime"
  17. "strings"
  18. "sync"
  19. "syscall"
  20. "time"
  21. "github.com/Sirupsen/logrus"
  22. containerd "github.com/docker/containerd/api/grpc/types"
  23. "github.com/docker/docker/api"
  24. "github.com/docker/docker/container"
  25. "github.com/docker/docker/daemon/events"
  26. "github.com/docker/docker/daemon/exec"
  27. "github.com/docker/engine-api/types"
  28. containertypes "github.com/docker/engine-api/types/container"
  29. "github.com/docker/libnetwork/cluster"
  30. // register graph drivers
  31. _ "github.com/docker/docker/daemon/graphdriver/register"
  32. dmetadata "github.com/docker/docker/distribution/metadata"
  33. "github.com/docker/docker/distribution/xfer"
  34. "github.com/docker/docker/image"
  35. "github.com/docker/docker/layer"
  36. "github.com/docker/docker/libcontainerd"
  37. "github.com/docker/docker/migrate/v1"
  38. "github.com/docker/docker/pkg/fileutils"
  39. "github.com/docker/docker/pkg/graphdb"
  40. "github.com/docker/docker/pkg/idtools"
  41. "github.com/docker/docker/pkg/progress"
  42. "github.com/docker/docker/pkg/registrar"
  43. "github.com/docker/docker/pkg/signal"
  44. "github.com/docker/docker/pkg/streamformatter"
  45. "github.com/docker/docker/pkg/sysinfo"
  46. "github.com/docker/docker/pkg/system"
  47. "github.com/docker/docker/pkg/truncindex"
  48. "github.com/docker/docker/reference"
  49. "github.com/docker/docker/registry"
  50. "github.com/docker/docker/runconfig"
  51. "github.com/docker/docker/utils"
  52. volumedrivers "github.com/docker/docker/volume/drivers"
  53. "github.com/docker/docker/volume/local"
  54. "github.com/docker/docker/volume/store"
  55. "github.com/docker/libnetwork"
  56. nwconfig "github.com/docker/libnetwork/config"
  57. "github.com/docker/libtrust"
  58. )
  59. var (
  60. // DefaultRuntimeBinary is the default runtime to be used by
  61. // containerd if none is specified
  62. DefaultRuntimeBinary = "docker-runc"
  63. errSystemNotSupported = fmt.Errorf("The Docker daemon is not supported on this platform.")
  64. )
  65. // Daemon holds information about the Docker daemon.
  66. type Daemon struct {
  67. ID string
  68. repository string
  69. containers container.Store
  70. execCommands *exec.Store
  71. referenceStore reference.Store
  72. downloadManager *xfer.LayerDownloadManager
  73. uploadManager *xfer.LayerUploadManager
  74. distributionMetadataStore dmetadata.Store
  75. trustKey libtrust.PrivateKey
  76. idIndex *truncindex.TruncIndex
  77. configStore *Config
  78. statsCollector *statsCollector
  79. defaultLogConfig containertypes.LogConfig
  80. RegistryService registry.Service
  81. EventsService *events.Events
  82. netController libnetwork.NetworkController
  83. volumes *store.VolumeStore
  84. discoveryWatcher discoveryReloader
  85. root string
  86. seccompEnabled bool
  87. shutdown bool
  88. uidMaps []idtools.IDMap
  89. gidMaps []idtools.IDMap
  90. layerStore layer.Store
  91. imageStore image.Store
  92. nameIndex *registrar.Registrar
  93. linkIndex *linkIndex
  94. containerd libcontainerd.Client
  95. containerdRemote libcontainerd.Remote
  96. defaultIsolation containertypes.Isolation // Default isolation mode on Windows
  97. clusterProvider cluster.Provider
  98. }
  99. func (daemon *Daemon) restore() error {
  100. var (
  101. debug = utils.IsDebugEnabled()
  102. currentDriver = daemon.GraphDriverName()
  103. containers = make(map[string]*container.Container)
  104. )
  105. if !debug {
  106. logrus.Info("Loading containers: start.")
  107. }
  108. dir, err := ioutil.ReadDir(daemon.repository)
  109. if err != nil {
  110. return err
  111. }
  112. containerCount := 0
  113. for _, v := range dir {
  114. id := v.Name()
  115. container, err := daemon.load(id)
  116. if !debug && logrus.GetLevel() == logrus.InfoLevel {
  117. fmt.Print(".")
  118. containerCount++
  119. }
  120. if err != nil {
  121. logrus.Errorf("Failed to load container %v: %v", id, err)
  122. continue
  123. }
  124. // Ignore the container if it does not support the current driver being used by the graph
  125. if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
  126. rwlayer, err := daemon.layerStore.GetRWLayer(container.ID)
  127. if err != nil {
  128. logrus.Errorf("Failed to load container mount %v: %v", id, err)
  129. continue
  130. }
  131. container.RWLayer = rwlayer
  132. logrus.Debugf("Loaded container %v", container.ID)
  133. containers[container.ID] = container
  134. } else {
  135. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  136. }
  137. }
  138. var migrateLegacyLinks bool
  139. restartContainers := make(map[*container.Container]chan struct{})
  140. activeSandboxes := make(map[string]interface{})
  141. for _, c := range containers {
  142. if err := daemon.registerName(c); err != nil {
  143. logrus.Errorf("Failed to register container %s: %s", c.ID, err)
  144. continue
  145. }
  146. if err := daemon.Register(c); err != nil {
  147. logrus.Errorf("Failed to register container %s: %s", c.ID, err)
  148. continue
  149. }
  150. // The LogConfig.Type is empty if the container was created before docker 1.12 with default log driver.
  151. // We should rewrite it to use the daemon defaults.
  152. // Fixes https://github.com/docker/docker/issues/22536
  153. if c.HostConfig.LogConfig.Type == "" {
  154. if err := daemon.mergeAndVerifyLogConfig(&c.HostConfig.LogConfig); err != nil {
  155. logrus.Errorf("Failed to verify log config for container %s: %q", c.ID, err)
  156. continue
  157. }
  158. }
  159. }
  160. var wg sync.WaitGroup
  161. var mapLock sync.Mutex
  162. for _, c := range containers {
  163. wg.Add(1)
  164. go func(c *container.Container) {
  165. defer wg.Done()
  166. rm := c.RestartManager(false)
  167. if c.IsRunning() || c.IsPaused() {
  168. if err := daemon.containerd.Restore(c.ID, libcontainerd.WithRestartManager(rm)); err != nil {
  169. logrus.Errorf("Failed to restore with containerd: %q", err)
  170. return
  171. }
  172. if !c.HostConfig.NetworkMode.IsContainer() && c.IsRunning() {
  173. options, err := daemon.buildSandboxOptions(c)
  174. if err != nil {
  175. logrus.Warnf("Failed build sandbox option to restore container %s: %v", c.ID, err)
  176. }
  177. mapLock.Lock()
  178. activeSandboxes[c.NetworkSettings.SandboxID] = options
  179. mapLock.Unlock()
  180. }
  181. }
  182. // fixme: only if not running
  183. // get list of containers we need to restart
  184. if daemon.configStore.AutoRestart && !c.IsRunning() && !c.IsPaused() && c.ShouldRestart() {
  185. mapLock.Lock()
  186. restartContainers[c] = make(chan struct{})
  187. mapLock.Unlock()
  188. }
  189. if c.RemovalInProgress {
  190. // We probably crashed in the middle of a removal, reset
  191. // the flag.
  192. //
  193. // We DO NOT remove the container here as we do not
  194. // know if the user had requested for either the
  195. // associated volumes, network links or both to also
  196. // be removed. So we put the container in the "dead"
  197. // state and leave further processing up to them.
  198. logrus.Debugf("Resetting RemovalInProgress flag from %v", c.ID)
  199. c.ResetRemovalInProgress()
  200. c.SetDead()
  201. c.ToDisk()
  202. }
  203. // if c.hostConfig.Links is nil (not just empty), then it is using the old sqlite links and needs to be migrated
  204. if c.HostConfig != nil && c.HostConfig.Links == nil {
  205. migrateLegacyLinks = true
  206. }
  207. }(c)
  208. }
  209. wg.Wait()
  210. daemon.netController, err = daemon.initNetworkController(daemon.configStore, activeSandboxes)
  211. if err != nil {
  212. return fmt.Errorf("Error initializing network controller: %v", err)
  213. }
  214. // migrate any legacy links from sqlite
  215. linkdbFile := filepath.Join(daemon.root, "linkgraph.db")
  216. var legacyLinkDB *graphdb.Database
  217. if migrateLegacyLinks {
  218. legacyLinkDB, err = graphdb.NewSqliteConn(linkdbFile)
  219. if err != nil {
  220. return fmt.Errorf("error connecting to legacy link graph DB %s, container links may be lost: %v", linkdbFile, err)
  221. }
  222. defer legacyLinkDB.Close()
  223. }
  224. // Now that all the containers are registered, register the links
  225. for _, c := range containers {
  226. if migrateLegacyLinks {
  227. if err := daemon.migrateLegacySqliteLinks(legacyLinkDB, c); err != nil {
  228. return err
  229. }
  230. }
  231. if err := daemon.registerLinks(c, c.HostConfig); err != nil {
  232. logrus.Errorf("failed to register link for container %s: %v", c.ID, err)
  233. }
  234. }
  235. group := sync.WaitGroup{}
  236. for c, notifier := range restartContainers {
  237. group.Add(1)
  238. go func(c *container.Container, chNotify chan struct{}) {
  239. defer group.Done()
  240. logrus.Debugf("Starting container %s", c.ID)
  241. // ignore errors here as this is a best effort to wait for children to be
  242. // running before we try to start the container
  243. children := daemon.children(c)
  244. timeout := time.After(5 * time.Second)
  245. for _, child := range children {
  246. if notifier, exists := restartContainers[child]; exists {
  247. select {
  248. case <-notifier:
  249. case <-timeout:
  250. }
  251. }
  252. }
  253. // Make sure networks are available before starting
  254. daemon.waitForNetworks(c)
  255. if err := daemon.containerStart(c); err != nil {
  256. logrus.Errorf("Failed to start container %s: %s", c.ID, err)
  257. }
  258. close(chNotify)
  259. }(c, notifier)
  260. }
  261. group.Wait()
  262. // any containers that were started above would already have had this done,
  263. // however we need to now prepare the mountpoints for the rest of the containers as well.
  264. // This shouldn't cause any issue running on the containers that already had this run.
  265. // This must be run after any containers with a restart policy so that containerized plugins
  266. // can have a chance to be running before we try to initialize them.
  267. for _, c := range containers {
  268. // if the container has restart policy, do not
  269. // prepare the mountpoints since it has been done on restarting.
  270. // This is to speed up the daemon start when a restart container
  271. // has a volume and the volume dirver is not available.
  272. if _, ok := restartContainers[c]; ok {
  273. continue
  274. }
  275. group.Add(1)
  276. go func(c *container.Container) {
  277. defer group.Done()
  278. if err := daemon.prepareMountPoints(c); err != nil {
  279. logrus.Error(err)
  280. }
  281. }(c)
  282. }
  283. group.Wait()
  284. if !debug {
  285. if logrus.GetLevel() == logrus.InfoLevel && containerCount > 0 {
  286. fmt.Println()
  287. }
  288. logrus.Info("Loading containers: done.")
  289. }
  290. return nil
  291. }
  292. // waitForNetworks is used during daemon initialization when starting up containers
  293. // It ensures that all of a container's networks are available before the daemon tries to start the container.
  294. // In practice it just makes sure the discovery service is available for containers which use a network that require discovery.
  295. func (daemon *Daemon) waitForNetworks(c *container.Container) {
  296. if daemon.discoveryWatcher == nil {
  297. return
  298. }
  299. // Make sure if the container has a network that requires discovery that the discovery service is available before starting
  300. for netName := range c.NetworkSettings.Networks {
  301. // If we get `ErrNoSuchNetwork` here, it can assumed that it is due to discovery not being ready
  302. // Most likely this is because the K/V store used for discovery is in a container and needs to be started
  303. if _, err := daemon.netController.NetworkByName(netName); err != nil {
  304. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  305. continue
  306. }
  307. // use a longish timeout here due to some slowdowns in libnetwork if the k/v store is on anything other than --net=host
  308. // FIXME: why is this slow???
  309. logrus.Debugf("Container %s waiting for network to be ready", c.Name)
  310. select {
  311. case <-daemon.discoveryWatcher.ReadyCh():
  312. case <-time.After(60 * time.Second):
  313. }
  314. return
  315. }
  316. }
  317. }
  318. func (daemon *Daemon) children(c *container.Container) map[string]*container.Container {
  319. return daemon.linkIndex.children(c)
  320. }
  321. // parents returns the names of the parent containers of the container
  322. // with the given name.
  323. func (daemon *Daemon) parents(c *container.Container) map[string]*container.Container {
  324. return daemon.linkIndex.parents(c)
  325. }
  326. func (daemon *Daemon) registerLink(parent, child *container.Container, alias string) error {
  327. fullName := path.Join(parent.Name, alias)
  328. if err := daemon.nameIndex.Reserve(fullName, child.ID); err != nil {
  329. if err == registrar.ErrNameReserved {
  330. logrus.Warnf("error registering link for %s, to %s, as alias %s, ignoring: %v", parent.ID, child.ID, alias, err)
  331. return nil
  332. }
  333. return err
  334. }
  335. daemon.linkIndex.link(parent, child, fullName)
  336. return nil
  337. }
  338. // SetClusterProvider sets a component for quering the current cluster state.
  339. func (daemon *Daemon) SetClusterProvider(clusterProvider cluster.Provider) {
  340. daemon.clusterProvider = clusterProvider
  341. daemon.netController.SetClusterProvider(clusterProvider)
  342. }
  343. // IsSwarmCompatible verifies if the current daemon
  344. // configuration is compatible with the swarm mode
  345. func (daemon *Daemon) IsSwarmCompatible() error {
  346. if daemon.configStore == nil {
  347. return nil
  348. }
  349. return daemon.configStore.isSwarmCompatible()
  350. }
  351. // NewDaemon sets up everything for the daemon to be able to service
  352. // requests from the webserver.
  353. func NewDaemon(config *Config, registryService registry.Service, containerdRemote libcontainerd.Remote) (daemon *Daemon, err error) {
  354. setDefaultMtu(config)
  355. // Ensure that we have a correct root key limit for launching containers.
  356. if err := ModifyRootKeyLimit(); err != nil {
  357. logrus.Warnf("unable to modify root key limit, number of containers could be limitied by this quota: %v", err)
  358. }
  359. // Ensure we have compatible and valid configuration options
  360. if err := verifyDaemonSettings(config); err != nil {
  361. return nil, err
  362. }
  363. // Do we have a disabled network?
  364. config.DisableBridge = isBridgeNetworkDisabled(config)
  365. // Verify the platform is supported as a daemon
  366. if !platformSupported {
  367. return nil, errSystemNotSupported
  368. }
  369. // Validate platform-specific requirements
  370. if err := checkSystem(); err != nil {
  371. return nil, err
  372. }
  373. // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
  374. // on Windows to dump Go routine stacks
  375. setupDumpStackTrap()
  376. uidMaps, gidMaps, err := setupRemappedRoot(config)
  377. if err != nil {
  378. return nil, err
  379. }
  380. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  381. if err != nil {
  382. return nil, err
  383. }
  384. // get the canonical path to the Docker root directory
  385. var realRoot string
  386. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  387. realRoot = config.Root
  388. } else {
  389. realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
  390. if err != nil {
  391. return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  392. }
  393. }
  394. if err = setupDaemonRoot(config, realRoot, rootUID, rootGID); err != nil {
  395. return nil, err
  396. }
  397. // set up the tmpDir to use a canonical path
  398. tmp, err := tempDir(config.Root, rootUID, rootGID)
  399. if err != nil {
  400. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  401. }
  402. realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
  403. if err != nil {
  404. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  405. }
  406. os.Setenv("TMPDIR", realTmp)
  407. d := &Daemon{configStore: config}
  408. // Ensure the daemon is properly shutdown if there is a failure during
  409. // initialization
  410. defer func() {
  411. if err != nil {
  412. if err := d.Shutdown(); err != nil {
  413. logrus.Error(err)
  414. }
  415. }
  416. }()
  417. // Set the default isolation mode (only applicable on Windows)
  418. if err := d.setDefaultIsolation(); err != nil {
  419. return nil, fmt.Errorf("error setting default isolation mode: %v", err)
  420. }
  421. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  422. if err := configureMaxThreads(config); err != nil {
  423. logrus.Warnf("Failed to configure golang's threads limit: %v", err)
  424. }
  425. installDefaultAppArmorProfile()
  426. daemonRepo := filepath.Join(config.Root, "containers")
  427. if err := idtools.MkdirAllAs(daemonRepo, 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  428. return nil, err
  429. }
  430. driverName := os.Getenv("DOCKER_DRIVER")
  431. if driverName == "" {
  432. driverName = config.GraphDriver
  433. }
  434. d.layerStore, err = layer.NewStoreFromOptions(layer.StoreOptions{
  435. StorePath: config.Root,
  436. MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
  437. GraphDriver: driverName,
  438. GraphDriverOptions: config.GraphOptions,
  439. UIDMaps: uidMaps,
  440. GIDMaps: gidMaps,
  441. })
  442. if err != nil {
  443. return nil, err
  444. }
  445. graphDriver := d.layerStore.DriverName()
  446. imageRoot := filepath.Join(config.Root, "image", graphDriver)
  447. // Configure and validate the kernels security support
  448. if err := configureKernelSecuritySupport(config, graphDriver); err != nil {
  449. return nil, err
  450. }
  451. logrus.Debugf("Max Concurrent Downloads: %d", *config.MaxConcurrentDownloads)
  452. d.downloadManager = xfer.NewLayerDownloadManager(d.layerStore, *config.MaxConcurrentDownloads)
  453. logrus.Debugf("Max Concurrent Uploads: %d", *config.MaxConcurrentUploads)
  454. d.uploadManager = xfer.NewLayerUploadManager(*config.MaxConcurrentUploads)
  455. ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
  456. if err != nil {
  457. return nil, err
  458. }
  459. d.imageStore, err = image.NewImageStore(ifs, d.layerStore)
  460. if err != nil {
  461. return nil, err
  462. }
  463. // Configure the volumes driver
  464. volStore, err := d.configureVolumes(rootUID, rootGID)
  465. if err != nil {
  466. return nil, err
  467. }
  468. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  469. if err != nil {
  470. return nil, err
  471. }
  472. trustDir := filepath.Join(config.Root, "trust")
  473. if err := system.MkdirAll(trustDir, 0700); err != nil {
  474. return nil, err
  475. }
  476. distributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, "distribution"))
  477. if err != nil {
  478. return nil, err
  479. }
  480. eventsService := events.New()
  481. referenceStore, err := reference.NewReferenceStore(filepath.Join(imageRoot, "repositories.json"))
  482. if err != nil {
  483. return nil, fmt.Errorf("Couldn't create Tag store repositories: %s", err)
  484. }
  485. if err := restoreCustomImage(d.imageStore, d.layerStore, referenceStore); err != nil {
  486. return nil, fmt.Errorf("Couldn't restore custom images: %s", err)
  487. }
  488. migrationStart := time.Now()
  489. if err := v1.Migrate(config.Root, graphDriver, d.layerStore, d.imageStore, referenceStore, distributionMetadataStore); err != nil {
  490. 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)
  491. }
  492. logrus.Infof("Graph migration to content-addressability took %.2f seconds", time.Since(migrationStart).Seconds())
  493. // Discovery is only enabled when the daemon is launched with an address to advertise. When
  494. // initialized, the daemon is registered and we can store the discovery backend as its read-only
  495. if err := d.initDiscovery(config); err != nil {
  496. return nil, err
  497. }
  498. sysInfo := sysinfo.New(false)
  499. // Check if Devices cgroup is mounted, it is hard requirement for container security,
  500. // on Linux.
  501. if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled {
  502. return nil, fmt.Errorf("Devices cgroup isn't mounted")
  503. }
  504. d.ID = trustKey.PublicKey().KeyID()
  505. d.repository = daemonRepo
  506. d.containers = container.NewMemoryStore()
  507. d.execCommands = exec.NewStore()
  508. d.referenceStore = referenceStore
  509. d.distributionMetadataStore = distributionMetadataStore
  510. d.trustKey = trustKey
  511. d.idIndex = truncindex.NewTruncIndex([]string{})
  512. d.statsCollector = d.newStatsCollector(1 * time.Second)
  513. d.defaultLogConfig = containertypes.LogConfig{
  514. Type: config.LogConfig.Type,
  515. Config: config.LogConfig.Config,
  516. }
  517. d.RegistryService = registryService
  518. d.EventsService = eventsService
  519. d.volumes = volStore
  520. d.root = config.Root
  521. d.uidMaps = uidMaps
  522. d.gidMaps = gidMaps
  523. d.seccompEnabled = sysInfo.Seccomp
  524. d.nameIndex = registrar.NewRegistrar()
  525. d.linkIndex = newLinkIndex()
  526. d.containerdRemote = containerdRemote
  527. go d.execCommandGC()
  528. d.containerd, err = containerdRemote.Client(d)
  529. if err != nil {
  530. return nil, err
  531. }
  532. if err := d.restore(); err != nil {
  533. return nil, err
  534. }
  535. return d, nil
  536. }
  537. func (daemon *Daemon) shutdownContainer(c *container.Container) error {
  538. // TODO(windows): Handle docker restart with paused containers
  539. if c.IsPaused() {
  540. // To terminate a process in freezer cgroup, we should send
  541. // SIGTERM to this process then unfreeze it, and the process will
  542. // force to terminate immediately.
  543. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpause it", c.ID)
  544. sig, ok := signal.SignalMap["TERM"]
  545. if !ok {
  546. return fmt.Errorf("System doesn not support SIGTERM")
  547. }
  548. if err := daemon.kill(c, int(sig)); err != nil {
  549. return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err)
  550. }
  551. if err := daemon.containerUnpause(c); err != nil {
  552. return fmt.Errorf("Failed to unpause container %s with error: %v", c.ID, err)
  553. }
  554. if _, err := c.WaitStop(10 * time.Second); err != nil {
  555. logrus.Debugf("container %s failed to exit in 10 second of SIGTERM, sending SIGKILL to force", c.ID)
  556. sig, ok := signal.SignalMap["KILL"]
  557. if !ok {
  558. return fmt.Errorf("System does not support SIGKILL")
  559. }
  560. if err := daemon.kill(c, int(sig)); err != nil {
  561. logrus.Errorf("Failed to SIGKILL container %s", c.ID)
  562. }
  563. c.WaitStop(-1 * time.Second)
  564. return err
  565. }
  566. }
  567. // If container failed to exit in 10 seconds of SIGTERM, then using the force
  568. if err := daemon.containerStop(c, 10); err != nil {
  569. return fmt.Errorf("Stop container %s with error: %v", c.ID, err)
  570. }
  571. c.WaitStop(-1 * time.Second)
  572. return nil
  573. }
  574. // Shutdown stops the daemon.
  575. func (daemon *Daemon) Shutdown() error {
  576. daemon.shutdown = true
  577. // Keep mounts and networking running on daemon shutdown if
  578. // we are to keep containers running and restore them.
  579. if daemon.configStore.LiveRestore {
  580. return nil
  581. }
  582. if daemon.containers != nil {
  583. logrus.Debug("starting clean shutdown of all containers...")
  584. daemon.containers.ApplyAll(func(c *container.Container) {
  585. if !c.IsRunning() {
  586. return
  587. }
  588. logrus.Debugf("stopping %s", c.ID)
  589. if err := daemon.shutdownContainer(c); err != nil {
  590. logrus.Errorf("Stop container error: %v", err)
  591. return
  592. }
  593. if mountid, err := daemon.layerStore.GetMountID(c.ID); err == nil {
  594. daemon.cleanupMountsByID(mountid)
  595. }
  596. logrus.Debugf("container stopped %s", c.ID)
  597. })
  598. }
  599. // trigger libnetwork Stop only if it's initialized
  600. if daemon.netController != nil {
  601. daemon.netController.Stop()
  602. }
  603. if daemon.layerStore != nil {
  604. if err := daemon.layerStore.Cleanup(); err != nil {
  605. logrus.Errorf("Error during layer Store.Cleanup(): %v", err)
  606. }
  607. }
  608. if err := daemon.cleanupMounts(); err != nil {
  609. return err
  610. }
  611. return nil
  612. }
  613. // Mount sets container.BaseFS
  614. // (is it not set coming in? why is it unset?)
  615. func (daemon *Daemon) Mount(container *container.Container) error {
  616. dir, err := container.RWLayer.Mount(container.GetMountLabel())
  617. if err != nil {
  618. return err
  619. }
  620. logrus.Debugf("container mounted via layerStore: %v", dir)
  621. if container.BaseFS != dir {
  622. // The mount path reported by the graph driver should always be trusted on Windows, since the
  623. // volume path for a given mounted layer may change over time. This should only be an error
  624. // on non-Windows operating systems.
  625. if container.BaseFS != "" && runtime.GOOS != "windows" {
  626. daemon.Unmount(container)
  627. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  628. daemon.GraphDriverName(), container.ID, container.BaseFS, dir)
  629. }
  630. }
  631. container.BaseFS = dir // TODO: combine these fields
  632. return nil
  633. }
  634. // Unmount unsets the container base filesystem
  635. func (daemon *Daemon) Unmount(container *container.Container) error {
  636. if err := container.RWLayer.Unmount(); err != nil {
  637. logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
  638. return err
  639. }
  640. return nil
  641. }
  642. func writeDistributionProgress(cancelFunc func(), outStream io.Writer, progressChan <-chan progress.Progress) {
  643. progressOutput := streamformatter.NewJSONStreamFormatter().NewProgressOutput(outStream, false)
  644. operationCancelled := false
  645. for prog := range progressChan {
  646. if err := progressOutput.WriteProgress(prog); err != nil && !operationCancelled {
  647. // don't log broken pipe errors as this is the normal case when a client aborts
  648. if isBrokenPipe(err) {
  649. logrus.Info("Pull session cancelled")
  650. } else {
  651. logrus.Errorf("error writing progress to client: %v", err)
  652. }
  653. cancelFunc()
  654. operationCancelled = true
  655. // Don't return, because we need to continue draining
  656. // progressChan until it's closed to avoid a deadlock.
  657. }
  658. }
  659. }
  660. func isBrokenPipe(e error) bool {
  661. if netErr, ok := e.(*net.OpError); ok {
  662. e = netErr.Err
  663. if sysErr, ok := netErr.Err.(*os.SyscallError); ok {
  664. e = sysErr.Err
  665. }
  666. }
  667. return e == syscall.EPIPE
  668. }
  669. // GraphDriverName returns the name of the graph driver used by the layer.Store
  670. func (daemon *Daemon) GraphDriverName() string {
  671. return daemon.layerStore.DriverName()
  672. }
  673. // GetUIDGIDMaps returns the current daemon's user namespace settings
  674. // for the full uid and gid maps which will be applied to containers
  675. // started in this instance.
  676. func (daemon *Daemon) GetUIDGIDMaps() ([]idtools.IDMap, []idtools.IDMap) {
  677. return daemon.uidMaps, daemon.gidMaps
  678. }
  679. // GetRemappedUIDGID returns the current daemon's uid and gid values
  680. // if user namespaces are in use for this daemon instance. If not
  681. // this function will return "real" root values of 0, 0.
  682. func (daemon *Daemon) GetRemappedUIDGID() (int, int) {
  683. uid, gid, _ := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps)
  684. return uid, gid
  685. }
  686. // tempDir returns the default directory to use for temporary files.
  687. func tempDir(rootDir string, rootUID, rootGID int) (string, error) {
  688. var tmpDir string
  689. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  690. tmpDir = filepath.Join(rootDir, "tmp")
  691. }
  692. return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID)
  693. }
  694. func (daemon *Daemon) setupInitLayer(initPath string) error {
  695. rootUID, rootGID := daemon.GetRemappedUIDGID()
  696. return setupInitLayer(initPath, rootUID, rootGID)
  697. }
  698. func setDefaultMtu(config *Config) {
  699. // do nothing if the config does not have the default 0 value.
  700. if config.Mtu != 0 {
  701. return
  702. }
  703. config.Mtu = defaultNetworkMtu
  704. }
  705. func (daemon *Daemon) configureVolumes(rootUID, rootGID int) (*store.VolumeStore, error) {
  706. volumesDriver, err := local.New(daemon.configStore.Root, rootUID, rootGID)
  707. if err != nil {
  708. return nil, err
  709. }
  710. if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) {
  711. return nil, fmt.Errorf("local volume driver could not be registered")
  712. }
  713. return store.New(daemon.configStore.Root)
  714. }
  715. // IsShuttingDown tells whether the daemon is shutting down or not
  716. func (daemon *Daemon) IsShuttingDown() bool {
  717. return daemon.shutdown
  718. }
  719. // initDiscovery initializes the discovery watcher for this daemon.
  720. func (daemon *Daemon) initDiscovery(config *Config) error {
  721. advertise, err := parseClusterAdvertiseSettings(config.ClusterStore, config.ClusterAdvertise)
  722. if err != nil {
  723. if err == errDiscoveryDisabled {
  724. return nil
  725. }
  726. return err
  727. }
  728. config.ClusterAdvertise = advertise
  729. discoveryWatcher, err := initDiscovery(config.ClusterStore, config.ClusterAdvertise, config.ClusterOpts)
  730. if err != nil {
  731. return fmt.Errorf("discovery initialization failed (%v)", err)
  732. }
  733. daemon.discoveryWatcher = discoveryWatcher
  734. return nil
  735. }
  736. // Reload reads configuration changes and modifies the
  737. // daemon according to those changes.
  738. // These are the settings that Reload changes:
  739. // - Daemon labels.
  740. // - Daemon debug log level.
  741. // - Daemon max concurrent downloads
  742. // - Daemon max concurrent uploads
  743. // - Cluster discovery (reconfigure and restart).
  744. // - Daemon live restore
  745. func (daemon *Daemon) Reload(config *Config) error {
  746. var err error
  747. // used to hold reloaded changes
  748. attributes := map[string]string{}
  749. // We need defer here to ensure the lock is released as
  750. // daemon.SystemInfo() will try to get it too
  751. defer func() {
  752. if err == nil {
  753. daemon.LogDaemonEventWithAttributes("reload", attributes)
  754. }
  755. }()
  756. daemon.configStore.reloadLock.Lock()
  757. defer daemon.configStore.reloadLock.Unlock()
  758. daemon.platformReload(config, &attributes)
  759. if err = daemon.reloadClusterDiscovery(config); err != nil {
  760. return err
  761. }
  762. if config.IsValueSet("labels") {
  763. daemon.configStore.Labels = config.Labels
  764. }
  765. if config.IsValueSet("debug") {
  766. daemon.configStore.Debug = config.Debug
  767. }
  768. if config.IsValueSet("live-restore") {
  769. daemon.configStore.LiveRestore = config.LiveRestore
  770. if err := daemon.containerdRemote.UpdateOptions(libcontainerd.WithLiveRestore(config.LiveRestore)); err != nil {
  771. return err
  772. }
  773. }
  774. // If no value is set for max-concurrent-downloads we assume it is the default value
  775. // We always "reset" as the cost is lightweight and easy to maintain.
  776. if config.IsValueSet("max-concurrent-downloads") && config.MaxConcurrentDownloads != nil {
  777. *daemon.configStore.MaxConcurrentDownloads = *config.MaxConcurrentDownloads
  778. } else {
  779. maxConcurrentDownloads := defaultMaxConcurrentDownloads
  780. daemon.configStore.MaxConcurrentDownloads = &maxConcurrentDownloads
  781. }
  782. logrus.Debugf("Reset Max Concurrent Downloads: %d", *daemon.configStore.MaxConcurrentDownloads)
  783. if daemon.downloadManager != nil {
  784. daemon.downloadManager.SetConcurrency(*daemon.configStore.MaxConcurrentDownloads)
  785. }
  786. // If no value is set for max-concurrent-upload we assume it is the default value
  787. // We always "reset" as the cost is lightweight and easy to maintain.
  788. if config.IsValueSet("max-concurrent-uploads") && config.MaxConcurrentUploads != nil {
  789. *daemon.configStore.MaxConcurrentUploads = *config.MaxConcurrentUploads
  790. } else {
  791. maxConcurrentUploads := defaultMaxConcurrentUploads
  792. daemon.configStore.MaxConcurrentUploads = &maxConcurrentUploads
  793. }
  794. logrus.Debugf("Reset Max Concurrent Uploads: %d", *daemon.configStore.MaxConcurrentUploads)
  795. if daemon.uploadManager != nil {
  796. daemon.uploadManager.SetConcurrency(*daemon.configStore.MaxConcurrentUploads)
  797. }
  798. // We emit daemon reload event here with updatable configurations
  799. attributes["debug"] = fmt.Sprintf("%t", daemon.configStore.Debug)
  800. attributes["cluster-store"] = daemon.configStore.ClusterStore
  801. if daemon.configStore.ClusterOpts != nil {
  802. opts, _ := json.Marshal(daemon.configStore.ClusterOpts)
  803. attributes["cluster-store-opts"] = string(opts)
  804. } else {
  805. attributes["cluster-store-opts"] = "{}"
  806. }
  807. attributes["cluster-advertise"] = daemon.configStore.ClusterAdvertise
  808. if daemon.configStore.Labels != nil {
  809. labels, _ := json.Marshal(daemon.configStore.Labels)
  810. attributes["labels"] = string(labels)
  811. } else {
  812. attributes["labels"] = "[]"
  813. }
  814. attributes["max-concurrent-downloads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentDownloads)
  815. attributes["max-concurrent-uploads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentUploads)
  816. return nil
  817. }
  818. func (daemon *Daemon) reloadClusterDiscovery(config *Config) error {
  819. var err error
  820. newAdvertise := daemon.configStore.ClusterAdvertise
  821. newClusterStore := daemon.configStore.ClusterStore
  822. if config.IsValueSet("cluster-advertise") {
  823. if config.IsValueSet("cluster-store") {
  824. newClusterStore = config.ClusterStore
  825. }
  826. newAdvertise, err = parseClusterAdvertiseSettings(newClusterStore, config.ClusterAdvertise)
  827. if err != nil && err != errDiscoveryDisabled {
  828. return err
  829. }
  830. }
  831. if daemon.clusterProvider != nil {
  832. if err := config.isSwarmCompatible(); err != nil {
  833. return err
  834. }
  835. }
  836. // check discovery modifications
  837. if !modifiedDiscoverySettings(daemon.configStore, newAdvertise, newClusterStore, config.ClusterOpts) {
  838. return nil
  839. }
  840. // enable discovery for the first time if it was not previously enabled
  841. if daemon.discoveryWatcher == nil {
  842. discoveryWatcher, err := initDiscovery(newClusterStore, newAdvertise, config.ClusterOpts)
  843. if err != nil {
  844. return fmt.Errorf("discovery initialization failed (%v)", err)
  845. }
  846. daemon.discoveryWatcher = discoveryWatcher
  847. } else {
  848. if err == errDiscoveryDisabled {
  849. // disable discovery if it was previously enabled and it's disabled now
  850. daemon.discoveryWatcher.Stop()
  851. } else {
  852. // reload discovery
  853. if err = daemon.discoveryWatcher.Reload(config.ClusterStore, newAdvertise, config.ClusterOpts); err != nil {
  854. return err
  855. }
  856. }
  857. }
  858. daemon.configStore.ClusterStore = newClusterStore
  859. daemon.configStore.ClusterOpts = config.ClusterOpts
  860. daemon.configStore.ClusterAdvertise = newAdvertise
  861. if daemon.netController == nil {
  862. return nil
  863. }
  864. netOptions, err := daemon.networkOptions(daemon.configStore, nil)
  865. if err != nil {
  866. logrus.Warnf("Failed to reload configuration with network controller: %v", err)
  867. return nil
  868. }
  869. err = daemon.netController.ReloadConfiguration(netOptions...)
  870. if err != nil {
  871. logrus.Warnf("Failed to reload configuration with network controller: %v", err)
  872. }
  873. return nil
  874. }
  875. func isBridgeNetworkDisabled(config *Config) bool {
  876. return config.bridgeConfig.Iface == disableNetworkBridge
  877. }
  878. func (daemon *Daemon) networkOptions(dconfig *Config, activeSandboxes map[string]interface{}) ([]nwconfig.Option, error) {
  879. options := []nwconfig.Option{}
  880. if dconfig == nil {
  881. return options, nil
  882. }
  883. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  884. dd := runconfig.DefaultDaemonNetworkMode()
  885. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  886. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  887. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  888. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  889. kv := strings.Split(dconfig.ClusterStore, "://")
  890. if len(kv) != 2 {
  891. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  892. }
  893. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  894. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  895. }
  896. if len(dconfig.ClusterOpts) > 0 {
  897. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  898. }
  899. if daemon.discoveryWatcher != nil {
  900. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  901. }
  902. if dconfig.ClusterAdvertise != "" {
  903. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  904. }
  905. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  906. options = append(options, driverOptions(dconfig)...)
  907. if daemon.configStore != nil && daemon.configStore.LiveRestore && len(activeSandboxes) != 0 {
  908. options = append(options, nwconfig.OptionActiveSandboxes(activeSandboxes))
  909. }
  910. return options, nil
  911. }
  912. func copyBlkioEntry(entries []*containerd.BlkioStatsEntry) []types.BlkioStatEntry {
  913. out := make([]types.BlkioStatEntry, len(entries))
  914. for i, re := range entries {
  915. out[i] = types.BlkioStatEntry{
  916. Major: re.Major,
  917. Minor: re.Minor,
  918. Op: re.Op,
  919. Value: re.Value,
  920. }
  921. }
  922. return out
  923. }