overlay.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. // +build linux
  2. package overlay2
  3. import (
  4. "bufio"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "github.com/docker/docker/daemon/graphdriver"
  17. "github.com/docker/docker/daemon/graphdriver/overlayutils"
  18. "github.com/docker/docker/daemon/graphdriver/quota"
  19. "github.com/docker/docker/pkg/archive"
  20. "github.com/docker/docker/pkg/chrootarchive"
  21. "github.com/docker/docker/pkg/containerfs"
  22. "github.com/docker/docker/pkg/directory"
  23. "github.com/docker/docker/pkg/fsutils"
  24. "github.com/docker/docker/pkg/idtools"
  25. "github.com/docker/docker/pkg/locker"
  26. "github.com/docker/docker/pkg/mount"
  27. "github.com/docker/docker/pkg/parsers"
  28. "github.com/docker/docker/pkg/parsers/kernel"
  29. "github.com/docker/docker/pkg/system"
  30. "github.com/docker/go-units"
  31. rsystem "github.com/opencontainers/runc/libcontainer/system"
  32. "github.com/opencontainers/selinux/go-selinux/label"
  33. "github.com/sirupsen/logrus"
  34. "golang.org/x/sys/unix"
  35. )
  36. var (
  37. // untar defines the untar method
  38. untar = chrootarchive.UntarUncompressed
  39. )
  40. // This backend uses the overlay union filesystem for containers
  41. // with diff directories for each layer.
  42. // This version of the overlay driver requires at least kernel
  43. // 4.0.0 in order to support mounting multiple diff directories.
  44. // Each container/image has at least a "diff" directory and "link" file.
  45. // If there is also a "lower" file when there are diff layers
  46. // below as well as "merged" and "work" directories. The "diff" directory
  47. // has the upper layer of the overlay and is used to capture any
  48. // changes to the layer. The "lower" file contains all the lower layer
  49. // mounts separated by ":" and ordered from uppermost to lowermost
  50. // layers. The overlay itself is mounted in the "merged" directory,
  51. // and the "work" dir is needed for overlay to work.
  52. // The "link" file for each layer contains a unique string for the layer.
  53. // Under the "l" directory at the root there will be a symbolic link
  54. // with that unique string pointing the "diff" directory for the layer.
  55. // The symbolic links are used to reference lower layers in the "lower"
  56. // file and on mount. The links are used to shorten the total length
  57. // of a layer reference without requiring changes to the layer identifier
  58. // or root directory. Mounts are always done relative to root and
  59. // referencing the symbolic links in order to ensure the number of
  60. // lower directories can fit in a single page for making the mount
  61. // syscall. A hard upper limit of 128 lower layers is enforced to ensure
  62. // that mounts do not fail due to length.
  63. const (
  64. driverName = "overlay2"
  65. linkDir = "l"
  66. lowerFile = "lower"
  67. maxDepth = 128
  68. // idLength represents the number of random characters
  69. // which can be used to create the unique link identifier
  70. // for every layer. If this value is too long then the
  71. // page size limit for the mount command may be exceeded.
  72. // The idLength should be selected such that following equation
  73. // is true (512 is a buffer for label metadata).
  74. // ((idLength + len(linkDir) + 1) * maxDepth) <= (pageSize - 512)
  75. idLength = 26
  76. )
  77. type overlayOptions struct {
  78. overrideKernelCheck bool
  79. quota quota.Quota
  80. }
  81. // Driver contains information about the home directory and the list of active
  82. // mounts that are created using this driver.
  83. type Driver struct {
  84. home string
  85. uidMaps []idtools.IDMap
  86. gidMaps []idtools.IDMap
  87. ctr *graphdriver.RefCounter
  88. quotaCtl *quota.Control
  89. options overlayOptions
  90. naiveDiff graphdriver.DiffDriver
  91. supportsDType bool
  92. locker *locker.Locker
  93. }
  94. var (
  95. backingFs = "<unknown>"
  96. projectQuotaSupported = false
  97. useNaiveDiffLock sync.Once
  98. useNaiveDiffOnly bool
  99. )
  100. func init() {
  101. graphdriver.Register(driverName, Init)
  102. }
  103. // Init returns the native diff driver for overlay filesystem.
  104. // If overlay filesystem is not supported on the host, the error
  105. // graphdriver.ErrNotSupported is returned.
  106. // If an overlay filesystem is not supported over an existing filesystem then
  107. // the error graphdriver.ErrIncompatibleFS is returned.
  108. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  109. opts, err := parseOptions(options)
  110. if err != nil {
  111. return nil, err
  112. }
  113. if err := supportsOverlay(); err != nil {
  114. return nil, graphdriver.ErrNotSupported
  115. }
  116. // require kernel 4.0.0 to ensure multiple lower dirs are supported
  117. v, err := kernel.GetKernelVersion()
  118. if err != nil {
  119. return nil, err
  120. }
  121. // Perform feature detection on /var/lib/docker/overlay2 if it's an existing directory.
  122. // This covers situations where /var/lib/docker/overlay2 is a mount, and on a different
  123. // filesystem than /var/lib/docker.
  124. // If the path does not exist, fall back to using /var/lib/docker for feature detection.
  125. testdir := home
  126. if _, err := os.Stat(testdir); os.IsNotExist(err) {
  127. testdir = filepath.Dir(testdir)
  128. }
  129. fsMagic, err := graphdriver.GetFSMagic(testdir)
  130. if err != nil {
  131. return nil, err
  132. }
  133. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  134. backingFs = fsName
  135. }
  136. switch fsMagic {
  137. case graphdriver.FsMagicAufs, graphdriver.FsMagicEcryptfs, graphdriver.FsMagicNfsFs, graphdriver.FsMagicOverlay, graphdriver.FsMagicZfs:
  138. logrus.Errorf("'overlay2' is not supported over %s", backingFs)
  139. return nil, graphdriver.ErrIncompatibleFS
  140. case graphdriver.FsMagicBtrfs:
  141. // Support for OverlayFS on BTRFS was added in kernel 4.7
  142. // See https://btrfs.wiki.kernel.org/index.php/Changelog
  143. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 7, Minor: 0}) < 0 {
  144. if !opts.overrideKernelCheck {
  145. logrus.Errorf("'overlay2' requires kernel 4.7 to use on %s", backingFs)
  146. return nil, graphdriver.ErrIncompatibleFS
  147. }
  148. logrus.Warn("Using pre-4.7.0 kernel for overlay2 on btrfs, may require kernel update")
  149. }
  150. }
  151. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 0, Minor: 0}) < 0 {
  152. if opts.overrideKernelCheck {
  153. logrus.Warn("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update")
  154. } else {
  155. if err := supportsMultipleLowerDir(testdir); err != nil {
  156. logrus.Debugf("Multiple lower dirs not supported: %v", err)
  157. return nil, graphdriver.ErrNotSupported
  158. }
  159. }
  160. }
  161. supportsDType, err := fsutils.SupportsDType(testdir)
  162. if err != nil {
  163. return nil, err
  164. }
  165. if !supportsDType {
  166. if !graphdriver.IsInitialized(home) {
  167. return nil, overlayutils.ErrDTypeNotSupported("overlay2", backingFs)
  168. }
  169. // allow running without d_type only for existing setups (#27443)
  170. logrus.Warn(overlayutils.ErrDTypeNotSupported("overlay2", backingFs))
  171. }
  172. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  173. if err != nil {
  174. return nil, err
  175. }
  176. // Create the driver home dir
  177. if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, idtools.IDPair{rootUID, rootGID}); err != nil {
  178. return nil, err
  179. }
  180. if err := mount.MakePrivate(home); err != nil {
  181. return nil, err
  182. }
  183. d := &Driver{
  184. home: home,
  185. uidMaps: uidMaps,
  186. gidMaps: gidMaps,
  187. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  188. supportsDType: supportsDType,
  189. locker: locker.New(),
  190. options: *opts,
  191. }
  192. d.naiveDiff = graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps)
  193. if backingFs == "xfs" {
  194. // Try to enable project quota support over xfs.
  195. if d.quotaCtl, err = quota.NewControl(home); err == nil {
  196. projectQuotaSupported = true
  197. } else if opts.quota.Size > 0 {
  198. return nil, fmt.Errorf("Storage option overlay2.size not supported. Filesystem does not support Project Quota: %v", err)
  199. }
  200. } else if opts.quota.Size > 0 {
  201. // if xfs is not the backing fs then error out if the storage-opt overlay2.size is used.
  202. return nil, fmt.Errorf("Storage Option overlay2.size only supported for backingFS XFS. Found %v", backingFs)
  203. }
  204. logrus.Debugf("backingFs=%s, projectQuotaSupported=%v", backingFs, projectQuotaSupported)
  205. return d, nil
  206. }
  207. func parseOptions(options []string) (*overlayOptions, error) {
  208. o := &overlayOptions{}
  209. for _, option := range options {
  210. key, val, err := parsers.ParseKeyValueOpt(option)
  211. if err != nil {
  212. return nil, err
  213. }
  214. key = strings.ToLower(key)
  215. switch key {
  216. case "overlay2.override_kernel_check":
  217. o.overrideKernelCheck, err = strconv.ParseBool(val)
  218. if err != nil {
  219. return nil, err
  220. }
  221. case "overlay2.size":
  222. size, err := units.RAMInBytes(val)
  223. if err != nil {
  224. return nil, err
  225. }
  226. o.quota.Size = uint64(size)
  227. default:
  228. return nil, fmt.Errorf("overlay2: unknown option %s", key)
  229. }
  230. }
  231. return o, nil
  232. }
  233. func supportsOverlay() error {
  234. // We can try to modprobe overlay first before looking at
  235. // proc/filesystems for when overlay is supported
  236. exec.Command("modprobe", "overlay").Run()
  237. f, err := os.Open("/proc/filesystems")
  238. if err != nil {
  239. return err
  240. }
  241. defer f.Close()
  242. s := bufio.NewScanner(f)
  243. for s.Scan() {
  244. if s.Text() == "nodev\toverlay" {
  245. return nil
  246. }
  247. }
  248. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  249. return graphdriver.ErrNotSupported
  250. }
  251. func useNaiveDiff(home string) bool {
  252. useNaiveDiffLock.Do(func() {
  253. if err := doesSupportNativeDiff(home); err != nil {
  254. logrus.Warnf("Not using native diff for overlay2, this may cause degraded performance for building images: %v", err)
  255. useNaiveDiffOnly = true
  256. }
  257. })
  258. return useNaiveDiffOnly
  259. }
  260. func (d *Driver) String() string {
  261. return driverName
  262. }
  263. // Status returns current driver information in a two dimensional string array.
  264. // Output contains "Backing Filesystem" used in this implementation.
  265. func (d *Driver) Status() [][2]string {
  266. return [][2]string{
  267. {"Backing Filesystem", backingFs},
  268. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  269. {"Native Overlay Diff", strconv.FormatBool(!useNaiveDiff(d.home))},
  270. }
  271. }
  272. // GetMetadata returns metadata about the overlay driver such as the LowerDir,
  273. // UpperDir, WorkDir, and MergeDir used to store data.
  274. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  275. dir := d.dir(id)
  276. if _, err := os.Stat(dir); err != nil {
  277. return nil, err
  278. }
  279. metadata := map[string]string{
  280. "WorkDir": path.Join(dir, "work"),
  281. "MergedDir": path.Join(dir, "merged"),
  282. "UpperDir": path.Join(dir, "diff"),
  283. }
  284. lowerDirs, err := d.getLowerDirs(id)
  285. if err != nil {
  286. return nil, err
  287. }
  288. if len(lowerDirs) > 0 {
  289. metadata["LowerDir"] = strings.Join(lowerDirs, ":")
  290. }
  291. return metadata, nil
  292. }
  293. // Cleanup any state created by overlay which should be cleaned when daemon
  294. // is being shutdown. For now, we just have to unmount the bind mounted
  295. // we had created.
  296. func (d *Driver) Cleanup() error {
  297. return mount.Unmount(d.home)
  298. }
  299. // CreateReadWrite creates a layer that is writable for use as a container
  300. // file system.
  301. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  302. if opts != nil && len(opts.StorageOpt) != 0 && !projectQuotaSupported {
  303. return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option")
  304. }
  305. if opts == nil {
  306. opts = &graphdriver.CreateOpts{
  307. StorageOpt: map[string]string{},
  308. }
  309. }
  310. if _, ok := opts.StorageOpt["size"]; !ok {
  311. if opts.StorageOpt == nil {
  312. opts.StorageOpt = map[string]string{}
  313. }
  314. opts.StorageOpt["size"] = strconv.FormatUint(d.options.quota.Size, 10)
  315. }
  316. return d.create(id, parent, opts)
  317. }
  318. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  319. // The parent filesystem is used to configure these directories for the overlay.
  320. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  321. if opts != nil && len(opts.StorageOpt) != 0 {
  322. if _, ok := opts.StorageOpt["size"]; ok {
  323. return fmt.Errorf("--storage-opt size is only supported for ReadWrite Layers")
  324. }
  325. }
  326. return d.create(id, parent, opts)
  327. }
  328. func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  329. dir := d.dir(id)
  330. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  331. if err != nil {
  332. return err
  333. }
  334. root := idtools.IDPair{UID: rootUID, GID: rootGID}
  335. if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
  336. return err
  337. }
  338. if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
  339. return err
  340. }
  341. defer func() {
  342. // Clean up on failure
  343. if retErr != nil {
  344. os.RemoveAll(dir)
  345. }
  346. }()
  347. if opts != nil && len(opts.StorageOpt) > 0 {
  348. driver := &Driver{}
  349. if err := d.parseStorageOpt(opts.StorageOpt, driver); err != nil {
  350. return err
  351. }
  352. if driver.options.quota.Size > 0 {
  353. // Set container disk quota limit
  354. if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil {
  355. return err
  356. }
  357. }
  358. }
  359. if err := idtools.MkdirAndChown(path.Join(dir, "diff"), 0755, root); err != nil {
  360. return err
  361. }
  362. lid := generateID(idLength)
  363. if err := os.Symlink(path.Join("..", id, "diff"), path.Join(d.home, linkDir, lid)); err != nil {
  364. return err
  365. }
  366. // Write link id to link file
  367. if err := ioutil.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
  368. return err
  369. }
  370. // if no parent directory, done
  371. if parent == "" {
  372. return nil
  373. }
  374. if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
  375. return err
  376. }
  377. lower, err := d.getLower(parent)
  378. if err != nil {
  379. return err
  380. }
  381. if lower != "" {
  382. if err := ioutil.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
  383. return err
  384. }
  385. }
  386. return nil
  387. }
  388. // Parse overlay storage options
  389. func (d *Driver) parseStorageOpt(storageOpt map[string]string, driver *Driver) error {
  390. // Read size to set the disk project quota per container
  391. for key, val := range storageOpt {
  392. key := strings.ToLower(key)
  393. switch key {
  394. case "size":
  395. size, err := units.RAMInBytes(val)
  396. if err != nil {
  397. return err
  398. }
  399. driver.options.quota.Size = uint64(size)
  400. default:
  401. return fmt.Errorf("Unknown option %s", key)
  402. }
  403. }
  404. return nil
  405. }
  406. func (d *Driver) getLower(parent string) (string, error) {
  407. parentDir := d.dir(parent)
  408. // Ensure parent exists
  409. if _, err := os.Lstat(parentDir); err != nil {
  410. return "", err
  411. }
  412. // Read Parent link fileA
  413. parentLink, err := ioutil.ReadFile(path.Join(parentDir, "link"))
  414. if err != nil {
  415. return "", err
  416. }
  417. lowers := []string{path.Join(linkDir, string(parentLink))}
  418. parentLower, err := ioutil.ReadFile(path.Join(parentDir, lowerFile))
  419. if err == nil {
  420. parentLowers := strings.Split(string(parentLower), ":")
  421. lowers = append(lowers, parentLowers...)
  422. }
  423. if len(lowers) > maxDepth {
  424. return "", errors.New("max depth exceeded")
  425. }
  426. return strings.Join(lowers, ":"), nil
  427. }
  428. func (d *Driver) dir(id string) string {
  429. return path.Join(d.home, id)
  430. }
  431. func (d *Driver) getLowerDirs(id string) ([]string, error) {
  432. var lowersArray []string
  433. lowers, err := ioutil.ReadFile(path.Join(d.dir(id), lowerFile))
  434. if err == nil {
  435. for _, s := range strings.Split(string(lowers), ":") {
  436. lp, err := os.Readlink(path.Join(d.home, s))
  437. if err != nil {
  438. return nil, err
  439. }
  440. lowersArray = append(lowersArray, path.Clean(path.Join(d.home, linkDir, lp)))
  441. }
  442. } else if !os.IsNotExist(err) {
  443. return nil, err
  444. }
  445. return lowersArray, nil
  446. }
  447. // Remove cleans the directories that are created for this id.
  448. func (d *Driver) Remove(id string) error {
  449. d.locker.Lock(id)
  450. defer d.locker.Unlock(id)
  451. dir := d.dir(id)
  452. lid, err := ioutil.ReadFile(path.Join(dir, "link"))
  453. if err == nil {
  454. if err := os.RemoveAll(path.Join(d.home, linkDir, string(lid))); err != nil {
  455. logrus.Debugf("Failed to remove link: %v", err)
  456. }
  457. }
  458. if err := system.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
  459. return err
  460. }
  461. return nil
  462. }
  463. // Get creates and mounts the required file system for the given id and returns the mount path.
  464. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
  465. d.locker.Lock(id)
  466. defer d.locker.Unlock(id)
  467. dir := d.dir(id)
  468. if _, err := os.Stat(dir); err != nil {
  469. return nil, err
  470. }
  471. diffDir := path.Join(dir, "diff")
  472. lowers, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  473. if err != nil {
  474. // If no lower, just return diff directory
  475. if os.IsNotExist(err) {
  476. return containerfs.NewLocalContainerFS(diffDir), nil
  477. }
  478. return nil, err
  479. }
  480. mergedDir := path.Join(dir, "merged")
  481. if count := d.ctr.Increment(mergedDir); count > 1 {
  482. return containerfs.NewLocalContainerFS(mergedDir), nil
  483. }
  484. defer func() {
  485. if retErr != nil {
  486. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  487. if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil {
  488. logrus.Errorf("error unmounting %v: %v", mergedDir, mntErr)
  489. }
  490. // Cleanup the created merged directory; see the comment in Put's rmdir
  491. if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
  492. logrus.Debugf("Failed to remove %s: %v: %v", id, rmErr, err)
  493. }
  494. }
  495. }
  496. }()
  497. workDir := path.Join(dir, "work")
  498. splitLowers := strings.Split(string(lowers), ":")
  499. absLowers := make([]string, len(splitLowers))
  500. for i, s := range splitLowers {
  501. absLowers[i] = path.Join(d.home, s)
  502. }
  503. opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", strings.Join(absLowers, ":"), path.Join(dir, "diff"), path.Join(dir, "work"))
  504. mountData := label.FormatMountLabel(opts, mountLabel)
  505. mount := unix.Mount
  506. mountTarget := mergedDir
  507. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  508. if err != nil {
  509. return nil, err
  510. }
  511. if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.IDPair{rootUID, rootGID}); err != nil {
  512. return nil, err
  513. }
  514. pageSize := unix.Getpagesize()
  515. // Go can return a larger page size than supported by the system
  516. // as of go 1.7. This will be fixed in 1.8 and this block can be
  517. // removed when building with 1.8.
  518. // See https://github.com/golang/go/commit/1b9499b06989d2831e5b156161d6c07642926ee1
  519. // See https://github.com/docker/docker/issues/27384
  520. if pageSize > 4096 {
  521. pageSize = 4096
  522. }
  523. // Use relative paths and mountFrom when the mount data has exceeded
  524. // the page size. The mount syscall fails if the mount data cannot
  525. // fit within a page and relative links make the mount data much
  526. // smaller at the expense of requiring a fork exec to chroot.
  527. if len(mountData) > pageSize {
  528. opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", string(lowers), path.Join(id, "diff"), path.Join(id, "work"))
  529. mountData = label.FormatMountLabel(opts, mountLabel)
  530. if len(mountData) > pageSize {
  531. return nil, fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData))
  532. }
  533. mount = func(source string, target string, mType string, flags uintptr, label string) error {
  534. return mountFrom(d.home, source, target, mType, flags, label)
  535. }
  536. mountTarget = path.Join(id, "merged")
  537. }
  538. if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil {
  539. return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  540. }
  541. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  542. // user namespace requires this to move a directory from lower to upper.
  543. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  544. return nil, err
  545. }
  546. return containerfs.NewLocalContainerFS(mergedDir), nil
  547. }
  548. // Put unmounts the mount path created for the give id.
  549. // It also removes the 'merged' directory to force the kernel to unmount the
  550. // overlay mount in other namespaces.
  551. func (d *Driver) Put(id string) error {
  552. d.locker.Lock(id)
  553. defer d.locker.Unlock(id)
  554. dir := d.dir(id)
  555. _, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  556. if err != nil {
  557. // If no lower, no mount happened and just return directly
  558. if os.IsNotExist(err) {
  559. return nil
  560. }
  561. return err
  562. }
  563. mountpoint := path.Join(dir, "merged")
  564. if count := d.ctr.Decrement(mountpoint); count > 0 {
  565. return nil
  566. }
  567. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  568. logrus.Debugf("Failed to unmount %s overlay: %s - %v", id, mountpoint, err)
  569. }
  570. // Remove the mountpoint here. Removing the mountpoint (in newer kernels)
  571. // will cause all other instances of this mount in other mount namespaces
  572. // to be unmounted. This is necessary to avoid cases where an overlay mount
  573. // that is present in another namespace will cause subsequent mounts
  574. // operations to fail with ebusy. We ignore any errors here because this may
  575. // fail on older kernels which don't have
  576. // torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied.
  577. if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) {
  578. logrus.Debugf("Failed to remove %s overlay: %v", id, err)
  579. }
  580. return nil
  581. }
  582. // Exists checks to see if the id is already mounted.
  583. func (d *Driver) Exists(id string) bool {
  584. _, err := os.Stat(d.dir(id))
  585. return err == nil
  586. }
  587. // isParent determines whether the given parent is the direct parent of the
  588. // given layer id
  589. func (d *Driver) isParent(id, parent string) bool {
  590. lowers, err := d.getLowerDirs(id)
  591. if err != nil {
  592. return false
  593. }
  594. if parent == "" && len(lowers) > 0 {
  595. return false
  596. }
  597. parentDir := d.dir(parent)
  598. var ld string
  599. if len(lowers) > 0 {
  600. ld = filepath.Dir(lowers[0])
  601. }
  602. if ld == "" && parent == "" {
  603. return true
  604. }
  605. return ld == parentDir
  606. }
  607. // ApplyDiff applies the new layer into a root
  608. func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
  609. if !d.isParent(id, parent) {
  610. return d.naiveDiff.ApplyDiff(id, parent, diff)
  611. }
  612. applyDir := d.getDiffPath(id)
  613. logrus.Debugf("Applying tar in %s", applyDir)
  614. // Overlay doesn't need the parent id to apply the diff
  615. if err := untar(diff, applyDir, &archive.TarOptions{
  616. UIDMaps: d.uidMaps,
  617. GIDMaps: d.gidMaps,
  618. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  619. InUserNS: rsystem.RunningInUserNS(),
  620. }); err != nil {
  621. return 0, err
  622. }
  623. return directory.Size(applyDir)
  624. }
  625. func (d *Driver) getDiffPath(id string) string {
  626. dir := d.dir(id)
  627. return path.Join(dir, "diff")
  628. }
  629. // DiffSize calculates the changes between the specified id
  630. // and its parent and returns the size in bytes of the changes
  631. // relative to its base filesystem directory.
  632. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  633. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  634. return d.naiveDiff.DiffSize(id, parent)
  635. }
  636. return directory.Size(d.getDiffPath(id))
  637. }
  638. // Diff produces an archive of the changes between the specified
  639. // layer and its parent layer which may be "".
  640. func (d *Driver) Diff(id, parent string) (io.ReadCloser, error) {
  641. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  642. return d.naiveDiff.Diff(id, parent)
  643. }
  644. diffPath := d.getDiffPath(id)
  645. logrus.Debugf("Tar with options on %s", diffPath)
  646. return archive.TarWithOptions(diffPath, &archive.TarOptions{
  647. Compression: archive.Uncompressed,
  648. UIDMaps: d.uidMaps,
  649. GIDMaps: d.gidMaps,
  650. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  651. })
  652. }
  653. // Changes produces a list of changes between the specified layer and its
  654. // parent layer. If parent is "", then all changes will be ADD changes.
  655. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  656. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  657. return d.naiveDiff.Changes(id, parent)
  658. }
  659. // Overlay doesn't have snapshots, so we need to get changes from all parent
  660. // layers.
  661. diffPath := d.getDiffPath(id)
  662. layers, err := d.getLowerDirs(id)
  663. if err != nil {
  664. return nil, err
  665. }
  666. return archive.OverlayChanges(layers, diffPath)
  667. }