overlay.go 15 KB

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