overlay.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. // +build linux
  2. package overlay // import "github.com/docker/docker/daemon/graphdriver/overlay"
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "github.com/docker/docker/daemon/graphdriver"
  15. "github.com/docker/docker/daemon/graphdriver/copy"
  16. "github.com/docker/docker/daemon/graphdriver/overlayutils"
  17. "github.com/docker/docker/pkg/archive"
  18. "github.com/docker/docker/pkg/containerfs"
  19. "github.com/docker/docker/pkg/fsutils"
  20. "github.com/docker/docker/pkg/idtools"
  21. "github.com/docker/docker/pkg/locker"
  22. "github.com/docker/docker/pkg/mount"
  23. "github.com/docker/docker/pkg/parsers"
  24. "github.com/docker/docker/pkg/system"
  25. "github.com/opencontainers/selinux/go-selinux/label"
  26. "github.com/sirupsen/logrus"
  27. "golang.org/x/sys/unix"
  28. )
  29. // This is a small wrapper over the NaiveDiffWriter that lets us have a custom
  30. // implementation of ApplyDiff()
  31. var (
  32. // ErrApplyDiffFallback is returned to indicate that a normal ApplyDiff is applied as a fallback from Naive diff writer.
  33. ErrApplyDiffFallback = fmt.Errorf("Fall back to normal ApplyDiff")
  34. backingFs = "<unknown>"
  35. )
  36. // ApplyDiffProtoDriver wraps the ProtoDriver by extending the interface with ApplyDiff method.
  37. type ApplyDiffProtoDriver interface {
  38. graphdriver.ProtoDriver
  39. // ApplyDiff writes the diff to the archive for the given id and parent id.
  40. // It returns the size in bytes written if successful, an error ErrApplyDiffFallback is returned otherwise.
  41. ApplyDiff(id, parent string, diff io.Reader) (size int64, err error)
  42. }
  43. type naiveDiffDriverWithApply struct {
  44. graphdriver.Driver
  45. applyDiff ApplyDiffProtoDriver
  46. }
  47. // NaiveDiffDriverWithApply returns a NaiveDiff driver with custom ApplyDiff.
  48. func NaiveDiffDriverWithApply(driver ApplyDiffProtoDriver, uidMaps, gidMaps []idtools.IDMap) graphdriver.Driver {
  49. return &naiveDiffDriverWithApply{
  50. Driver: graphdriver.NewNaiveDiffDriver(driver, uidMaps, gidMaps),
  51. applyDiff: driver,
  52. }
  53. }
  54. // ApplyDiff creates a diff layer with either the NaiveDiffDriver or with a fallback.
  55. func (d *naiveDiffDriverWithApply) ApplyDiff(id, parent string, diff io.Reader) (int64, error) {
  56. b, err := d.applyDiff.ApplyDiff(id, parent, diff)
  57. if err == ErrApplyDiffFallback {
  58. return d.Driver.ApplyDiff(id, parent, diff)
  59. }
  60. return b, err
  61. }
  62. // This backend uses the overlay union filesystem for containers
  63. // plus hard link file sharing for images.
  64. // Each container/image can have a "root" subdirectory which is a plain
  65. // filesystem hierarchy, or they can use overlay.
  66. // If they use overlay there is a "upper" directory and a "lower-id"
  67. // file, as well as "merged" and "work" directories. The "upper"
  68. // directory has the upper layer of the overlay, and "lower-id" contains
  69. // the id of the parent whose "root" directory shall be used as the lower
  70. // layer in the overlay. The overlay itself is mounted in the "merged"
  71. // directory, and the "work" dir is needed for overlay to work.
  72. // When an overlay layer is created there are two cases, either the
  73. // parent has a "root" dir, then we start out with an empty "upper"
  74. // directory overlaid on the parents root. This is typically the
  75. // case with the init layer of a container which is based on an image.
  76. // If there is no "root" in the parent, we inherit the lower-id from
  77. // the parent and start by making a copy in the parent's "upper" dir.
  78. // This is typically the case for a container layer which copies
  79. // its parent -init upper layer.
  80. // Additionally we also have a custom implementation of ApplyLayer
  81. // which makes a recursive copy of the parent "root" layer using
  82. // hardlinks to share file data, and then applies the layer on top
  83. // of that. This means all child images share file (but not directory)
  84. // data with the parent.
  85. type overlayOptions struct{}
  86. // Driver contains information about the home directory and the list of active 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. supportsDType bool
  93. locker *locker.Locker
  94. }
  95. func init() {
  96. graphdriver.Register("overlay", Init)
  97. }
  98. // Init returns the NaiveDiffDriver, a native diff driver for overlay filesystem.
  99. // If overlay filesystem is not supported on the host, the error
  100. // graphdriver.ErrNotSupported is returned.
  101. // If an overlay filesystem is not supported over an existing filesystem then
  102. // error graphdriver.ErrIncompatibleFS is returned.
  103. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  104. _, err := parseOptions(options)
  105. if err != nil {
  106. return nil, err
  107. }
  108. if err := supportsOverlay(); err != nil {
  109. return nil, graphdriver.ErrNotSupported
  110. }
  111. // Perform feature detection on /var/lib/docker/overlay if it's an existing directory.
  112. // This covers situations where /var/lib/docker/overlay is a mount, and on a different
  113. // filesystem than /var/lib/docker.
  114. // If the path does not exist, fall back to using /var/lib/docker for feature detection.
  115. testdir := home
  116. if _, err := os.Stat(testdir); os.IsNotExist(err) {
  117. testdir = filepath.Dir(testdir)
  118. }
  119. fsMagic, err := graphdriver.GetFSMagic(testdir)
  120. if err != nil {
  121. return nil, err
  122. }
  123. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  124. backingFs = fsName
  125. }
  126. switch fsMagic {
  127. case graphdriver.FsMagicAufs, graphdriver.FsMagicBtrfs, graphdriver.FsMagicEcryptfs, graphdriver.FsMagicNfsFs, graphdriver.FsMagicOverlay, graphdriver.FsMagicZfs:
  128. logrus.WithField("storage-driver", "overlay").Errorf("'overlay' is not supported over %s", backingFs)
  129. return nil, graphdriver.ErrIncompatibleFS
  130. }
  131. supportsDType, err := fsutils.SupportsDType(testdir)
  132. if err != nil {
  133. return nil, err
  134. }
  135. if !supportsDType {
  136. if !graphdriver.IsInitialized(home) {
  137. return nil, overlayutils.ErrDTypeNotSupported("overlay", backingFs)
  138. }
  139. // allow running without d_type only for existing setups (#27443)
  140. logrus.WithField("storage-driver", "overlay").Warn(overlayutils.ErrDTypeNotSupported("overlay", backingFs))
  141. }
  142. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  143. if err != nil {
  144. return nil, err
  145. }
  146. // Create the driver home dir
  147. if err := idtools.MkdirAllAndChown(home, 0700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil {
  148. return nil, err
  149. }
  150. d := &Driver{
  151. home: home,
  152. uidMaps: uidMaps,
  153. gidMaps: gidMaps,
  154. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  155. supportsDType: supportsDType,
  156. locker: locker.New(),
  157. }
  158. return NaiveDiffDriverWithApply(d, uidMaps, gidMaps), nil
  159. }
  160. func parseOptions(options []string) (*overlayOptions, error) {
  161. o := &overlayOptions{}
  162. for _, option := range options {
  163. key, _, err := parsers.ParseKeyValueOpt(option)
  164. if err != nil {
  165. return nil, err
  166. }
  167. key = strings.ToLower(key)
  168. switch key {
  169. default:
  170. return nil, fmt.Errorf("overlay: unknown option %s", key)
  171. }
  172. }
  173. return o, nil
  174. }
  175. func supportsOverlay() error {
  176. // We can try to modprobe overlay first before looking at
  177. // proc/filesystems for when overlay is supported
  178. exec.Command("modprobe", "overlay").Run()
  179. f, err := os.Open("/proc/filesystems")
  180. if err != nil {
  181. return err
  182. }
  183. defer f.Close()
  184. s := bufio.NewScanner(f)
  185. for s.Scan() {
  186. if s.Text() == "nodev\toverlay" {
  187. return nil
  188. }
  189. }
  190. logrus.WithField("storage-driver", "overlay").Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  191. return graphdriver.ErrNotSupported
  192. }
  193. func (d *Driver) String() string {
  194. return "overlay"
  195. }
  196. // Status returns current driver information in a two dimensional string array.
  197. // Output contains "Backing Filesystem" used in this implementation.
  198. func (d *Driver) Status() [][2]string {
  199. return [][2]string{
  200. {"Backing Filesystem", backingFs},
  201. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  202. }
  203. }
  204. // GetMetadata returns metadata about the overlay driver such as root,
  205. // LowerDir, UpperDir, WorkDir and MergeDir used to store data.
  206. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  207. dir := d.dir(id)
  208. if _, err := os.Stat(dir); err != nil {
  209. return nil, err
  210. }
  211. metadata := make(map[string]string)
  212. // If id has a root, it is an image
  213. rootDir := path.Join(dir, "root")
  214. if _, err := os.Stat(rootDir); err == nil {
  215. metadata["RootDir"] = rootDir
  216. return metadata, nil
  217. }
  218. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  219. if err != nil {
  220. return nil, err
  221. }
  222. metadata["LowerDir"] = path.Join(d.dir(string(lowerID)), "root")
  223. metadata["UpperDir"] = path.Join(dir, "upper")
  224. metadata["WorkDir"] = path.Join(dir, "work")
  225. metadata["MergedDir"] = path.Join(dir, "merged")
  226. return metadata, nil
  227. }
  228. // Cleanup any state created by overlay which should be cleaned when daemon
  229. // is being shutdown. For now, we just have to unmount the bind mounted
  230. // we had created.
  231. func (d *Driver) Cleanup() error {
  232. return mount.RecursiveUnmount(d.home)
  233. }
  234. // CreateReadWrite creates a layer that is writable for use as a container
  235. // file system.
  236. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  237. return d.Create(id, parent, opts)
  238. }
  239. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  240. // The parent filesystem is used to configure these directories for the overlay.
  241. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  242. if opts != nil && len(opts.StorageOpt) != 0 {
  243. return fmt.Errorf("--storage-opt is not supported for overlay")
  244. }
  245. dir := d.dir(id)
  246. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  247. if err != nil {
  248. return err
  249. }
  250. root := idtools.IDPair{UID: rootUID, GID: rootGID}
  251. if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
  252. return err
  253. }
  254. if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
  255. return err
  256. }
  257. defer func() {
  258. // Clean up on failure
  259. if retErr != nil {
  260. os.RemoveAll(dir)
  261. }
  262. }()
  263. // Toplevel images are just a "root" dir
  264. if parent == "" {
  265. return idtools.MkdirAndChown(path.Join(dir, "root"), 0755, root)
  266. }
  267. parentDir := d.dir(parent)
  268. // Ensure parent exists
  269. if _, err := os.Lstat(parentDir); err != nil {
  270. return err
  271. }
  272. // If parent has a root, just do an overlay to it
  273. parentRoot := path.Join(parentDir, "root")
  274. if s, err := os.Lstat(parentRoot); err == nil {
  275. if err := idtools.MkdirAndChown(path.Join(dir, "upper"), s.Mode(), root); err != nil {
  276. return err
  277. }
  278. if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
  279. return err
  280. }
  281. return ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666)
  282. }
  283. // Otherwise, copy the upper and the lower-id from the parent
  284. lowerID, err := ioutil.ReadFile(path.Join(parentDir, "lower-id"))
  285. if err != nil {
  286. return err
  287. }
  288. if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerID, 0666); err != nil {
  289. return err
  290. }
  291. parentUpperDir := path.Join(parentDir, "upper")
  292. s, err := os.Lstat(parentUpperDir)
  293. if err != nil {
  294. return err
  295. }
  296. upperDir := path.Join(dir, "upper")
  297. if err := idtools.MkdirAndChown(upperDir, s.Mode(), root); err != nil {
  298. return err
  299. }
  300. if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
  301. return err
  302. }
  303. return copy.DirCopy(parentUpperDir, upperDir, copy.Content, true)
  304. }
  305. func (d *Driver) dir(id string) string {
  306. return path.Join(d.home, id)
  307. }
  308. // Remove cleans the directories that are created for this id.
  309. func (d *Driver) Remove(id string) error {
  310. if id == "" {
  311. return fmt.Errorf("refusing to remove the directories: id is empty")
  312. }
  313. d.locker.Lock(id)
  314. defer d.locker.Unlock(id)
  315. return system.EnsureRemoveAll(d.dir(id))
  316. }
  317. // Get creates and mounts the required file system for the given id and returns the mount path.
  318. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err error) {
  319. d.locker.Lock(id)
  320. defer d.locker.Unlock(id)
  321. dir := d.dir(id)
  322. if _, err := os.Stat(dir); err != nil {
  323. return nil, err
  324. }
  325. // If id has a root, just return it
  326. rootDir := path.Join(dir, "root")
  327. if _, err := os.Stat(rootDir); err == nil {
  328. return containerfs.NewLocalContainerFS(rootDir), nil
  329. }
  330. mergedDir := path.Join(dir, "merged")
  331. if count := d.ctr.Increment(mergedDir); count > 1 {
  332. return containerfs.NewLocalContainerFS(mergedDir), nil
  333. }
  334. defer func() {
  335. if err != nil {
  336. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  337. if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil {
  338. logrus.WithField("storage-driver", "overlay").Debugf("Failed to unmount %s: %v: %v", id, mntErr, err)
  339. }
  340. // Cleanup the created merged directory; see the comment in Put's rmdir
  341. if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
  342. logrus.WithField("storage-driver", "overlay").Warnf("Failed to remove %s: %v: %v", id, rmErr, err)
  343. }
  344. }
  345. }
  346. }()
  347. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  348. if err != nil {
  349. return nil, err
  350. }
  351. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  352. if err != nil {
  353. return nil, err
  354. }
  355. if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil {
  356. return nil, err
  357. }
  358. var (
  359. lowerDir = path.Join(d.dir(string(lowerID)), "root")
  360. upperDir = path.Join(dir, "upper")
  361. workDir = path.Join(dir, "work")
  362. opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
  363. )
  364. if err := unix.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
  365. return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  366. }
  367. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  368. // user namespace requires this to move a directory from lower to upper.
  369. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  370. return nil, err
  371. }
  372. return containerfs.NewLocalContainerFS(mergedDir), nil
  373. }
  374. // Put unmounts the mount path created for the give id.
  375. // It also removes the 'merged' directory to force the kernel to unmount the
  376. // overlay mount in other namespaces.
  377. func (d *Driver) Put(id string) error {
  378. d.locker.Lock(id)
  379. defer d.locker.Unlock(id)
  380. // If id has a root, just return
  381. if _, err := os.Stat(path.Join(d.dir(id), "root")); err == nil {
  382. return nil
  383. }
  384. mountpoint := path.Join(d.dir(id), "merged")
  385. logger := logrus.WithField("storage-driver", "overlay")
  386. if count := d.ctr.Decrement(mountpoint); count > 0 {
  387. return nil
  388. }
  389. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  390. logger.Debugf("Failed to unmount %s overlay: %v", id, err)
  391. }
  392. // Remove the mountpoint here. Removing the mountpoint (in newer kernels)
  393. // will cause all other instances of this mount in other mount namespaces
  394. // to be unmounted. This is necessary to avoid cases where an overlay mount
  395. // that is present in another namespace will cause subsequent mounts
  396. // operations to fail with ebusy. We ignore any errors here because this may
  397. // fail on older kernels which don't have
  398. // torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied.
  399. if err := unix.Rmdir(mountpoint); err != nil {
  400. logger.Debugf("Failed to remove %s overlay: %v", id, err)
  401. }
  402. return nil
  403. }
  404. // ApplyDiff applies the new layer on top of the root, if parent does not exist with will return an ErrApplyDiffFallback error.
  405. func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
  406. dir := d.dir(id)
  407. if parent == "" {
  408. return 0, ErrApplyDiffFallback
  409. }
  410. parentRootDir := path.Join(d.dir(parent), "root")
  411. if _, err := os.Stat(parentRootDir); err != nil {
  412. return 0, ErrApplyDiffFallback
  413. }
  414. // We now know there is a parent, and it has a "root" directory containing
  415. // the full root filesystem. We can just hardlink it and apply the
  416. // layer. This relies on two things:
  417. // 1) ApplyDiff is only run once on a clean (no writes to upper layer) container
  418. // 2) ApplyDiff doesn't do any in-place writes to files (would break hardlinks)
  419. // These are all currently true and are not expected to break
  420. tmpRootDir, err := ioutil.TempDir(dir, "tmproot")
  421. if err != nil {
  422. return 0, err
  423. }
  424. defer func() {
  425. if err != nil {
  426. os.RemoveAll(tmpRootDir)
  427. } else {
  428. os.RemoveAll(path.Join(dir, "upper"))
  429. os.RemoveAll(path.Join(dir, "work"))
  430. os.RemoveAll(path.Join(dir, "merged"))
  431. os.RemoveAll(path.Join(dir, "lower-id"))
  432. }
  433. }()
  434. if err = copy.DirCopy(parentRootDir, tmpRootDir, copy.Hardlink, true); err != nil {
  435. return 0, err
  436. }
  437. options := &archive.TarOptions{UIDMaps: d.uidMaps, GIDMaps: d.gidMaps}
  438. if size, err = graphdriver.ApplyUncompressedLayer(tmpRootDir, diff, options); err != nil {
  439. return 0, err
  440. }
  441. rootDir := path.Join(dir, "root")
  442. if err := os.Rename(tmpRootDir, rootDir); err != nil {
  443. return 0, err
  444. }
  445. return
  446. }
  447. // Exists checks to see if the id is already mounted.
  448. func (d *Driver) Exists(id string) bool {
  449. _, err := os.Stat(d.dir(id))
  450. return err == nil
  451. }