overlay.go 23 KB

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