daemon.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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 %s with containerd: %s", c.ID, 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, we can assume 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 querying 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(config.Root)
  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. if err := setupDaemonProcess(config); err != nil {
  398. return nil, err
  399. }
  400. // set up the tmpDir to use a canonical path
  401. tmp, err := tempDir(config.Root, rootUID, rootGID)
  402. if err != nil {
  403. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  404. }
  405. realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
  406. if err != nil {
  407. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  408. }
  409. os.Setenv("TMPDIR", realTmp)
  410. d := &Daemon{configStore: config}
  411. // Ensure the daemon is properly shutdown if there is a failure during
  412. // initialization
  413. defer func() {
  414. if err != nil {
  415. if err := d.Shutdown(); err != nil {
  416. logrus.Error(err)
  417. }
  418. }
  419. }()
  420. // Set the default isolation mode (only applicable on Windows)
  421. if err := d.setDefaultIsolation(); err != nil {
  422. return nil, fmt.Errorf("error setting default isolation mode: %v", err)
  423. }
  424. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  425. if err := configureMaxThreads(config); err != nil {
  426. logrus.Warnf("Failed to configure golang's threads limit: %v", err)
  427. }
  428. installDefaultAppArmorProfile()
  429. daemonRepo := filepath.Join(config.Root, "containers")
  430. if err := idtools.MkdirAllAs(daemonRepo, 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  431. return nil, err
  432. }
  433. driverName := os.Getenv("DOCKER_DRIVER")
  434. if driverName == "" {
  435. driverName = config.GraphDriver
  436. }
  437. d.layerStore, err = layer.NewStoreFromOptions(layer.StoreOptions{
  438. StorePath: config.Root,
  439. MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
  440. GraphDriver: driverName,
  441. GraphDriverOptions: config.GraphOptions,
  442. UIDMaps: uidMaps,
  443. GIDMaps: gidMaps,
  444. })
  445. if err != nil {
  446. return nil, err
  447. }
  448. graphDriver := d.layerStore.DriverName()
  449. imageRoot := filepath.Join(config.Root, "image", graphDriver)
  450. // Configure and validate the kernels security support
  451. if err := configureKernelSecuritySupport(config, graphDriver); err != nil {
  452. return nil, err
  453. }
  454. logrus.Debugf("Max Concurrent Downloads: %d", *config.MaxConcurrentDownloads)
  455. d.downloadManager = xfer.NewLayerDownloadManager(d.layerStore, *config.MaxConcurrentDownloads)
  456. logrus.Debugf("Max Concurrent Uploads: %d", *config.MaxConcurrentUploads)
  457. d.uploadManager = xfer.NewLayerUploadManager(*config.MaxConcurrentUploads)
  458. ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
  459. if err != nil {
  460. return nil, err
  461. }
  462. d.imageStore, err = image.NewImageStore(ifs, d.layerStore)
  463. if err != nil {
  464. return nil, err
  465. }
  466. // Configure the volumes driver
  467. volStore, err := d.configureVolumes(rootUID, rootGID)
  468. if err != nil {
  469. return nil, err
  470. }
  471. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  472. if err != nil {
  473. return nil, err
  474. }
  475. trustDir := filepath.Join(config.Root, "trust")
  476. if err := system.MkdirAll(trustDir, 0700); err != nil {
  477. return nil, err
  478. }
  479. distributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, "distribution"))
  480. if err != nil {
  481. return nil, err
  482. }
  483. eventsService := events.New()
  484. referenceStore, err := reference.NewReferenceStore(filepath.Join(imageRoot, "repositories.json"))
  485. if err != nil {
  486. return nil, fmt.Errorf("Couldn't create Tag store repositories: %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. if err := pluginInit(d, config, containerdRemote); err != nil {
  536. return nil, err
  537. }
  538. return d, nil
  539. }
  540. func (daemon *Daemon) shutdownContainer(c *container.Container) error {
  541. // TODO(windows): Handle docker restart with paused containers
  542. if c.IsPaused() {
  543. // To terminate a process in freezer cgroup, we should send
  544. // SIGTERM to this process then unfreeze it, and the process will
  545. // force to terminate immediately.
  546. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpausing it", c.ID)
  547. sig, ok := signal.SignalMap["TERM"]
  548. if !ok {
  549. return fmt.Errorf("System does not support SIGTERM")
  550. }
  551. if err := daemon.kill(c, int(sig)); err != nil {
  552. return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err)
  553. }
  554. if err := daemon.containerUnpause(c); err != nil {
  555. return fmt.Errorf("Failed to unpause container %s with error: %v", c.ID, err)
  556. }
  557. if _, err := c.WaitStop(10 * time.Second); err != nil {
  558. logrus.Debugf("container %s failed to exit in 10 seconds of SIGTERM, sending SIGKILL to force", c.ID)
  559. sig, ok := signal.SignalMap["KILL"]
  560. if !ok {
  561. return fmt.Errorf("System does not support SIGKILL")
  562. }
  563. if err := daemon.kill(c, int(sig)); err != nil {
  564. logrus.Errorf("Failed to SIGKILL container %s", c.ID)
  565. }
  566. c.WaitStop(-1 * time.Second)
  567. return err
  568. }
  569. }
  570. // If container failed to exit in 10 seconds of SIGTERM, then using the force
  571. if err := daemon.containerStop(c, 10); err != nil {
  572. return fmt.Errorf("Failed to stop container %s with error: %v", c.ID, err)
  573. }
  574. c.WaitStop(-1 * time.Second)
  575. return nil
  576. }
  577. // Shutdown stops the daemon.
  578. func (daemon *Daemon) Shutdown() error {
  579. daemon.shutdown = true
  580. // Keep mounts and networking running on daemon shutdown if
  581. // we are to keep containers running and restore them.
  582. pluginShutdown()
  583. if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
  584. // check if there are any running containers, if none we should do some cleanup
  585. if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
  586. return nil
  587. }
  588. }
  589. if daemon.containers != nil {
  590. logrus.Debug("starting clean shutdown of all containers...")
  591. daemon.containers.ApplyAll(func(c *container.Container) {
  592. if !c.IsRunning() {
  593. return
  594. }
  595. logrus.Debugf("stopping %s", c.ID)
  596. if err := daemon.shutdownContainer(c); err != nil {
  597. logrus.Errorf("Stop container error: %v", err)
  598. return
  599. }
  600. if mountid, err := daemon.layerStore.GetMountID(c.ID); err == nil {
  601. daemon.cleanupMountsByID(mountid)
  602. }
  603. logrus.Debugf("container stopped %s", c.ID)
  604. })
  605. }
  606. // trigger libnetwork Stop only if it's initialized
  607. if daemon.netController != nil {
  608. daemon.netController.Stop()
  609. }
  610. if daemon.layerStore != nil {
  611. if err := daemon.layerStore.Cleanup(); err != nil {
  612. logrus.Errorf("Error during layer Store.Cleanup(): %v", err)
  613. }
  614. }
  615. if err := daemon.cleanupMounts(); err != nil {
  616. return err
  617. }
  618. return nil
  619. }
  620. // Mount sets container.BaseFS
  621. // (is it not set coming in? why is it unset?)
  622. func (daemon *Daemon) Mount(container *container.Container) error {
  623. dir, err := container.RWLayer.Mount(container.GetMountLabel())
  624. if err != nil {
  625. return err
  626. }
  627. logrus.Debugf("container mounted via layerStore: %v", dir)
  628. if container.BaseFS != dir {
  629. // The mount path reported by the graph driver should always be trusted on Windows, since the
  630. // volume path for a given mounted layer may change over time. This should only be an error
  631. // on non-Windows operating systems.
  632. if container.BaseFS != "" && runtime.GOOS != "windows" {
  633. daemon.Unmount(container)
  634. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  635. daemon.GraphDriverName(), container.ID, container.BaseFS, dir)
  636. }
  637. }
  638. container.BaseFS = dir // TODO: combine these fields
  639. return nil
  640. }
  641. // Unmount unsets the container base filesystem
  642. func (daemon *Daemon) Unmount(container *container.Container) error {
  643. if err := container.RWLayer.Unmount(); err != nil {
  644. logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
  645. return err
  646. }
  647. return nil
  648. }
  649. // V4Subnets returns the IPv4 subnets of networks that are managed by Docker.
  650. func (daemon *Daemon) V4Subnets() []net.IPNet {
  651. var subnets []net.IPNet
  652. managedNetworks := daemon.netController.Networks()
  653. for _, managedNetwork := range managedNetworks {
  654. v4Infos, _ := managedNetwork.Info().IpamInfo()
  655. for _, v4Info := range v4Infos {
  656. if v4Info.IPAMData.Pool != nil {
  657. subnets = append(subnets, *v4Info.IPAMData.Pool)
  658. }
  659. }
  660. }
  661. return subnets
  662. }
  663. // V6Subnets returns the IPv6 subnets of networks that are managed by Docker.
  664. func (daemon *Daemon) V6Subnets() []net.IPNet {
  665. var subnets []net.IPNet
  666. managedNetworks := daemon.netController.Networks()
  667. for _, managedNetwork := range managedNetworks {
  668. _, v6Infos := managedNetwork.Info().IpamInfo()
  669. for _, v6Info := range v6Infos {
  670. if v6Info.IPAMData.Pool != nil {
  671. subnets = append(subnets, *v6Info.IPAMData.Pool)
  672. }
  673. }
  674. }
  675. return subnets
  676. }
  677. func writeDistributionProgress(cancelFunc func(), outStream io.Writer, progressChan <-chan progress.Progress) {
  678. progressOutput := streamformatter.NewJSONStreamFormatter().NewProgressOutput(outStream, false)
  679. operationCancelled := false
  680. for prog := range progressChan {
  681. if err := progressOutput.WriteProgress(prog); err != nil && !operationCancelled {
  682. // don't log broken pipe errors as this is the normal case when a client aborts
  683. if isBrokenPipe(err) {
  684. logrus.Info("Pull session cancelled")
  685. } else {
  686. logrus.Errorf("error writing progress to client: %v", err)
  687. }
  688. cancelFunc()
  689. operationCancelled = true
  690. // Don't return, because we need to continue draining
  691. // progressChan until it's closed to avoid a deadlock.
  692. }
  693. }
  694. }
  695. func isBrokenPipe(e error) bool {
  696. if netErr, ok := e.(*net.OpError); ok {
  697. e = netErr.Err
  698. if sysErr, ok := netErr.Err.(*os.SyscallError); ok {
  699. e = sysErr.Err
  700. }
  701. }
  702. return e == syscall.EPIPE
  703. }
  704. // GraphDriverName returns the name of the graph driver used by the layer.Store
  705. func (daemon *Daemon) GraphDriverName() string {
  706. return daemon.layerStore.DriverName()
  707. }
  708. // GetUIDGIDMaps returns the current daemon's user namespace settings
  709. // for the full uid and gid maps which will be applied to containers
  710. // started in this instance.
  711. func (daemon *Daemon) GetUIDGIDMaps() ([]idtools.IDMap, []idtools.IDMap) {
  712. return daemon.uidMaps, daemon.gidMaps
  713. }
  714. // GetRemappedUIDGID returns the current daemon's uid and gid values
  715. // if user namespaces are in use for this daemon instance. If not
  716. // this function will return "real" root values of 0, 0.
  717. func (daemon *Daemon) GetRemappedUIDGID() (int, int) {
  718. uid, gid, _ := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps)
  719. return uid, gid
  720. }
  721. // tempDir returns the default directory to use for temporary files.
  722. func tempDir(rootDir string, rootUID, rootGID int) (string, error) {
  723. var tmpDir string
  724. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  725. tmpDir = filepath.Join(rootDir, "tmp")
  726. }
  727. return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID)
  728. }
  729. func (daemon *Daemon) setupInitLayer(initPath string) error {
  730. rootUID, rootGID := daemon.GetRemappedUIDGID()
  731. return setupInitLayer(initPath, rootUID, rootGID)
  732. }
  733. func setDefaultMtu(config *Config) {
  734. // do nothing if the config does not have the default 0 value.
  735. if config.Mtu != 0 {
  736. return
  737. }
  738. config.Mtu = defaultNetworkMtu
  739. }
  740. func (daemon *Daemon) configureVolumes(rootUID, rootGID int) (*store.VolumeStore, error) {
  741. volumesDriver, err := local.New(daemon.configStore.Root, rootUID, rootGID)
  742. if err != nil {
  743. return nil, err
  744. }
  745. if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) {
  746. return nil, fmt.Errorf("local volume driver could not be registered")
  747. }
  748. return store.New(daemon.configStore.Root)
  749. }
  750. // IsShuttingDown tells whether the daemon is shutting down or not
  751. func (daemon *Daemon) IsShuttingDown() bool {
  752. return daemon.shutdown
  753. }
  754. // initDiscovery initializes the discovery watcher for this daemon.
  755. func (daemon *Daemon) initDiscovery(config *Config) error {
  756. advertise, err := parseClusterAdvertiseSettings(config.ClusterStore, config.ClusterAdvertise)
  757. if err != nil {
  758. if err == errDiscoveryDisabled {
  759. return nil
  760. }
  761. return err
  762. }
  763. config.ClusterAdvertise = advertise
  764. discoveryWatcher, err := initDiscovery(config.ClusterStore, config.ClusterAdvertise, config.ClusterOpts)
  765. if err != nil {
  766. return fmt.Errorf("discovery initialization failed (%v)", err)
  767. }
  768. daemon.discoveryWatcher = discoveryWatcher
  769. return nil
  770. }
  771. // Reload reads configuration changes and modifies the
  772. // daemon according to those changes.
  773. // These are the settings that Reload changes:
  774. // - Daemon labels.
  775. // - Daemon debug log level.
  776. // - Daemon max concurrent downloads
  777. // - Daemon max concurrent uploads
  778. // - Cluster discovery (reconfigure and restart).
  779. // - Daemon live restore
  780. func (daemon *Daemon) Reload(config *Config) error {
  781. var err error
  782. // used to hold reloaded changes
  783. attributes := map[string]string{}
  784. // We need defer here to ensure the lock is released as
  785. // daemon.SystemInfo() will try to get it too
  786. defer func() {
  787. if err == nil {
  788. daemon.LogDaemonEventWithAttributes("reload", attributes)
  789. }
  790. }()
  791. daemon.configStore.reloadLock.Lock()
  792. defer daemon.configStore.reloadLock.Unlock()
  793. daemon.platformReload(config, &attributes)
  794. if err = daemon.reloadClusterDiscovery(config); err != nil {
  795. return err
  796. }
  797. if config.IsValueSet("labels") {
  798. daemon.configStore.Labels = config.Labels
  799. }
  800. if config.IsValueSet("debug") {
  801. daemon.configStore.Debug = config.Debug
  802. }
  803. if config.IsValueSet("live-restore") {
  804. daemon.configStore.LiveRestoreEnabled = config.LiveRestoreEnabled
  805. if err := daemon.containerdRemote.UpdateOptions(libcontainerd.WithLiveRestore(config.LiveRestoreEnabled)); err != nil {
  806. return err
  807. }
  808. }
  809. // If no value is set for max-concurrent-downloads we assume it is the default value
  810. // We always "reset" as the cost is lightweight and easy to maintain.
  811. if config.IsValueSet("max-concurrent-downloads") && config.MaxConcurrentDownloads != nil {
  812. *daemon.configStore.MaxConcurrentDownloads = *config.MaxConcurrentDownloads
  813. } else {
  814. maxConcurrentDownloads := defaultMaxConcurrentDownloads
  815. daemon.configStore.MaxConcurrentDownloads = &maxConcurrentDownloads
  816. }
  817. logrus.Debugf("Reset Max Concurrent Downloads: %d", *daemon.configStore.MaxConcurrentDownloads)
  818. if daemon.downloadManager != nil {
  819. daemon.downloadManager.SetConcurrency(*daemon.configStore.MaxConcurrentDownloads)
  820. }
  821. // If no value is set for max-concurrent-upload we assume it is the default value
  822. // We always "reset" as the cost is lightweight and easy to maintain.
  823. if config.IsValueSet("max-concurrent-uploads") && config.MaxConcurrentUploads != nil {
  824. *daemon.configStore.MaxConcurrentUploads = *config.MaxConcurrentUploads
  825. } else {
  826. maxConcurrentUploads := defaultMaxConcurrentUploads
  827. daemon.configStore.MaxConcurrentUploads = &maxConcurrentUploads
  828. }
  829. logrus.Debugf("Reset Max Concurrent Uploads: %d", *daemon.configStore.MaxConcurrentUploads)
  830. if daemon.uploadManager != nil {
  831. daemon.uploadManager.SetConcurrency(*daemon.configStore.MaxConcurrentUploads)
  832. }
  833. // We emit daemon reload event here with updatable configurations
  834. attributes["debug"] = fmt.Sprintf("%t", daemon.configStore.Debug)
  835. attributes["live-restore"] = fmt.Sprintf("%t", daemon.configStore.LiveRestoreEnabled)
  836. attributes["cluster-store"] = daemon.configStore.ClusterStore
  837. if daemon.configStore.ClusterOpts != nil {
  838. opts, _ := json.Marshal(daemon.configStore.ClusterOpts)
  839. attributes["cluster-store-opts"] = string(opts)
  840. } else {
  841. attributes["cluster-store-opts"] = "{}"
  842. }
  843. attributes["cluster-advertise"] = daemon.configStore.ClusterAdvertise
  844. if daemon.configStore.Labels != nil {
  845. labels, _ := json.Marshal(daemon.configStore.Labels)
  846. attributes["labels"] = string(labels)
  847. } else {
  848. attributes["labels"] = "[]"
  849. }
  850. attributes["max-concurrent-downloads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentDownloads)
  851. attributes["max-concurrent-uploads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentUploads)
  852. return nil
  853. }
  854. func (daemon *Daemon) reloadClusterDiscovery(config *Config) error {
  855. var err error
  856. newAdvertise := daemon.configStore.ClusterAdvertise
  857. newClusterStore := daemon.configStore.ClusterStore
  858. if config.IsValueSet("cluster-advertise") {
  859. if config.IsValueSet("cluster-store") {
  860. newClusterStore = config.ClusterStore
  861. }
  862. newAdvertise, err = parseClusterAdvertiseSettings(newClusterStore, config.ClusterAdvertise)
  863. if err != nil && err != errDiscoveryDisabled {
  864. return err
  865. }
  866. }
  867. if daemon.clusterProvider != nil {
  868. if err := config.isSwarmCompatible(); err != nil {
  869. return err
  870. }
  871. }
  872. // check discovery modifications
  873. if !modifiedDiscoverySettings(daemon.configStore, newAdvertise, newClusterStore, config.ClusterOpts) {
  874. return nil
  875. }
  876. // enable discovery for the first time if it was not previously enabled
  877. if daemon.discoveryWatcher == nil {
  878. discoveryWatcher, err := initDiscovery(newClusterStore, newAdvertise, config.ClusterOpts)
  879. if err != nil {
  880. return fmt.Errorf("discovery initialization failed (%v)", err)
  881. }
  882. daemon.discoveryWatcher = discoveryWatcher
  883. } else {
  884. if err == errDiscoveryDisabled {
  885. // disable discovery if it was previously enabled and it's disabled now
  886. daemon.discoveryWatcher.Stop()
  887. } else {
  888. // reload discovery
  889. if err = daemon.discoveryWatcher.Reload(config.ClusterStore, newAdvertise, config.ClusterOpts); err != nil {
  890. return err
  891. }
  892. }
  893. }
  894. daemon.configStore.ClusterStore = newClusterStore
  895. daemon.configStore.ClusterOpts = config.ClusterOpts
  896. daemon.configStore.ClusterAdvertise = newAdvertise
  897. if daemon.netController == nil {
  898. return nil
  899. }
  900. netOptions, err := daemon.networkOptions(daemon.configStore, nil)
  901. if err != nil {
  902. logrus.Warnf("Failed to reload configuration with network controller: %v", err)
  903. return nil
  904. }
  905. err = daemon.netController.ReloadConfiguration(netOptions...)
  906. if err != nil {
  907. logrus.Warnf("Failed to reload configuration with network controller: %v", err)
  908. }
  909. return nil
  910. }
  911. func isBridgeNetworkDisabled(config *Config) bool {
  912. return config.bridgeConfig.Iface == disableNetworkBridge
  913. }
  914. func (daemon *Daemon) networkOptions(dconfig *Config, activeSandboxes map[string]interface{}) ([]nwconfig.Option, error) {
  915. options := []nwconfig.Option{}
  916. if dconfig == nil {
  917. return options, nil
  918. }
  919. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  920. options = append(options, nwconfig.OptionExecRoot(dconfig.GetExecRoot()))
  921. dd := runconfig.DefaultDaemonNetworkMode()
  922. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  923. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  924. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  925. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  926. kv := strings.Split(dconfig.ClusterStore, "://")
  927. if len(kv) != 2 {
  928. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  929. }
  930. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  931. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  932. }
  933. if len(dconfig.ClusterOpts) > 0 {
  934. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  935. }
  936. if daemon.discoveryWatcher != nil {
  937. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  938. }
  939. if dconfig.ClusterAdvertise != "" {
  940. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  941. }
  942. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  943. options = append(options, driverOptions(dconfig)...)
  944. if daemon.configStore != nil && daemon.configStore.LiveRestoreEnabled && len(activeSandboxes) != 0 {
  945. options = append(options, nwconfig.OptionActiveSandboxes(activeSandboxes))
  946. }
  947. return options, nil
  948. }
  949. func copyBlkioEntry(entries []*containerd.BlkioStatsEntry) []types.BlkioStatEntry {
  950. out := make([]types.BlkioStatEntry, len(entries))
  951. for i, re := range entries {
  952. out[i] = types.BlkioStatEntry{
  953. Major: re.Major,
  954. Minor: re.Minor,
  955. Op: re.Op,
  956. Value: re.Value,
  957. }
  958. }
  959. return out
  960. }