overlay.go 17 KB

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