overlay.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. // +build linux
  2. package overlay2 // import "github.com/docker/docker/daemon/graphdriver/overlay2"
  3. import (
  4. "bufio"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "github.com/docker/docker/daemon/graphdriver"
  18. "github.com/docker/docker/daemon/graphdriver/overlayutils"
  19. "github.com/docker/docker/daemon/graphdriver/quota"
  20. "github.com/docker/docker/pkg/archive"
  21. "github.com/docker/docker/pkg/chrootarchive"
  22. "github.com/docker/docker/pkg/containerfs"
  23. "github.com/docker/docker/pkg/directory"
  24. "github.com/docker/docker/pkg/fsutils"
  25. "github.com/docker/docker/pkg/idtools"
  26. "github.com/docker/docker/pkg/locker"
  27. "github.com/docker/docker/pkg/mount"
  28. "github.com/docker/docker/pkg/parsers"
  29. "github.com/docker/docker/pkg/parsers/kernel"
  30. "github.com/docker/docker/pkg/system"
  31. units "github.com/docker/go-units"
  32. rsystem "github.com/opencontainers/runc/libcontainer/system"
  33. "github.com/opencontainers/selinux/go-selinux/label"
  34. "github.com/sirupsen/logrus"
  35. "golang.org/x/sys/unix"
  36. )
  37. var (
  38. // untar defines the untar method
  39. untar = chrootarchive.UntarUncompressed
  40. )
  41. // This backend uses the overlay union filesystem for containers
  42. // with diff directories for each layer.
  43. // This version of the overlay driver requires at least kernel
  44. // 4.0.0 in order to support mounting multiple diff directories.
  45. // Each container/image has at least a "diff" directory and "link" file.
  46. // If there is also a "lower" file when there are diff layers
  47. // below as well as "merged" and "work" directories. The "diff" directory
  48. // has the upper layer of the overlay and is used to capture any
  49. // changes to the layer. The "lower" file contains all the lower layer
  50. // mounts separated by ":" and ordered from uppermost to lowermost
  51. // layers. The overlay itself is mounted in the "merged" directory,
  52. // and the "work" dir is needed for overlay to work.
  53. // The "link" file for each layer contains a unique string for the layer.
  54. // Under the "l" directory at the root there will be a symbolic link
  55. // with that unique string pointing the "diff" directory for the layer.
  56. // The symbolic links are used to reference lower layers in the "lower"
  57. // file and on mount. The links are used to shorten the total length
  58. // of a layer reference without requiring changes to the layer identifier
  59. // or root directory. Mounts are always done relative to root and
  60. // referencing the symbolic links in order to ensure the number of
  61. // lower directories can fit in a single page for making the mount
  62. // syscall. A hard upper limit of 128 lower layers is enforced to ensure
  63. // that mounts do not fail due to length.
  64. const (
  65. driverName = "overlay2"
  66. linkDir = "l"
  67. diffDirName = "diff"
  68. workDirName = "work"
  69. mergedDirName = "merged"
  70. lowerFile = "lower"
  71. maxDepth = 128
  72. // idLength represents the number of random characters
  73. // which can be used to create the unique link identifier
  74. // for every layer. If this value is too long then the
  75. // page size limit for the mount command may be exceeded.
  76. // The idLength should be selected such that following equation
  77. // is true (512 is a buffer for label metadata).
  78. // ((idLength + len(linkDir) + 1) * maxDepth) <= (pageSize - 512)
  79. idLength = 26
  80. )
  81. type overlayOptions struct {
  82. overrideKernelCheck bool
  83. quota quota.Quota
  84. }
  85. // Driver contains information about the home directory and the list of active
  86. // mounts that are created using this driver.
  87. type Driver struct {
  88. home string
  89. uidMaps []idtools.IDMap
  90. gidMaps []idtools.IDMap
  91. ctr *graphdriver.RefCounter
  92. quotaCtl *quota.Control
  93. options overlayOptions
  94. naiveDiff graphdriver.DiffDriver
  95. supportsDType bool
  96. locker *locker.Locker
  97. }
  98. var (
  99. logger = logrus.WithField("storage-driver", "overlay2")
  100. backingFs = "<unknown>"
  101. projectQuotaSupported = false
  102. useNaiveDiffLock sync.Once
  103. useNaiveDiffOnly bool
  104. indexOff string
  105. )
  106. func init() {
  107. graphdriver.Register(driverName, Init)
  108. }
  109. // Init returns the native diff driver for overlay filesystem.
  110. // If overlay filesystem is not supported on the host, the error
  111. // graphdriver.ErrNotSupported is returned.
  112. // If an overlay filesystem is not supported over an existing filesystem then
  113. // the error graphdriver.ErrIncompatibleFS is returned.
  114. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  115. opts, err := parseOptions(options)
  116. if err != nil {
  117. return nil, err
  118. }
  119. if err := supportsOverlay(); err != nil {
  120. return nil, graphdriver.ErrNotSupported
  121. }
  122. // require kernel 4.0.0 to ensure multiple lower dirs are supported
  123. v, err := kernel.GetKernelVersion()
  124. if err != nil {
  125. return nil, err
  126. }
  127. // Perform feature detection on /var/lib/docker/overlay2 if it's an existing directory.
  128. // This covers situations where /var/lib/docker/overlay2 is a mount, and on a different
  129. // filesystem than /var/lib/docker.
  130. // If the path does not exist, fall back to using /var/lib/docker for feature detection.
  131. testdir := home
  132. if _, err := os.Stat(testdir); os.IsNotExist(err) {
  133. testdir = filepath.Dir(testdir)
  134. }
  135. fsMagic, err := graphdriver.GetFSMagic(testdir)
  136. if err != nil {
  137. return nil, err
  138. }
  139. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  140. backingFs = fsName
  141. }
  142. switch fsMagic {
  143. case graphdriver.FsMagicAufs, graphdriver.FsMagicEcryptfs, graphdriver.FsMagicNfsFs, graphdriver.FsMagicOverlay, graphdriver.FsMagicZfs:
  144. logger.Errorf("'overlay2' is not supported over %s", backingFs)
  145. return nil, graphdriver.ErrIncompatibleFS
  146. case graphdriver.FsMagicBtrfs:
  147. // Support for OverlayFS on BTRFS was added in kernel 4.7
  148. // See https://btrfs.wiki.kernel.org/index.php/Changelog
  149. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 7, Minor: 0}) < 0 {
  150. if !opts.overrideKernelCheck {
  151. logger.Errorf("'overlay2' requires kernel 4.7 to use on %s", backingFs)
  152. return nil, graphdriver.ErrIncompatibleFS
  153. }
  154. logger.Warn("Using pre-4.7.0 kernel for overlay2 on btrfs, may require kernel update")
  155. }
  156. }
  157. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 0, Minor: 0}) < 0 {
  158. if opts.overrideKernelCheck {
  159. logger.Warn("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update")
  160. } else {
  161. if err := supportsMultipleLowerDir(testdir); err != nil {
  162. logger.Debugf("Multiple lower dirs not supported: %v", err)
  163. return nil, graphdriver.ErrNotSupported
  164. }
  165. }
  166. }
  167. supportsDType, err := fsutils.SupportsDType(testdir)
  168. if err != nil {
  169. return nil, err
  170. }
  171. if !supportsDType {
  172. if !graphdriver.IsInitialized(home) {
  173. return nil, overlayutils.ErrDTypeNotSupported("overlay2", backingFs)
  174. }
  175. // allow running without d_type only for existing setups (#27443)
  176. logger.Warn(overlayutils.ErrDTypeNotSupported("overlay2", backingFs))
  177. }
  178. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  179. if err != nil {
  180. return nil, err
  181. }
  182. // Create the driver home dir
  183. if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
  184. return nil, err
  185. }
  186. d := &Driver{
  187. home: home,
  188. uidMaps: uidMaps,
  189. gidMaps: gidMaps,
  190. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  191. supportsDType: supportsDType,
  192. locker: locker.New(),
  193. options: *opts,
  194. }
  195. d.naiveDiff = graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps)
  196. if backingFs == "xfs" {
  197. // Try to enable project quota support over xfs.
  198. if d.quotaCtl, err = quota.NewControl(home); err == nil {
  199. projectQuotaSupported = true
  200. } else if opts.quota.Size > 0 {
  201. return nil, fmt.Errorf("Storage option overlay2.size not supported. Filesystem does not support Project Quota: %v", err)
  202. }
  203. } else if opts.quota.Size > 0 {
  204. // if xfs is not the backing fs then error out if the storage-opt overlay2.size is used.
  205. return nil, fmt.Errorf("Storage Option overlay2.size only supported for backingFS XFS. Found %v", backingFs)
  206. }
  207. // figure out whether "index=off" option is recognized by the kernel
  208. _, err = os.Stat("/sys/module/overlay/parameters/index")
  209. switch {
  210. case err == nil:
  211. indexOff = "index=off,"
  212. case os.IsNotExist(err):
  213. // old kernel, no index -- do nothing
  214. default:
  215. logger.Warnf("Unable to detect whether overlay kernel module supports index parameter: %s", err)
  216. }
  217. logger.Debugf("backingFs=%s, projectQuotaSupported=%v, indexOff=%q", backingFs, projectQuotaSupported, indexOff)
  218. return d, nil
  219. }
  220. func parseOptions(options []string) (*overlayOptions, error) {
  221. o := &overlayOptions{}
  222. for _, option := range options {
  223. key, val, err := parsers.ParseKeyValueOpt(option)
  224. if err != nil {
  225. return nil, err
  226. }
  227. key = strings.ToLower(key)
  228. switch key {
  229. case "overlay2.override_kernel_check":
  230. o.overrideKernelCheck, err = strconv.ParseBool(val)
  231. if err != nil {
  232. return nil, err
  233. }
  234. case "overlay2.size":
  235. size, err := units.RAMInBytes(val)
  236. if err != nil {
  237. return nil, err
  238. }
  239. o.quota.Size = uint64(size)
  240. default:
  241. return nil, fmt.Errorf("overlay2: unknown option %s", key)
  242. }
  243. }
  244. return o, nil
  245. }
  246. func supportsOverlay() error {
  247. // We can try to modprobe overlay first before looking at
  248. // proc/filesystems for when overlay is supported
  249. exec.Command("modprobe", "overlay").Run()
  250. f, err := os.Open("/proc/filesystems")
  251. if err != nil {
  252. return err
  253. }
  254. defer f.Close()
  255. s := bufio.NewScanner(f)
  256. for s.Scan() {
  257. if s.Text() == "nodev\toverlay" {
  258. return nil
  259. }
  260. }
  261. logger.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  262. return graphdriver.ErrNotSupported
  263. }
  264. func useNaiveDiff(home string) bool {
  265. useNaiveDiffLock.Do(func() {
  266. if err := doesSupportNativeDiff(home); err != nil {
  267. logger.Warnf("Not using native diff for overlay2, this may cause degraded performance for building images: %v", err)
  268. useNaiveDiffOnly = true
  269. }
  270. })
  271. return useNaiveDiffOnly
  272. }
  273. func (d *Driver) String() string {
  274. return driverName
  275. }
  276. // Status returns current driver information in a two dimensional string array.
  277. // Output contains "Backing Filesystem" used in this implementation.
  278. func (d *Driver) Status() [][2]string {
  279. return [][2]string{
  280. {"Backing Filesystem", backingFs},
  281. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  282. {"Native Overlay Diff", strconv.FormatBool(!useNaiveDiff(d.home))},
  283. }
  284. }
  285. // GetMetadata returns metadata about the overlay driver such as the LowerDir,
  286. // UpperDir, WorkDir, and MergeDir used to store data.
  287. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  288. dir := d.dir(id)
  289. if _, err := os.Stat(dir); err != nil {
  290. return nil, err
  291. }
  292. metadata := map[string]string{
  293. "WorkDir": path.Join(dir, workDirName),
  294. "MergedDir": path.Join(dir, mergedDirName),
  295. "UpperDir": path.Join(dir, diffDirName),
  296. }
  297. lowerDirs, err := d.getLowerDirs(id)
  298. if err != nil {
  299. return nil, err
  300. }
  301. if len(lowerDirs) > 0 {
  302. metadata["LowerDir"] = strings.Join(lowerDirs, ":")
  303. }
  304. return metadata, nil
  305. }
  306. // Cleanup any state created by overlay which should be cleaned when daemon
  307. // is being shutdown. For now, we just have to unmount the bind mounted
  308. // we had created.
  309. func (d *Driver) Cleanup() error {
  310. return mount.RecursiveUnmount(d.home)
  311. }
  312. // CreateReadWrite creates a layer that is writable for use as a container
  313. // file system.
  314. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  315. if opts != nil && len(opts.StorageOpt) != 0 && !projectQuotaSupported {
  316. return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option")
  317. }
  318. if opts == nil {
  319. opts = &graphdriver.CreateOpts{
  320. StorageOpt: map[string]string{},
  321. }
  322. }
  323. if _, ok := opts.StorageOpt["size"]; !ok {
  324. if opts.StorageOpt == nil {
  325. opts.StorageOpt = map[string]string{}
  326. }
  327. opts.StorageOpt["size"] = strconv.FormatUint(d.options.quota.Size, 10)
  328. }
  329. return d.create(id, parent, opts)
  330. }
  331. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  332. // The parent filesystem is used to configure these directories for the overlay.
  333. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  334. if opts != nil && len(opts.StorageOpt) != 0 {
  335. if _, ok := opts.StorageOpt["size"]; ok {
  336. return fmt.Errorf("--storage-opt size is only supported for ReadWrite Layers")
  337. }
  338. }
  339. return d.create(id, parent, opts)
  340. }
  341. func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  342. dir := d.dir(id)
  343. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  344. if err != nil {
  345. return err
  346. }
  347. root := idtools.Identity{UID: rootUID, GID: rootGID}
  348. if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
  349. return err
  350. }
  351. if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
  352. return err
  353. }
  354. defer func() {
  355. // Clean up on failure
  356. if retErr != nil {
  357. os.RemoveAll(dir)
  358. }
  359. }()
  360. if opts != nil && len(opts.StorageOpt) > 0 {
  361. driver := &Driver{}
  362. if err := d.parseStorageOpt(opts.StorageOpt, driver); err != nil {
  363. return err
  364. }
  365. if driver.options.quota.Size > 0 {
  366. // Set container disk quota limit
  367. if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil {
  368. return err
  369. }
  370. }
  371. }
  372. if err := idtools.MkdirAndChown(path.Join(dir, diffDirName), 0755, root); err != nil {
  373. return err
  374. }
  375. lid := generateID(idLength)
  376. if err := os.Symlink(path.Join("..", id, diffDirName), path.Join(d.home, linkDir, lid)); err != nil {
  377. return err
  378. }
  379. // Write link id to link file
  380. if err := ioutil.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
  381. return err
  382. }
  383. // if no parent directory, done
  384. if parent == "" {
  385. return nil
  386. }
  387. if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0700, root); err != nil {
  388. return err
  389. }
  390. if err := ioutil.WriteFile(path.Join(d.dir(parent), "committed"), []byte{}, 0600); err != nil {
  391. return err
  392. }
  393. lower, err := d.getLower(parent)
  394. if err != nil {
  395. return err
  396. }
  397. if lower != "" {
  398. if err := ioutil.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
  399. return err
  400. }
  401. }
  402. return nil
  403. }
  404. // Parse overlay storage options
  405. func (d *Driver) parseStorageOpt(storageOpt map[string]string, driver *Driver) error {
  406. // Read size to set the disk project quota per container
  407. for key, val := range storageOpt {
  408. key := strings.ToLower(key)
  409. switch key {
  410. case "size":
  411. size, err := units.RAMInBytes(val)
  412. if err != nil {
  413. return err
  414. }
  415. driver.options.quota.Size = uint64(size)
  416. default:
  417. return fmt.Errorf("Unknown option %s", key)
  418. }
  419. }
  420. return nil
  421. }
  422. func (d *Driver) getLower(parent string) (string, error) {
  423. parentDir := d.dir(parent)
  424. // Ensure parent exists
  425. if _, err := os.Lstat(parentDir); err != nil {
  426. return "", err
  427. }
  428. // Read Parent link fileA
  429. parentLink, err := ioutil.ReadFile(path.Join(parentDir, "link"))
  430. if err != nil {
  431. return "", err
  432. }
  433. lowers := []string{path.Join(linkDir, string(parentLink))}
  434. parentLower, err := ioutil.ReadFile(path.Join(parentDir, lowerFile))
  435. if err == nil {
  436. parentLowers := strings.Split(string(parentLower), ":")
  437. lowers = append(lowers, parentLowers...)
  438. }
  439. if len(lowers) > maxDepth {
  440. return "", errors.New("max depth exceeded")
  441. }
  442. return strings.Join(lowers, ":"), nil
  443. }
  444. func (d *Driver) dir(id string) string {
  445. return path.Join(d.home, id)
  446. }
  447. func (d *Driver) getLowerDirs(id string) ([]string, error) {
  448. var lowersArray []string
  449. lowers, err := ioutil.ReadFile(path.Join(d.dir(id), lowerFile))
  450. if err == nil {
  451. for _, s := range strings.Split(string(lowers), ":") {
  452. lp, err := os.Readlink(path.Join(d.home, s))
  453. if err != nil {
  454. return nil, err
  455. }
  456. lowersArray = append(lowersArray, path.Clean(path.Join(d.home, linkDir, lp)))
  457. }
  458. } else if !os.IsNotExist(err) {
  459. return nil, err
  460. }
  461. return lowersArray, nil
  462. }
  463. // Remove cleans the directories that are created for this id.
  464. func (d *Driver) Remove(id string) error {
  465. if id == "" {
  466. return fmt.Errorf("refusing to remove the directories: id is empty")
  467. }
  468. d.locker.Lock(id)
  469. defer d.locker.Unlock(id)
  470. dir := d.dir(id)
  471. lid, err := ioutil.ReadFile(path.Join(dir, "link"))
  472. if err == nil {
  473. if len(lid) == 0 {
  474. logger.Errorf("refusing to remove empty link for layer %v", id)
  475. } else if err := os.RemoveAll(path.Join(d.home, linkDir, string(lid))); err != nil {
  476. logger.Debugf("Failed to remove link: %v", err)
  477. }
  478. }
  479. if err := system.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
  480. return err
  481. }
  482. return nil
  483. }
  484. // Get creates and mounts the required file system for the given id and returns the mount path.
  485. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
  486. d.locker.Lock(id)
  487. defer d.locker.Unlock(id)
  488. dir := d.dir(id)
  489. if _, err := os.Stat(dir); err != nil {
  490. return nil, err
  491. }
  492. diffDir := path.Join(dir, diffDirName)
  493. lowers, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  494. if err != nil {
  495. // If no lower, just return diff directory
  496. if os.IsNotExist(err) {
  497. return containerfs.NewLocalContainerFS(diffDir), nil
  498. }
  499. return nil, err
  500. }
  501. mergedDir := path.Join(dir, mergedDirName)
  502. if count := d.ctr.Increment(mergedDir); count > 1 {
  503. return containerfs.NewLocalContainerFS(mergedDir), nil
  504. }
  505. defer func() {
  506. if retErr != nil {
  507. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  508. if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil {
  509. logger.Errorf("error unmounting %v: %v", mergedDir, mntErr)
  510. }
  511. // Cleanup the created merged directory; see the comment in Put's rmdir
  512. if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
  513. logger.Debugf("Failed to remove %s: %v: %v", id, rmErr, err)
  514. }
  515. }
  516. }
  517. }()
  518. workDir := path.Join(dir, workDirName)
  519. splitLowers := strings.Split(string(lowers), ":")
  520. absLowers := make([]string, len(splitLowers))
  521. for i, s := range splitLowers {
  522. absLowers[i] = path.Join(d.home, s)
  523. }
  524. var readonly bool
  525. if _, err := os.Stat(path.Join(dir, "committed")); err == nil {
  526. readonly = true
  527. } else if !os.IsNotExist(err) {
  528. return nil, err
  529. }
  530. var opts string
  531. if readonly {
  532. opts = indexOff + "lowerdir=" + diffDir + ":" + strings.Join(absLowers, ":")
  533. } else {
  534. opts = indexOff + "lowerdir=" + strings.Join(absLowers, ":") + ",upperdir=" + diffDir + ",workdir=" + workDir
  535. }
  536. mountData := label.FormatMountLabel(opts, mountLabel)
  537. mount := unix.Mount
  538. mountTarget := mergedDir
  539. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  540. if err != nil {
  541. return nil, err
  542. }
  543. if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.Identity{UID: rootUID, GID: rootGID}); err != nil {
  544. return nil, err
  545. }
  546. pageSize := unix.Getpagesize()
  547. // Use relative paths and mountFrom when the mount data has exceeded
  548. // the page size. The mount syscall fails if the mount data cannot
  549. // fit within a page and relative links make the mount data much
  550. // smaller at the expense of requiring a fork exec to chroot.
  551. if len(mountData) > pageSize {
  552. if readonly {
  553. opts = indexOff + "lowerdir=" + path.Join(id, diffDirName) + ":" + string(lowers)
  554. } else {
  555. opts = indexOff + "lowerdir=" + string(lowers) + ",upperdir=" + path.Join(id, diffDirName) + ",workdir=" + path.Join(id, workDirName)
  556. }
  557. mountData = label.FormatMountLabel(opts, mountLabel)
  558. if len(mountData) > pageSize {
  559. return nil, fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData))
  560. }
  561. mount = func(source string, target string, mType string, flags uintptr, label string) error {
  562. return mountFrom(d.home, source, target, mType, flags, label)
  563. }
  564. mountTarget = path.Join(id, mergedDirName)
  565. }
  566. if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil {
  567. return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  568. }
  569. if !readonly {
  570. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  571. // user namespace requires this to move a directory from lower to upper.
  572. if err := os.Chown(path.Join(workDir, workDirName), rootUID, rootGID); err != nil {
  573. return nil, err
  574. }
  575. }
  576. return containerfs.NewLocalContainerFS(mergedDir), nil
  577. }
  578. // Put unmounts the mount path created for the give id.
  579. // It also removes the 'merged' directory to force the kernel to unmount the
  580. // overlay mount in other namespaces.
  581. func (d *Driver) Put(id string) error {
  582. d.locker.Lock(id)
  583. defer d.locker.Unlock(id)
  584. dir := d.dir(id)
  585. _, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  586. if err != nil {
  587. // If no lower, no mount happened and just return directly
  588. if os.IsNotExist(err) {
  589. return nil
  590. }
  591. return err
  592. }
  593. mountpoint := path.Join(dir, mergedDirName)
  594. if count := d.ctr.Decrement(mountpoint); count > 0 {
  595. return nil
  596. }
  597. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  598. logger.Debugf("Failed to unmount %s overlay: %s - %v", id, mountpoint, err)
  599. }
  600. // Remove the mountpoint here. Removing the mountpoint (in newer kernels)
  601. // will cause all other instances of this mount in other mount namespaces
  602. // to be unmounted. This is necessary to avoid cases where an overlay mount
  603. // that is present in another namespace will cause subsequent mounts
  604. // operations to fail with ebusy. We ignore any errors here because this may
  605. // fail on older kernels which don't have
  606. // torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied.
  607. if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) {
  608. logger.Debugf("Failed to remove %s overlay: %v", id, err)
  609. }
  610. return nil
  611. }
  612. // Exists checks to see if the id is already mounted.
  613. func (d *Driver) Exists(id string) bool {
  614. _, err := os.Stat(d.dir(id))
  615. return err == nil
  616. }
  617. // isParent determines whether the given parent is the direct parent of the
  618. // given layer id
  619. func (d *Driver) isParent(id, parent string) bool {
  620. lowers, err := d.getLowerDirs(id)
  621. if err != nil {
  622. return false
  623. }
  624. if parent == "" && len(lowers) > 0 {
  625. return false
  626. }
  627. parentDir := d.dir(parent)
  628. var ld string
  629. if len(lowers) > 0 {
  630. ld = filepath.Dir(lowers[0])
  631. }
  632. if ld == "" && parent == "" {
  633. return true
  634. }
  635. return ld == parentDir
  636. }
  637. // ApplyDiff applies the new layer into a root
  638. func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
  639. if !d.isParent(id, parent) {
  640. return d.naiveDiff.ApplyDiff(id, parent, diff)
  641. }
  642. applyDir := d.getDiffPath(id)
  643. logger.Debugf("Applying tar in %s", applyDir)
  644. // Overlay doesn't need the parent id to apply the diff
  645. if err := untar(diff, applyDir, &archive.TarOptions{
  646. UIDMaps: d.uidMaps,
  647. GIDMaps: d.gidMaps,
  648. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  649. InUserNS: rsystem.RunningInUserNS(),
  650. }); err != nil {
  651. return 0, err
  652. }
  653. return directory.Size(context.TODO(), applyDir)
  654. }
  655. func (d *Driver) getDiffPath(id string) string {
  656. dir := d.dir(id)
  657. return path.Join(dir, diffDirName)
  658. }
  659. // DiffSize calculates the changes between the specified id
  660. // and its parent and returns the size in bytes of the changes
  661. // relative to its base filesystem directory.
  662. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  663. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  664. return d.naiveDiff.DiffSize(id, parent)
  665. }
  666. return directory.Size(context.TODO(), d.getDiffPath(id))
  667. }
  668. // Diff produces an archive of the changes between the specified
  669. // layer and its parent layer which may be "".
  670. func (d *Driver) Diff(id, parent string) (io.ReadCloser, error) {
  671. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  672. return d.naiveDiff.Diff(id, parent)
  673. }
  674. diffPath := d.getDiffPath(id)
  675. logger.Debugf("Tar with options on %s", diffPath)
  676. return archive.TarWithOptions(diffPath, &archive.TarOptions{
  677. Compression: archive.Uncompressed,
  678. UIDMaps: d.uidMaps,
  679. GIDMaps: d.gidMaps,
  680. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  681. })
  682. }
  683. // Changes produces a list of changes between the specified layer and its
  684. // parent layer. If parent is "", then all changes will be ADD changes.
  685. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  686. return d.naiveDiff.Changes(id, parent)
  687. }