overlay.go 21 KB

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