overlay.go 21 KB

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