overlay.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. // +build linux
  2. package overlay2 // import "github.com/docker/docker/daemon/graphdriver/overlay2"
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "github.com/docker/docker/daemon/graphdriver"
  16. "github.com/docker/docker/daemon/graphdriver/overlayutils"
  17. "github.com/docker/docker/pkg/archive"
  18. "github.com/docker/docker/pkg/chrootarchive"
  19. "github.com/docker/docker/pkg/containerfs"
  20. "github.com/docker/docker/pkg/directory"
  21. "github.com/docker/docker/pkg/fsutils"
  22. "github.com/docker/docker/pkg/idtools"
  23. "github.com/docker/docker/pkg/parsers"
  24. "github.com/docker/docker/pkg/system"
  25. "github.com/docker/docker/quota"
  26. units "github.com/docker/go-units"
  27. "github.com/moby/locker"
  28. "github.com/moby/sys/mount"
  29. "github.com/opencontainers/selinux/go-selinux/label"
  30. "github.com/sirupsen/logrus"
  31. "golang.org/x/sys/unix"
  32. )
  33. var (
  34. // untar defines the untar method
  35. untar = chrootarchive.UntarUncompressed
  36. )
  37. // This backend uses the overlay union filesystem for containers
  38. // with diff directories for each layer.
  39. // This version of the overlay driver requires at least kernel
  40. // 4.0.0 in order to support mounting multiple diff directories.
  41. // Each container/image has at least a "diff" directory and "link" file.
  42. // If there is also a "lower" file when there are diff layers
  43. // below as well as "merged" and "work" directories. The "diff" directory
  44. // has the upper layer of the overlay and is used to capture any
  45. // changes to the layer. The "lower" file contains all the lower layer
  46. // mounts separated by ":" and ordered from uppermost to lowermost
  47. // layers. The overlay itself is mounted in the "merged" directory,
  48. // and the "work" dir is needed for overlay to work.
  49. // The "link" file for each layer contains a unique string for the layer.
  50. // Under the "l" directory at the root there will be a symbolic link
  51. // with that unique string pointing the "diff" directory for the layer.
  52. // The symbolic links are used to reference lower layers in the "lower"
  53. // file and on mount. The links are used to shorten the total length
  54. // of a layer reference without requiring changes to the layer identifier
  55. // or root directory. Mounts are always done relative to root and
  56. // referencing the symbolic links in order to ensure the number of
  57. // lower directories can fit in a single page for making the mount
  58. // syscall. A hard upper limit of 128 lower layers is enforced to ensure
  59. // that mounts do not fail due to length.
  60. const (
  61. driverName = "overlay2"
  62. linkDir = "l"
  63. diffDirName = "diff"
  64. workDirName = "work"
  65. mergedDirName = "merged"
  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. logger = logrus.WithField("storage-driver", "overlay2")
  96. backingFs = "<unknown>"
  97. projectQuotaSupported = false
  98. useNaiveDiffLock sync.Once
  99. useNaiveDiffOnly bool
  100. indexOff string
  101. userxattr string
  102. )
  103. func init() {
  104. graphdriver.Register(driverName, Init)
  105. }
  106. // Init returns the native diff driver for overlay filesystem.
  107. // If overlay filesystem is not supported on the host, the error
  108. // graphdriver.ErrNotSupported is returned.
  109. // If an overlay filesystem is not supported over an existing filesystem then
  110. // the error graphdriver.ErrIncompatibleFS is returned.
  111. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  112. opts, err := parseOptions(options)
  113. if err != nil {
  114. return nil, err
  115. }
  116. // Perform feature detection on /var/lib/docker/overlay2 if it's an existing directory.
  117. // This covers situations where /var/lib/docker/overlay2 is a mount, and on a different
  118. // filesystem than /var/lib/docker.
  119. // If the path does not exist, fall back to using /var/lib/docker for feature detection.
  120. testdir := home
  121. if _, err := os.Stat(testdir); os.IsNotExist(err) {
  122. testdir = filepath.Dir(testdir)
  123. }
  124. if err := overlayutils.SupportsOverlay(testdir, true); err != nil {
  125. logger.Error(err)
  126. return nil, graphdriver.ErrNotSupported
  127. }
  128. fsMagic, err := graphdriver.GetFSMagic(testdir)
  129. if err != nil {
  130. return nil, err
  131. }
  132. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  133. backingFs = fsName
  134. }
  135. supportsDType, err := fsutils.SupportsDType(testdir)
  136. if err != nil {
  137. return nil, err
  138. }
  139. if !supportsDType {
  140. if !graphdriver.IsInitialized(home) {
  141. return nil, overlayutils.ErrDTypeNotSupported("overlay2", backingFs)
  142. }
  143. // allow running without d_type only for existing setups (#27443)
  144. logger.Warn(overlayutils.ErrDTypeNotSupported("overlay2", backingFs))
  145. }
  146. _, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  147. if err != nil {
  148. return nil, err
  149. }
  150. cur := idtools.CurrentIdentity()
  151. dirID := idtools.Identity{
  152. UID: cur.UID,
  153. GID: rootGID,
  154. }
  155. if err := idtools.MkdirAllAndChown(home, 0710, dirID); err != nil {
  156. return nil, err
  157. }
  158. if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, cur); err != nil {
  159. return nil, err
  160. }
  161. d := &Driver{
  162. home: home,
  163. uidMaps: uidMaps,
  164. gidMaps: gidMaps,
  165. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  166. supportsDType: supportsDType,
  167. locker: locker.New(),
  168. options: *opts,
  169. }
  170. d.naiveDiff = graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps)
  171. if backingFs == "xfs" {
  172. // Try to enable project quota support over xfs.
  173. if d.quotaCtl, err = quota.NewControl(home); err == nil {
  174. projectQuotaSupported = true
  175. } else if opts.quota.Size > 0 {
  176. return nil, fmt.Errorf("Storage option overlay2.size not supported. Filesystem does not support Project Quota: %v", err)
  177. }
  178. } else if opts.quota.Size > 0 {
  179. // if xfs is not the backing fs then error out if the storage-opt overlay2.size is used.
  180. return nil, fmt.Errorf("Storage Option overlay2.size only supported for backingFS XFS. Found %v", backingFs)
  181. }
  182. // figure out whether "index=off" option is recognized by the kernel
  183. _, err = os.Stat("/sys/module/overlay/parameters/index")
  184. switch {
  185. case err == nil:
  186. indexOff = "index=off,"
  187. case os.IsNotExist(err):
  188. // old kernel, no index -- do nothing
  189. default:
  190. logger.Warnf("Unable to detect whether overlay kernel module supports index parameter: %s", err)
  191. }
  192. needsUserXattr, err := overlayutils.NeedsUserXAttr(home)
  193. if err != nil {
  194. logger.Warnf("Unable to detect whether overlay kernel module needs \"userxattr\" parameter: %s", err)
  195. }
  196. if needsUserXattr {
  197. userxattr = "userxattr,"
  198. }
  199. logger.Debugf("backingFs=%s, projectQuotaSupported=%v, indexOff=%q, userxattr=%q",
  200. backingFs, projectQuotaSupported, indexOff, userxattr)
  201. return d, nil
  202. }
  203. func parseOptions(options []string) (*overlayOptions, error) {
  204. o := &overlayOptions{}
  205. for _, option := range options {
  206. key, val, err := parsers.ParseKeyValueOpt(option)
  207. if err != nil {
  208. return nil, err
  209. }
  210. key = strings.ToLower(key)
  211. switch key {
  212. case "overlay2.override_kernel_check":
  213. o.overrideKernelCheck, err = strconv.ParseBool(val)
  214. if err != nil {
  215. return nil, err
  216. }
  217. case "overlay2.size":
  218. size, err := units.RAMInBytes(val)
  219. if err != nil {
  220. return nil, err
  221. }
  222. o.quota.Size = uint64(size)
  223. default:
  224. return nil, fmt.Errorf("overlay2: unknown option %s", key)
  225. }
  226. }
  227. return o, nil
  228. }
  229. func useNaiveDiff(home string) bool {
  230. useNaiveDiffLock.Do(func() {
  231. if err := doesSupportNativeDiff(home); err != nil {
  232. logger.Warnf("Not using native diff for overlay2, this may cause degraded performance for building images: %v", err)
  233. useNaiveDiffOnly = true
  234. }
  235. })
  236. return useNaiveDiffOnly
  237. }
  238. func (d *Driver) String() string {
  239. return driverName
  240. }
  241. // Status returns current driver information in a two dimensional string array.
  242. // Output contains "Backing Filesystem" used in this implementation.
  243. func (d *Driver) Status() [][2]string {
  244. return [][2]string{
  245. {"Backing Filesystem", backingFs},
  246. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  247. {"Native Overlay Diff", strconv.FormatBool(!useNaiveDiff(d.home))},
  248. {"userxattr", strconv.FormatBool(userxattr != "")},
  249. }
  250. }
  251. // GetMetadata returns metadata about the overlay driver such as the LowerDir,
  252. // UpperDir, WorkDir, and MergeDir used to store data.
  253. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  254. dir := d.dir(id)
  255. if _, err := os.Stat(dir); err != nil {
  256. return nil, err
  257. }
  258. metadata := map[string]string{
  259. "WorkDir": path.Join(dir, workDirName),
  260. "MergedDir": path.Join(dir, mergedDirName),
  261. "UpperDir": path.Join(dir, diffDirName),
  262. }
  263. lowerDirs, err := d.getLowerDirs(id)
  264. if err != nil {
  265. return nil, err
  266. }
  267. if len(lowerDirs) > 0 {
  268. metadata["LowerDir"] = strings.Join(lowerDirs, ":")
  269. }
  270. return metadata, nil
  271. }
  272. // Cleanup any state created by overlay which should be cleaned when daemon
  273. // is being shutdown. For now, we just have to unmount the bind mounted
  274. // we had created.
  275. func (d *Driver) Cleanup() error {
  276. return mount.RecursiveUnmount(d.home)
  277. }
  278. // CreateReadWrite creates a layer that is writable for use as a container
  279. // file system.
  280. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  281. if opts == nil {
  282. opts = &graphdriver.CreateOpts{
  283. StorageOpt: make(map[string]string),
  284. }
  285. } else if opts.StorageOpt == nil {
  286. opts.StorageOpt = make(map[string]string)
  287. }
  288. // Merge daemon default config.
  289. if _, ok := opts.StorageOpt["size"]; !ok && d.options.quota.Size != 0 {
  290. opts.StorageOpt["size"] = strconv.FormatUint(d.options.quota.Size, 10)
  291. }
  292. if _, ok := opts.StorageOpt["size"]; ok && !projectQuotaSupported {
  293. return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option")
  294. }
  295. return d.create(id, parent, opts)
  296. }
  297. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  298. // The parent filesystem is used to configure these directories for the overlay.
  299. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  300. if opts != nil && len(opts.StorageOpt) != 0 {
  301. if _, ok := opts.StorageOpt["size"]; ok {
  302. return fmt.Errorf("--storage-opt size is only supported for ReadWrite Layers")
  303. }
  304. }
  305. return d.create(id, parent, opts)
  306. }
  307. func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  308. dir := d.dir(id)
  309. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  310. if err != nil {
  311. return err
  312. }
  313. root := idtools.Identity{UID: rootUID, GID: rootGID}
  314. dirID := idtools.Identity{
  315. UID: idtools.CurrentIdentity().UID,
  316. GID: rootGID,
  317. }
  318. if err := idtools.MkdirAllAndChown(path.Dir(dir), 0710, dirID); err != nil {
  319. return err
  320. }
  321. if err := idtools.MkdirAndChown(dir, 0710, dirID); err != nil {
  322. return err
  323. }
  324. defer func() {
  325. // Clean up on failure
  326. if retErr != nil {
  327. os.RemoveAll(dir)
  328. }
  329. }()
  330. if opts != nil && len(opts.StorageOpt) > 0 {
  331. driver := &Driver{}
  332. if err := d.parseStorageOpt(opts.StorageOpt, driver); err != nil {
  333. return err
  334. }
  335. if driver.options.quota.Size > 0 {
  336. // Set container disk quota limit
  337. if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil {
  338. return err
  339. }
  340. }
  341. }
  342. if err := idtools.MkdirAndChown(path.Join(dir, diffDirName), 0755, root); err != nil {
  343. return err
  344. }
  345. lid := overlayutils.GenerateID(idLength, logger)
  346. if err := os.Symlink(path.Join("..", id, diffDirName), path.Join(d.home, linkDir, lid)); err != nil {
  347. return err
  348. }
  349. // Write link id to link file
  350. if err := ioutil.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
  351. return err
  352. }
  353. // if no parent directory, done
  354. if parent == "" {
  355. return nil
  356. }
  357. if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0700, root); err != nil {
  358. return err
  359. }
  360. if err := ioutil.WriteFile(path.Join(d.dir(parent), "committed"), []byte{}, 0600); err != nil {
  361. return err
  362. }
  363. lower, err := d.getLower(parent)
  364. if err != nil {
  365. return err
  366. }
  367. if lower != "" {
  368. if err := ioutil.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
  369. return err
  370. }
  371. }
  372. return nil
  373. }
  374. // Parse overlay storage options
  375. func (d *Driver) parseStorageOpt(storageOpt map[string]string, driver *Driver) error {
  376. // Read size to set the disk project quota per container
  377. for key, val := range storageOpt {
  378. key := strings.ToLower(key)
  379. switch key {
  380. case "size":
  381. size, err := units.RAMInBytes(val)
  382. if err != nil {
  383. return err
  384. }
  385. driver.options.quota.Size = uint64(size)
  386. default:
  387. return fmt.Errorf("Unknown option %s", key)
  388. }
  389. }
  390. return nil
  391. }
  392. func (d *Driver) getLower(parent string) (string, error) {
  393. parentDir := d.dir(parent)
  394. // Ensure parent exists
  395. if _, err := os.Lstat(parentDir); err != nil {
  396. return "", err
  397. }
  398. // Read Parent link fileA
  399. parentLink, err := ioutil.ReadFile(path.Join(parentDir, "link"))
  400. if err != nil {
  401. return "", err
  402. }
  403. lowers := []string{path.Join(linkDir, string(parentLink))}
  404. parentLower, err := ioutil.ReadFile(path.Join(parentDir, lowerFile))
  405. if err == nil {
  406. parentLowers := strings.Split(string(parentLower), ":")
  407. lowers = append(lowers, parentLowers...)
  408. }
  409. if len(lowers) > maxDepth {
  410. return "", errors.New("max depth exceeded")
  411. }
  412. return strings.Join(lowers, ":"), nil
  413. }
  414. func (d *Driver) dir(id string) string {
  415. return path.Join(d.home, id)
  416. }
  417. func (d *Driver) getLowerDirs(id string) ([]string, error) {
  418. var lowersArray []string
  419. lowers, err := ioutil.ReadFile(path.Join(d.dir(id), lowerFile))
  420. if err == nil {
  421. for _, s := range strings.Split(string(lowers), ":") {
  422. lp, err := os.Readlink(path.Join(d.home, s))
  423. if err != nil {
  424. return nil, err
  425. }
  426. lowersArray = append(lowersArray, path.Clean(path.Join(d.home, linkDir, lp)))
  427. }
  428. } else if !os.IsNotExist(err) {
  429. return nil, err
  430. }
  431. return lowersArray, nil
  432. }
  433. // Remove cleans the directories that are created for this id.
  434. func (d *Driver) Remove(id string) error {
  435. if id == "" {
  436. return fmt.Errorf("refusing to remove the directories: id is empty")
  437. }
  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 len(lid) == 0 {
  444. logger.Errorf("refusing to remove empty link for layer %v", id)
  445. } else if err := os.RemoveAll(path.Join(d.home, linkDir, string(lid))); err != nil {
  446. logger.Debugf("Failed to remove link: %v", err)
  447. }
  448. }
  449. if err := system.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
  450. return err
  451. }
  452. return nil
  453. }
  454. // Get creates and mounts the required file system for the given id and returns the mount path.
  455. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
  456. d.locker.Lock(id)
  457. defer d.locker.Unlock(id)
  458. dir := d.dir(id)
  459. if _, err := os.Stat(dir); err != nil {
  460. return nil, err
  461. }
  462. diffDir := path.Join(dir, diffDirName)
  463. lowers, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  464. if err != nil {
  465. // If no lower, just return diff directory
  466. if os.IsNotExist(err) {
  467. return containerfs.NewLocalContainerFS(diffDir), nil
  468. }
  469. return nil, err
  470. }
  471. mergedDir := path.Join(dir, mergedDirName)
  472. if count := d.ctr.Increment(mergedDir); count > 1 {
  473. return containerfs.NewLocalContainerFS(mergedDir), nil
  474. }
  475. defer func() {
  476. if retErr != nil {
  477. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  478. if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil {
  479. logger.Errorf("error unmounting %v: %v", mergedDir, mntErr)
  480. }
  481. // Cleanup the created merged directory; see the comment in Put's rmdir
  482. if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
  483. logger.Debugf("Failed to remove %s: %v: %v", id, rmErr, err)
  484. }
  485. }
  486. }
  487. }()
  488. workDir := path.Join(dir, workDirName)
  489. splitLowers := strings.Split(string(lowers), ":")
  490. absLowers := make([]string, len(splitLowers))
  491. for i, s := range splitLowers {
  492. absLowers[i] = path.Join(d.home, s)
  493. }
  494. var readonly bool
  495. if _, err := os.Stat(path.Join(dir, "committed")); err == nil {
  496. readonly = true
  497. } else if !os.IsNotExist(err) {
  498. return nil, err
  499. }
  500. var opts string
  501. if readonly {
  502. opts = indexOff + userxattr + "lowerdir=" + diffDir + ":" + strings.Join(absLowers, ":")
  503. } else {
  504. opts = indexOff + userxattr + "lowerdir=" + strings.Join(absLowers, ":") + ",upperdir=" + diffDir + ",workdir=" + workDir
  505. }
  506. mountData := label.FormatMountLabel(opts, mountLabel)
  507. mount := unix.Mount
  508. mountTarget := mergedDir
  509. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  510. if err != nil {
  511. return nil, err
  512. }
  513. if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
  514. return nil, err
  515. }
  516. pageSize := unix.Getpagesize()
  517. // Use relative paths and mountFrom when the mount data has exceeded
  518. // the page size. The mount syscall fails if the mount data cannot
  519. // fit within a page and relative links make the mount data much
  520. // smaller at the expense of requiring a fork exec to chroot.
  521. if len(mountData) > pageSize-1 {
  522. if readonly {
  523. opts = indexOff + userxattr + "lowerdir=" + path.Join(id, diffDirName) + ":" + string(lowers)
  524. } else {
  525. opts = indexOff + userxattr + "lowerdir=" + string(lowers) + ",upperdir=" + path.Join(id, diffDirName) + ",workdir=" + path.Join(id, workDirName)
  526. }
  527. mountData = label.FormatMountLabel(opts, mountLabel)
  528. if len(mountData) > pageSize-1 {
  529. return nil, fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData))
  530. }
  531. mount = func(source string, target string, mType string, flags uintptr, label string) error {
  532. return mountFrom(d.home, source, target, mType, flags, label)
  533. }
  534. mountTarget = path.Join(id, mergedDirName)
  535. }
  536. if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil {
  537. return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  538. }
  539. if !readonly {
  540. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  541. // user namespace requires this to move a directory from lower to upper.
  542. if err := os.Chown(path.Join(workDir, workDirName), rootUID, rootGID); err != nil {
  543. return nil, err
  544. }
  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, mergedDirName)
  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. logger.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. logger.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 useNaiveDiff(d.home) || !d.isParent(id, parent) {
  610. return d.naiveDiff.ApplyDiff(id, parent, diff)
  611. }
  612. // never reach here if we are running in UserNS
  613. applyDir := d.getDiffPath(id)
  614. logger.Debugf("Applying tar in %s", applyDir)
  615. // Overlay doesn't need the parent id to apply the diff
  616. if err := untar(diff, applyDir, &archive.TarOptions{
  617. UIDMaps: d.uidMaps,
  618. GIDMaps: d.gidMaps,
  619. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  620. }); err != nil {
  621. return 0, err
  622. }
  623. return directory.Size(context.TODO(), applyDir)
  624. }
  625. func (d *Driver) getDiffPath(id string) string {
  626. dir := d.dir(id)
  627. return path.Join(dir, diffDirName)
  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(context.TODO(), 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. // never reach here if we are running in UserNS
  645. diffPath := d.getDiffPath(id)
  646. logger.Debugf("Tar with options on %s", diffPath)
  647. return archive.TarWithOptions(diffPath, &archive.TarOptions{
  648. Compression: archive.Uncompressed,
  649. UIDMaps: d.uidMaps,
  650. GIDMaps: d.gidMaps,
  651. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  652. })
  653. }
  654. // Changes produces a list of changes between the specified layer and its
  655. // parent layer. If parent is "", then all changes will be ADD changes.
  656. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  657. return d.naiveDiff.Changes(id, parent)
  658. }