overlay.go 14 KB

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