overlay.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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 identifier
  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
  81. // mounts that are created using this driver.
  82. type Driver struct {
  83. home string
  84. uidMaps []idtools.IDMap
  85. gidMaps []idtools.IDMap
  86. ctr *graphdriver.RefCounter
  87. quotaCtl *quota.Control
  88. options overlayOptions
  89. naiveDiff graphdriver.DiffDriver
  90. supportsDType bool
  91. locker *locker.Locker
  92. }
  93. var (
  94. backingFs = "<unknown>"
  95. projectQuotaSupported = false
  96. useNaiveDiffLock sync.Once
  97. useNaiveDiffOnly bool
  98. )
  99. func init() {
  100. graphdriver.Register(driverName, Init)
  101. }
  102. // Init returns the native diff driver for overlay filesystem.
  103. // If overlay filesystem is not supported on the host, the error
  104. // graphdriver.ErrNotSupported is returned.
  105. // If an overlay filesystem is not supported over an existing filesystem then
  106. // the error graphdriver.ErrIncompatibleFS is returned.
  107. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  108. opts, err := parseOptions(options)
  109. if err != nil {
  110. return nil, err
  111. }
  112. if err := supportsOverlay(); err != nil {
  113. return nil, graphdriver.ErrNotSupported
  114. }
  115. // require kernel 4.0.0 to ensure multiple lower dirs are supported
  116. v, err := kernel.GetKernelVersion()
  117. if err != nil {
  118. return nil, err
  119. }
  120. fsMagic, err := graphdriver.GetFSMagic(home)
  121. if err != nil {
  122. return nil, err
  123. }
  124. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  125. backingFs = fsName
  126. }
  127. // check if they are running over btrfs, aufs, zfs, overlay, or ecryptfs
  128. switch fsMagic {
  129. case graphdriver.FsMagicAufs, graphdriver.FsMagicZfs, graphdriver.FsMagicOverlay, graphdriver.FsMagicEcryptfs:
  130. logrus.Errorf("'overlay2' is not supported over %s", backingFs)
  131. return nil, graphdriver.ErrIncompatibleFS
  132. case graphdriver.FsMagicBtrfs:
  133. // Support for OverlayFS on BTRFS was added in kernel 4.7
  134. // See https://btrfs.wiki.kernel.org/index.php/Changelog
  135. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 7, Minor: 0}) < 0 {
  136. if !opts.overrideKernelCheck {
  137. logrus.Errorf("'overlay2' requires kernel 4.7 to use on %s", backingFs)
  138. return nil, graphdriver.ErrIncompatibleFS
  139. }
  140. logrus.Warn("Using pre-4.7.0 kernel for overlay2 on btrfs, may require kernel update")
  141. }
  142. }
  143. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 0, Minor: 0}) < 0 {
  144. if opts.overrideKernelCheck {
  145. logrus.Warn("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update")
  146. } else {
  147. if err := supportsMultipleLowerDir(filepath.Dir(home)); err != nil {
  148. logrus.Debugf("Multiple lower dirs not supported: %v", err)
  149. return nil, graphdriver.ErrNotSupported
  150. }
  151. }
  152. }
  153. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  154. if err != nil {
  155. return nil, err
  156. }
  157. // Create the driver home dir
  158. if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, idtools.IDPair{rootUID, rootGID}); err != nil && !os.IsExist(err) {
  159. return nil, err
  160. }
  161. if err := mount.MakePrivate(home); err != nil {
  162. return nil, err
  163. }
  164. supportsDType, err := fsutils.SupportsDType(home)
  165. if err != nil {
  166. return nil, err
  167. }
  168. if !supportsDType {
  169. // not a fatal error until v17.12 (#27443)
  170. logrus.Warn(overlayutils.ErrDTypeNotSupported("overlay2", backingFs))
  171. }
  172. d := &Driver{
  173. home: home,
  174. uidMaps: uidMaps,
  175. gidMaps: gidMaps,
  176. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  177. supportsDType: supportsDType,
  178. locker: locker.New(),
  179. options: *opts,
  180. }
  181. d.naiveDiff = graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps)
  182. if backingFs == "xfs" {
  183. // Try to enable project quota support over xfs.
  184. if d.quotaCtl, err = quota.NewControl(home); err == nil {
  185. projectQuotaSupported = true
  186. } else if opts.quota.Size > 0 {
  187. return nil, fmt.Errorf("Storage option overlay2.size not supported. Filesystem does not support Project Quota: %v", err)
  188. }
  189. } else if opts.quota.Size > 0 {
  190. // if xfs is not the backing fs then error out if the storage-opt overlay2.size is used.
  191. return nil, fmt.Errorf("Storage Option overlay2.size only supported for backingFS XFS. Found %v", backingFs)
  192. }
  193. logrus.Debugf("backingFs=%s, projectQuotaSupported=%v", backingFs, projectQuotaSupported)
  194. return d, nil
  195. }
  196. func parseOptions(options []string) (*overlayOptions, error) {
  197. o := &overlayOptions{}
  198. for _, option := range options {
  199. key, val, err := parsers.ParseKeyValueOpt(option)
  200. if err != nil {
  201. return nil, err
  202. }
  203. key = strings.ToLower(key)
  204. switch key {
  205. case "overlay2.override_kernel_check":
  206. o.overrideKernelCheck, err = strconv.ParseBool(val)
  207. if err != nil {
  208. return nil, err
  209. }
  210. case "overlay2.size":
  211. size, err := units.RAMInBytes(val)
  212. if err != nil {
  213. return nil, err
  214. }
  215. o.quota.Size = uint64(size)
  216. default:
  217. return nil, fmt.Errorf("overlay2: unknown option %s", key)
  218. }
  219. }
  220. return o, nil
  221. }
  222. func supportsOverlay() error {
  223. // We can try to modprobe overlay first before looking at
  224. // proc/filesystems for when overlay is supported
  225. exec.Command("modprobe", "overlay").Run()
  226. f, err := os.Open("/proc/filesystems")
  227. if err != nil {
  228. return err
  229. }
  230. defer f.Close()
  231. s := bufio.NewScanner(f)
  232. for s.Scan() {
  233. if s.Text() == "nodev\toverlay" {
  234. return nil
  235. }
  236. }
  237. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  238. return graphdriver.ErrNotSupported
  239. }
  240. func useNaiveDiff(home string) bool {
  241. useNaiveDiffLock.Do(func() {
  242. if err := doesSupportNativeDiff(home); err != nil {
  243. logrus.Warnf("Not using native diff for overlay2, this may cause degraded performance for building images: %v", err)
  244. useNaiveDiffOnly = true
  245. }
  246. })
  247. return useNaiveDiffOnly
  248. }
  249. func (d *Driver) String() string {
  250. return driverName
  251. }
  252. // Status returns current driver information in a two dimensional string array.
  253. // Output contains "Backing Filesystem" used in this implementation.
  254. func (d *Driver) Status() [][2]string {
  255. return [][2]string{
  256. {"Backing Filesystem", backingFs},
  257. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  258. {"Native Overlay Diff", strconv.FormatBool(!useNaiveDiff(d.home))},
  259. }
  260. }
  261. // GetMetadata returns metadata about the overlay driver such as the LowerDir,
  262. // UpperDir, WorkDir, and MergeDir used to store data.
  263. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  264. dir := d.dir(id)
  265. if _, err := os.Stat(dir); err != nil {
  266. return nil, err
  267. }
  268. metadata := map[string]string{
  269. "WorkDir": path.Join(dir, "work"),
  270. "MergedDir": path.Join(dir, "merged"),
  271. "UpperDir": path.Join(dir, "diff"),
  272. }
  273. lowerDirs, err := d.getLowerDirs(id)
  274. if err != nil {
  275. return nil, err
  276. }
  277. if len(lowerDirs) > 0 {
  278. metadata["LowerDir"] = strings.Join(lowerDirs, ":")
  279. }
  280. return metadata, nil
  281. }
  282. // Cleanup any state created by overlay which should be cleaned when daemon
  283. // is being shutdown. For now, we just have to unmount the bind mounted
  284. // we had created.
  285. func (d *Driver) Cleanup() error {
  286. return mount.Unmount(d.home)
  287. }
  288. // CreateReadWrite creates a layer that is writable for use as a container
  289. // file system.
  290. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  291. if opts != nil && len(opts.StorageOpt) != 0 && !projectQuotaSupported {
  292. return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option")
  293. }
  294. if opts == nil {
  295. opts = &graphdriver.CreateOpts{
  296. StorageOpt: map[string]string{},
  297. }
  298. }
  299. if _, ok := opts.StorageOpt["size"]; !ok {
  300. if opts.StorageOpt == nil {
  301. opts.StorageOpt = map[string]string{}
  302. }
  303. opts.StorageOpt["size"] = strconv.FormatUint(d.options.quota.Size, 10)
  304. }
  305. return d.create(id, parent, opts)
  306. }
  307. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  308. // The parent filesystem is used to configure these directories for the overlay.
  309. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  310. if opts != nil && len(opts.StorageOpt) != 0 {
  311. if _, ok := opts.StorageOpt["size"]; ok {
  312. return fmt.Errorf("--storage-opt size is only supported for ReadWrite Layers")
  313. }
  314. }
  315. return d.create(id, parent, opts)
  316. }
  317. func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  318. dir := d.dir(id)
  319. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  320. if err != nil {
  321. return err
  322. }
  323. root := idtools.IDPair{UID: rootUID, GID: rootGID}
  324. if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
  325. return err
  326. }
  327. if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
  328. return err
  329. }
  330. defer func() {
  331. // Clean up on failure
  332. if retErr != nil {
  333. os.RemoveAll(dir)
  334. }
  335. }()
  336. if opts != nil && len(opts.StorageOpt) > 0 {
  337. driver := &Driver{}
  338. if err := d.parseStorageOpt(opts.StorageOpt, driver); err != nil {
  339. return err
  340. }
  341. if driver.options.quota.Size > 0 {
  342. // Set container disk quota limit
  343. if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil {
  344. return err
  345. }
  346. }
  347. }
  348. if err := idtools.MkdirAndChown(path.Join(dir, "diff"), 0755, root); err != nil {
  349. return err
  350. }
  351. lid := generateID(idLength)
  352. if err := os.Symlink(path.Join("..", id, "diff"), path.Join(d.home, linkDir, lid)); err != nil {
  353. return err
  354. }
  355. // Write link id to link file
  356. if err := ioutil.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
  357. return err
  358. }
  359. // if no parent directory, done
  360. if parent == "" {
  361. return nil
  362. }
  363. if err := idtools.MkdirAndChown(path.Join(dir, "work"), 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. // Cleanup the created merged directory; see the comment in Put's rmdir
  480. if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
  481. logrus.Debugf("Failed to remove %s: %v: %v", id, rmErr, err)
  482. }
  483. }
  484. }
  485. }()
  486. workDir := path.Join(dir, "work")
  487. splitLowers := strings.Split(string(lowers), ":")
  488. absLowers := make([]string, len(splitLowers))
  489. for i, s := range splitLowers {
  490. absLowers[i] = path.Join(d.home, s)
  491. }
  492. opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", strings.Join(absLowers, ":"), path.Join(dir, "diff"), path.Join(dir, "work"))
  493. mountData := label.FormatMountLabel(opts, mountLabel)
  494. mount := unix.Mount
  495. mountTarget := mergedDir
  496. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  497. if err != nil {
  498. return nil, err
  499. }
  500. if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.IDPair{rootUID, rootGID}); err != nil {
  501. return nil, err
  502. }
  503. pageSize := unix.Getpagesize()
  504. // Go can return a larger page size than supported by the system
  505. // as of go 1.7. This will be fixed in 1.8 and this block can be
  506. // removed when building with 1.8.
  507. // See https://github.com/golang/go/commit/1b9499b06989d2831e5b156161d6c07642926ee1
  508. // See https://github.com/docker/docker/issues/27384
  509. if pageSize > 4096 {
  510. pageSize = 4096
  511. }
  512. // Use relative paths and mountFrom when the mount data has exceeded
  513. // the page size. The mount syscall fails if the mount data cannot
  514. // fit within a page and relative links make the mount data much
  515. // smaller at the expense of requiring a fork exec to chroot.
  516. if len(mountData) > pageSize {
  517. opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", string(lowers), path.Join(id, "diff"), path.Join(id, "work"))
  518. mountData = label.FormatMountLabel(opts, mountLabel)
  519. if len(mountData) > pageSize {
  520. return nil, fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData))
  521. }
  522. mount = func(source string, target string, mType string, flags uintptr, label string) error {
  523. return mountFrom(d.home, source, target, mType, flags, label)
  524. }
  525. mountTarget = path.Join(id, "merged")
  526. }
  527. if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil {
  528. return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  529. }
  530. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  531. // user namespace requires this to move a directory from lower to upper.
  532. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  533. return nil, err
  534. }
  535. return containerfs.NewLocalContainerFS(mergedDir), nil
  536. }
  537. // Put unmounts the mount path created for the give id.
  538. // It also removes the 'merged' directory to force the kernel to unmount the
  539. // overlay mount in other namespaces.
  540. func (d *Driver) Put(id string) error {
  541. d.locker.Lock(id)
  542. defer d.locker.Unlock(id)
  543. dir := d.dir(id)
  544. _, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  545. if err != nil {
  546. // If no lower, no mount happened and just return directly
  547. if os.IsNotExist(err) {
  548. return nil
  549. }
  550. return err
  551. }
  552. mountpoint := path.Join(dir, "merged")
  553. if count := d.ctr.Decrement(mountpoint); count > 0 {
  554. return nil
  555. }
  556. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  557. logrus.Debugf("Failed to unmount %s overlay: %s - %v", id, mountpoint, err)
  558. }
  559. // Remove the mountpoint here. Removing the mountpoint (in newer kernels)
  560. // will cause all other instances of this mount in other mount namespaces
  561. // to be unmounted. This is necessary to avoid cases where an overlay mount
  562. // that is present in another namespace will cause subsequent mounts
  563. // operations to fail with ebusy. We ignore any errors here because this may
  564. // fail on older kernels which don't have
  565. // torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied.
  566. if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) {
  567. logrus.Debugf("Failed to remove %s overlay: %v", id, err)
  568. }
  569. return nil
  570. }
  571. // Exists checks to see if the id is already mounted.
  572. func (d *Driver) Exists(id string) bool {
  573. _, err := os.Stat(d.dir(id))
  574. return err == nil
  575. }
  576. // isParent determines whether the given parent is the direct parent of the
  577. // given layer id
  578. func (d *Driver) isParent(id, parent string) bool {
  579. lowers, err := d.getLowerDirs(id)
  580. if err != nil {
  581. return false
  582. }
  583. if parent == "" && len(lowers) > 0 {
  584. return false
  585. }
  586. parentDir := d.dir(parent)
  587. var ld string
  588. if len(lowers) > 0 {
  589. ld = filepath.Dir(lowers[0])
  590. }
  591. if ld == "" && parent == "" {
  592. return true
  593. }
  594. return ld == parentDir
  595. }
  596. // ApplyDiff applies the new layer into a root
  597. func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
  598. if !d.isParent(id, parent) {
  599. return d.naiveDiff.ApplyDiff(id, parent, diff)
  600. }
  601. applyDir := d.getDiffPath(id)
  602. logrus.Debugf("Applying tar in %s", applyDir)
  603. // Overlay doesn't need the parent id to apply the diff
  604. if err := untar(diff, applyDir, &archive.TarOptions{
  605. UIDMaps: d.uidMaps,
  606. GIDMaps: d.gidMaps,
  607. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  608. }); err != nil {
  609. return 0, err
  610. }
  611. return directory.Size(applyDir)
  612. }
  613. func (d *Driver) getDiffPath(id string) string {
  614. dir := d.dir(id)
  615. return path.Join(dir, "diff")
  616. }
  617. // DiffSize calculates the changes between the specified id
  618. // and its parent and returns the size in bytes of the changes
  619. // relative to its base filesystem directory.
  620. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  621. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  622. return d.naiveDiff.DiffSize(id, parent)
  623. }
  624. return directory.Size(d.getDiffPath(id))
  625. }
  626. // Diff produces an archive of the changes between the specified
  627. // layer and its parent layer which may be "".
  628. func (d *Driver) Diff(id, parent string) (io.ReadCloser, error) {
  629. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  630. return d.naiveDiff.Diff(id, parent)
  631. }
  632. diffPath := d.getDiffPath(id)
  633. logrus.Debugf("Tar with options on %s", diffPath)
  634. return archive.TarWithOptions(diffPath, &archive.TarOptions{
  635. Compression: archive.Uncompressed,
  636. UIDMaps: d.uidMaps,
  637. GIDMaps: d.gidMaps,
  638. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  639. })
  640. }
  641. // Changes produces a list of changes between the specified layer and its
  642. // parent layer. If parent is "", then all changes will be ADD changes.
  643. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  644. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  645. return d.naiveDiff.Changes(id, parent)
  646. }
  647. // Overlay doesn't have snapshots, so we need to get changes from all parent
  648. // layers.
  649. diffPath := d.getDiffPath(id)
  650. layers, err := d.getLowerDirs(id)
  651. if err != nil {
  652. return nil, err
  653. }
  654. return archive.OverlayChanges(layers, diffPath)
  655. }