overlay.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // +build linux
  2. package overlay2
  3. import (
  4. "bufio"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "syscall"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/daemon/graphdriver"
  16. "github.com/docker/docker/daemon/graphdriver/quota"
  17. "github.com/docker/docker/pkg/archive"
  18. "github.com/docker/docker/pkg/chrootarchive"
  19. "github.com/docker/docker/pkg/directory"
  20. "github.com/docker/docker/pkg/idtools"
  21. "github.com/docker/docker/pkg/mount"
  22. "github.com/docker/docker/pkg/parsers"
  23. "github.com/docker/docker/pkg/parsers/kernel"
  24. "github.com/docker/go-units"
  25. "github.com/opencontainers/runc/libcontainer/label"
  26. )
  27. var (
  28. // untar defines the untar method
  29. untar = chrootarchive.UntarUncompressed
  30. )
  31. // This backend uses the overlay union filesystem for containers
  32. // with diff directories for each layer.
  33. // This version of the overlay driver requires at least kernel
  34. // 4.0.0 in order to support mounting multiple diff directories.
  35. // Each container/image has at least a "diff" directory and "link" file.
  36. // If there is also a "lower" file when there are diff layers
  37. // below as well as "merged" and "work" directories. The "diff" directory
  38. // has the upper layer of the overlay and is used to capture any
  39. // changes to the layer. The "lower" file contains all the lower layer
  40. // mounts separated by ":" and ordered from uppermost to lowermost
  41. // layers. The overlay itself is mounted in the "merged" directory,
  42. // and the "work" dir is needed for overlay to work.
  43. // The "link" file for each layer contains a unique string for the layer.
  44. // Under the "l" directory at the root there will be a symbolic link
  45. // with that unique string pointing the "diff" directory for the layer.
  46. // The symbolic links are used to reference lower layers in the "lower"
  47. // file and on mount. The links are used to shorten the total length
  48. // of a layer reference without requiring changes to the layer identifier
  49. // or root directory. Mounts are always done relative to root and
  50. // referencing the symbolic links in order to ensure the number of
  51. // lower directories can fit in a single page for making the mount
  52. // syscall. A hard upper limit of 128 lower layers is enforced to ensure
  53. // that mounts do not fail due to length.
  54. const (
  55. driverName = "overlay2"
  56. linkDir = "l"
  57. lowerFile = "lower"
  58. maxDepth = 128
  59. // idLength represents the number of random characters
  60. // which can be used to create the unique link identifer
  61. // for every layer. If this value is too long then the
  62. // page size limit for the mount command may be exceeded.
  63. // The idLength should be selected such that following equation
  64. // is true (512 is a buffer for label metadata).
  65. // ((idLength + len(linkDir) + 1) * maxDepth) <= (pageSize - 512)
  66. idLength = 26
  67. )
  68. type overlayOptions struct {
  69. overrideKernelCheck bool
  70. quota quota.Quota
  71. }
  72. // Driver contains information about the home directory and the list of active mounts that are created using this driver.
  73. type Driver struct {
  74. home string
  75. uidMaps []idtools.IDMap
  76. gidMaps []idtools.IDMap
  77. ctr *graphdriver.RefCounter
  78. quotaCtl *quota.Control
  79. options overlayOptions
  80. }
  81. var (
  82. backingFs = "<unknown>"
  83. projectQuotaSupported = false
  84. )
  85. func init() {
  86. graphdriver.Register(driverName, Init)
  87. }
  88. // Init returns the a native diff driver for overlay filesystem.
  89. // If overlay filesystem is not supported on the host, graphdriver.ErrNotSupported is returned as error.
  90. // If an overlay filesystem is not supported over an existing filesystem then error graphdriver.ErrIncompatibleFS is returned.
  91. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  92. opts, err := parseOptions(options)
  93. if err != nil {
  94. return nil, err
  95. }
  96. if err := supportsOverlay(); err != nil {
  97. return nil, graphdriver.ErrNotSupported
  98. }
  99. // require kernel 4.0.0 to ensure multiple lower dirs are supported
  100. v, err := kernel.GetKernelVersion()
  101. if err != nil {
  102. return nil, err
  103. }
  104. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 0, Minor: 0}) < 0 {
  105. if !opts.overrideKernelCheck {
  106. return nil, graphdriver.ErrNotSupported
  107. }
  108. logrus.Warnf("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update")
  109. }
  110. fsMagic, err := graphdriver.GetFSMagic(home)
  111. if err != nil {
  112. return nil, err
  113. }
  114. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  115. backingFs = fsName
  116. }
  117. // check if they are running over btrfs, aufs, zfs, overlay, or ecryptfs
  118. switch fsMagic {
  119. case graphdriver.FsMagicBtrfs, graphdriver.FsMagicAufs, graphdriver.FsMagicZfs, graphdriver.FsMagicOverlay, graphdriver.FsMagicEcryptfs:
  120. logrus.Errorf("'overlay2' is not supported over %s", backingFs)
  121. return nil, graphdriver.ErrIncompatibleFS
  122. }
  123. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  124. if err != nil {
  125. return nil, err
  126. }
  127. // Create the driver home dir
  128. if err := idtools.MkdirAllAs(path.Join(home, linkDir), 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  129. return nil, err
  130. }
  131. if err := mount.MakePrivate(home); err != nil {
  132. return nil, err
  133. }
  134. d := &Driver{
  135. home: home,
  136. uidMaps: uidMaps,
  137. gidMaps: gidMaps,
  138. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  139. }
  140. if backingFs == "xfs" {
  141. // Try to enable project quota support over xfs.
  142. if d.quotaCtl, err = quota.NewControl(home); err == nil {
  143. projectQuotaSupported = true
  144. }
  145. }
  146. logrus.Debugf("backingFs=%s, projectQuotaSupported=%v", backingFs, projectQuotaSupported)
  147. return d, nil
  148. }
  149. func parseOptions(options []string) (*overlayOptions, error) {
  150. o := &overlayOptions{}
  151. for _, option := range options {
  152. key, val, err := parsers.ParseKeyValueOpt(option)
  153. if err != nil {
  154. return nil, err
  155. }
  156. key = strings.ToLower(key)
  157. switch key {
  158. case "overlay2.override_kernel_check":
  159. o.overrideKernelCheck, err = strconv.ParseBool(val)
  160. if err != nil {
  161. return nil, err
  162. }
  163. default:
  164. return nil, fmt.Errorf("overlay2: Unknown option %s\n", key)
  165. }
  166. }
  167. return o, nil
  168. }
  169. func supportsOverlay() error {
  170. // We can try to modprobe overlay first before looking at
  171. // proc/filesystems for when overlay is supported
  172. exec.Command("modprobe", "overlay").Run()
  173. f, err := os.Open("/proc/filesystems")
  174. if err != nil {
  175. return err
  176. }
  177. defer f.Close()
  178. s := bufio.NewScanner(f)
  179. for s.Scan() {
  180. if s.Text() == "nodev\toverlay" {
  181. return nil
  182. }
  183. }
  184. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  185. return graphdriver.ErrNotSupported
  186. }
  187. func (d *Driver) String() string {
  188. return driverName
  189. }
  190. // Status returns current driver information in a two dimensional string array.
  191. // Output contains "Backing Filesystem" used in this implementation.
  192. func (d *Driver) Status() [][2]string {
  193. return [][2]string{
  194. {"Backing Filesystem", backingFs},
  195. }
  196. }
  197. // GetMetadata returns meta data about the overlay driver such as
  198. // LowerDir, UpperDir, WorkDir and MergeDir used to store data.
  199. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  200. dir := d.dir(id)
  201. if _, err := os.Stat(dir); err != nil {
  202. return nil, err
  203. }
  204. metadata := map[string]string{
  205. "WorkDir": path.Join(dir, "work"),
  206. "MergedDir": path.Join(dir, "merged"),
  207. "UpperDir": path.Join(dir, "diff"),
  208. }
  209. lowerDirs, err := d.getLowerDirs(id)
  210. if err != nil {
  211. return nil, err
  212. }
  213. if len(lowerDirs) > 0 {
  214. metadata["LowerDir"] = strings.Join(lowerDirs, ":")
  215. }
  216. return metadata, nil
  217. }
  218. // Cleanup any state created by overlay which should be cleaned when daemon
  219. // is being shutdown. For now, we just have to unmount the bind mounted
  220. // we had created.
  221. func (d *Driver) Cleanup() error {
  222. return mount.Unmount(d.home)
  223. }
  224. // CreateReadWrite creates a layer that is writable for use as a container
  225. // file system.
  226. func (d *Driver) CreateReadWrite(id, parent, mountLabel string, storageOpt map[string]string) error {
  227. return d.Create(id, parent, mountLabel, storageOpt)
  228. }
  229. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  230. // The parent filesystem is used to configure these directories for the overlay.
  231. func (d *Driver) Create(id, parent, mountLabel string, storageOpt map[string]string) (retErr error) {
  232. if len(storageOpt) != 0 && !projectQuotaSupported {
  233. return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option")
  234. }
  235. dir := d.dir(id)
  236. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  237. if err != nil {
  238. return err
  239. }
  240. if err := idtools.MkdirAllAs(path.Dir(dir), 0700, rootUID, rootGID); err != nil {
  241. return err
  242. }
  243. if err := idtools.MkdirAs(dir, 0700, rootUID, rootGID); err != nil {
  244. return err
  245. }
  246. defer func() {
  247. // Clean up on failure
  248. if retErr != nil {
  249. os.RemoveAll(dir)
  250. }
  251. }()
  252. if len(storageOpt) > 0 {
  253. driver := &Driver{}
  254. if err := d.parseStorageOpt(storageOpt, driver); err != nil {
  255. return err
  256. }
  257. if driver.options.quota.Size > 0 {
  258. // Set container disk quota limit
  259. if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil {
  260. return err
  261. }
  262. }
  263. }
  264. if err := idtools.MkdirAs(path.Join(dir, "diff"), 0755, rootUID, rootGID); err != nil {
  265. return err
  266. }
  267. lid := generateID(idLength)
  268. if err := os.Symlink(path.Join("..", id, "diff"), path.Join(d.home, linkDir, lid)); err != nil {
  269. return err
  270. }
  271. // Write link id to link file
  272. if err := ioutil.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
  273. return err
  274. }
  275. // if no parent directory, done
  276. if parent == "" {
  277. return nil
  278. }
  279. if err := idtools.MkdirAs(path.Join(dir, "work"), 0700, rootUID, rootGID); err != nil {
  280. return err
  281. }
  282. if err := idtools.MkdirAs(path.Join(dir, "merged"), 0700, rootUID, rootGID); err != nil {
  283. return err
  284. }
  285. lower, err := d.getLower(parent)
  286. if err != nil {
  287. return err
  288. }
  289. if lower != "" {
  290. if err := ioutil.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
  291. return err
  292. }
  293. }
  294. return nil
  295. }
  296. // Parse overlay storage options
  297. func (d *Driver) parseStorageOpt(storageOpt map[string]string, driver *Driver) error {
  298. // Read size to set the disk project quota per container
  299. for key, val := range storageOpt {
  300. key := strings.ToLower(key)
  301. switch key {
  302. case "size":
  303. size, err := units.RAMInBytes(val)
  304. if err != nil {
  305. return err
  306. }
  307. driver.options.quota.Size = uint64(size)
  308. default:
  309. return fmt.Errorf("Unknown option %s", key)
  310. }
  311. }
  312. return nil
  313. }
  314. func (d *Driver) getLower(parent string) (string, error) {
  315. parentDir := d.dir(parent)
  316. // Ensure parent exists
  317. if _, err := os.Lstat(parentDir); err != nil {
  318. return "", err
  319. }
  320. // Read Parent link fileA
  321. parentLink, err := ioutil.ReadFile(path.Join(parentDir, "link"))
  322. if err != nil {
  323. return "", err
  324. }
  325. lowers := []string{path.Join(linkDir, string(parentLink))}
  326. parentLower, err := ioutil.ReadFile(path.Join(parentDir, lowerFile))
  327. if err == nil {
  328. parentLowers := strings.Split(string(parentLower), ":")
  329. lowers = append(lowers, parentLowers...)
  330. }
  331. if len(lowers) > maxDepth {
  332. return "", errors.New("max depth exceeded")
  333. }
  334. return strings.Join(lowers, ":"), nil
  335. }
  336. func (d *Driver) dir(id string) string {
  337. return path.Join(d.home, id)
  338. }
  339. func (d *Driver) getLowerDirs(id string) ([]string, error) {
  340. var lowersArray []string
  341. lowers, err := ioutil.ReadFile(path.Join(d.dir(id), lowerFile))
  342. if err == nil {
  343. for _, s := range strings.Split(string(lowers), ":") {
  344. lp, err := os.Readlink(path.Join(d.home, s))
  345. if err != nil {
  346. return nil, err
  347. }
  348. lowersArray = append(lowersArray, path.Clean(path.Join(d.home, "link", lp)))
  349. }
  350. } else if !os.IsNotExist(err) {
  351. return nil, err
  352. }
  353. return lowersArray, nil
  354. }
  355. // Remove cleans the directories that are created for this id.
  356. func (d *Driver) Remove(id string) error {
  357. dir := d.dir(id)
  358. lid, err := ioutil.ReadFile(path.Join(dir, "link"))
  359. if err == nil {
  360. if err := os.RemoveAll(path.Join(d.home, linkDir, string(lid))); err != nil {
  361. logrus.Debugf("Failed to remove link: %v", err)
  362. }
  363. }
  364. if err := os.RemoveAll(dir); err != nil && !os.IsNotExist(err) {
  365. return err
  366. }
  367. return nil
  368. }
  369. // Get creates and mounts the required file system for the given id and returns the mount path.
  370. func (d *Driver) Get(id string, mountLabel string) (s string, err error) {
  371. dir := d.dir(id)
  372. if _, err := os.Stat(dir); err != nil {
  373. return "", err
  374. }
  375. diffDir := path.Join(dir, "diff")
  376. lowers, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  377. if err != nil {
  378. // If no lower, just return diff directory
  379. if os.IsNotExist(err) {
  380. return diffDir, nil
  381. }
  382. return "", err
  383. }
  384. mergedDir := path.Join(dir, "merged")
  385. if count := d.ctr.Increment(mergedDir); count > 1 {
  386. return mergedDir, nil
  387. }
  388. defer func() {
  389. if err != nil {
  390. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  391. syscall.Unmount(mergedDir, 0)
  392. }
  393. }
  394. }()
  395. workDir := path.Join(dir, "work")
  396. splitLowers := strings.Split(string(lowers), ":")
  397. absLowers := make([]string, len(splitLowers))
  398. for i, s := range splitLowers {
  399. absLowers[i] = path.Join(d.home, s)
  400. }
  401. opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", strings.Join(absLowers, ":"), path.Join(dir, "diff"), path.Join(dir, "work"))
  402. mountData := label.FormatMountLabel(opts, mountLabel)
  403. mount := syscall.Mount
  404. mountTarget := mergedDir
  405. pageSize := syscall.Getpagesize()
  406. // Go can return a larger page size than supported by the system
  407. // as of go 1.7. This will be fixed in 1.8 and this block can be
  408. // removed when building with 1.8.
  409. // See https://github.com/golang/go/commit/1b9499b06989d2831e5b156161d6c07642926ee1
  410. // See https://github.com/docker/docker/issues/27384
  411. if pageSize > 4096 {
  412. pageSize = 4096
  413. }
  414. // Use relative paths and mountFrom when the mount data has exceeded
  415. // the page size. The mount syscall fails if the mount data cannot
  416. // fit within a page and relative links make the mount data much
  417. // smaller at the expense of requiring a fork exec to chroot.
  418. if len(mountData) > pageSize {
  419. opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", string(lowers), path.Join(id, "diff"), path.Join(id, "work"))
  420. mountData = label.FormatMountLabel(opts, mountLabel)
  421. if len(mountData) > pageSize {
  422. return "", fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData))
  423. }
  424. mount = func(source string, target string, mType string, flags uintptr, label string) error {
  425. return mountFrom(d.home, source, target, mType, flags, label)
  426. }
  427. mountTarget = path.Join(id, "merged")
  428. }
  429. if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil {
  430. return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  431. }
  432. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  433. // user namespace requires this to move a directory from lower to upper.
  434. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  435. if err != nil {
  436. return "", err
  437. }
  438. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  439. return "", err
  440. }
  441. return mergedDir, nil
  442. }
  443. // Put unmounts the mount path created for the give id.
  444. func (d *Driver) Put(id string) error {
  445. mountpoint := path.Join(d.dir(id), "merged")
  446. if count := d.ctr.Decrement(mountpoint); count > 0 {
  447. return nil
  448. }
  449. if err := syscall.Unmount(mountpoint, 0); err != nil {
  450. logrus.Debugf("Failed to unmount %s overlay: %v", id, err)
  451. }
  452. return nil
  453. }
  454. // Exists checks to see if the id is already mounted.
  455. func (d *Driver) Exists(id string) bool {
  456. _, err := os.Stat(d.dir(id))
  457. return err == nil
  458. }
  459. // ApplyDiff applies the new layer into a root
  460. func (d *Driver) ApplyDiff(id string, parent string, diff archive.Reader) (size int64, err error) {
  461. applyDir := d.getDiffPath(id)
  462. logrus.Debugf("Applying tar in %s", applyDir)
  463. // Overlay doesn't need the parent id to apply the diff
  464. if err := untar(diff, applyDir, &archive.TarOptions{
  465. UIDMaps: d.uidMaps,
  466. GIDMaps: d.gidMaps,
  467. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  468. }); err != nil {
  469. return 0, err
  470. }
  471. return d.DiffSize(id, parent)
  472. }
  473. func (d *Driver) getDiffPath(id string) string {
  474. dir := d.dir(id)
  475. return path.Join(dir, "diff")
  476. }
  477. // DiffSize calculates the changes between the specified id
  478. // and its parent and returns the size in bytes of the changes
  479. // relative to its base filesystem directory.
  480. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  481. return directory.Size(d.getDiffPath(id))
  482. }
  483. // Diff produces an archive of the changes between the specified
  484. // layer and its parent layer which may be "".
  485. func (d *Driver) Diff(id, parent string) (archive.Archive, error) {
  486. diffPath := d.getDiffPath(id)
  487. logrus.Debugf("Tar with options on %s", diffPath)
  488. return archive.TarWithOptions(diffPath, &archive.TarOptions{
  489. Compression: archive.Uncompressed,
  490. UIDMaps: d.uidMaps,
  491. GIDMaps: d.gidMaps,
  492. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  493. })
  494. }
  495. // Changes produces a list of changes between the specified layer
  496. // and its parent layer. If parent is "", then all changes will be ADD changes.
  497. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  498. // Overlay doesn't have snapshots, so we need to get changes from all parent
  499. // layers.
  500. diffPath := d.getDiffPath(id)
  501. layers, err := d.getLowerDirs(id)
  502. if err != nil {
  503. return nil, err
  504. }
  505. return archive.OverlayChanges(layers, diffPath)
  506. }