overlay.go 23 KB

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