daemon.go 37 KB

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