overlay.go 16 KB

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