overlay.go 21 KB

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