overlay.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. // +build linux
  2. package overlay
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "strconv"
  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/locker"
  20. "github.com/docker/docker/pkg/mount"
  21. "github.com/docker/docker/pkg/system"
  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. // Driver contains information about the home directory and the list of active mounts that are created using this driver.
  83. type Driver struct {
  84. home string
  85. uidMaps []idtools.IDMap
  86. gidMaps []idtools.IDMap
  87. ctr *graphdriver.RefCounter
  88. supportsDType bool
  89. locker *locker.Locker
  90. }
  91. func init() {
  92. graphdriver.Register("overlay", Init)
  93. }
  94. // Init returns the NaiveDiffDriver, a native diff driver for overlay filesystem.
  95. // If overlay filesystem is not supported on the host, graphdriver.ErrNotSupported is returned as error.
  96. // If an overlay filesystem is not supported over an existing filesystem then error graphdriver.ErrIncompatibleFS is returned.
  97. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  98. if err := supportsOverlay(); err != nil {
  99. return nil, graphdriver.ErrNotSupported
  100. }
  101. fsMagic, err := graphdriver.GetFSMagic(home)
  102. if err != nil {
  103. return nil, err
  104. }
  105. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  106. backingFs = fsName
  107. }
  108. switch fsMagic {
  109. case graphdriver.FsMagicAufs, graphdriver.FsMagicBtrfs, graphdriver.FsMagicOverlay, graphdriver.FsMagicZfs, graphdriver.FsMagicEcryptfs:
  110. logrus.Errorf("'overlay' is not supported over %s", backingFs)
  111. return nil, graphdriver.ErrIncompatibleFS
  112. }
  113. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  114. if err != nil {
  115. return nil, err
  116. }
  117. // Create the driver home dir
  118. if err := idtools.MkdirAllAndChown(home, 0700, idtools.IDPair{rootUID, rootGID}); err != nil && !os.IsExist(err) {
  119. return nil, err
  120. }
  121. if err := mount.MakePrivate(home); err != nil {
  122. return nil, err
  123. }
  124. supportsDType, err := fsutils.SupportsDType(home)
  125. if err != nil {
  126. return nil, err
  127. }
  128. if !supportsDType {
  129. // not a fatal error until v17.12 (#27443)
  130. logrus.Warn(overlayutils.ErrDTypeNotSupported("overlay", backingFs))
  131. }
  132. d := &Driver{
  133. home: home,
  134. uidMaps: uidMaps,
  135. gidMaps: gidMaps,
  136. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  137. supportsDType: supportsDType,
  138. locker: locker.New(),
  139. }
  140. return NaiveDiffDriverWithApply(d, uidMaps, gidMaps), nil
  141. }
  142. func supportsOverlay() error {
  143. // We can try to modprobe overlay first before looking at
  144. // proc/filesystems for when overlay is supported
  145. exec.Command("modprobe", "overlay").Run()
  146. f, err := os.Open("/proc/filesystems")
  147. if err != nil {
  148. return err
  149. }
  150. defer f.Close()
  151. s := bufio.NewScanner(f)
  152. for s.Scan() {
  153. if s.Text() == "nodev\toverlay" {
  154. return nil
  155. }
  156. }
  157. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  158. return graphdriver.ErrNotSupported
  159. }
  160. func (d *Driver) String() string {
  161. return "overlay"
  162. }
  163. // Status returns current driver information in a two dimensional string array.
  164. // Output contains "Backing Filesystem" used in this implementation.
  165. func (d *Driver) Status() [][2]string {
  166. return [][2]string{
  167. {"Backing Filesystem", backingFs},
  168. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  169. }
  170. }
  171. // GetMetadata returns meta data about the overlay driver such as root, LowerDir, UpperDir, WorkDir and MergeDir used to store data.
  172. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  173. dir := d.dir(id)
  174. if _, err := os.Stat(dir); err != nil {
  175. return nil, err
  176. }
  177. metadata := make(map[string]string)
  178. // If id has a root, it is an image
  179. rootDir := path.Join(dir, "root")
  180. if _, err := os.Stat(rootDir); err == nil {
  181. metadata["RootDir"] = rootDir
  182. return metadata, nil
  183. }
  184. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  185. if err != nil {
  186. return nil, err
  187. }
  188. metadata["LowerDir"] = path.Join(d.dir(string(lowerID)), "root")
  189. metadata["UpperDir"] = path.Join(dir, "upper")
  190. metadata["WorkDir"] = path.Join(dir, "work")
  191. metadata["MergedDir"] = path.Join(dir, "merged")
  192. return metadata, nil
  193. }
  194. // Cleanup any state created by overlay which should be cleaned when daemon
  195. // is being shutdown. For now, we just have to unmount the bind mounted
  196. // we had created.
  197. func (d *Driver) Cleanup() error {
  198. return mount.Unmount(d.home)
  199. }
  200. // CreateReadWrite creates a layer that is writable for use as a container
  201. // file system.
  202. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  203. return d.Create(id, parent, opts)
  204. }
  205. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  206. // The parent filesystem is used to configure these directories for the overlay.
  207. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  208. if opts != nil && len(opts.StorageOpt) != 0 {
  209. return fmt.Errorf("--storage-opt is not supported for overlay")
  210. }
  211. dir := d.dir(id)
  212. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  213. if err != nil {
  214. return err
  215. }
  216. root := idtools.IDPair{UID: rootUID, GID: rootGID}
  217. if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
  218. return err
  219. }
  220. if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
  221. return err
  222. }
  223. defer func() {
  224. // Clean up on failure
  225. if retErr != nil {
  226. os.RemoveAll(dir)
  227. }
  228. }()
  229. // Toplevel images are just a "root" dir
  230. if parent == "" {
  231. return idtools.MkdirAndChown(path.Join(dir, "root"), 0755, root)
  232. }
  233. parentDir := d.dir(parent)
  234. // Ensure parent exists
  235. if _, err := os.Lstat(parentDir); err != nil {
  236. return err
  237. }
  238. // If parent has a root, just do an overlay to it
  239. parentRoot := path.Join(parentDir, "root")
  240. if s, err := os.Lstat(parentRoot); err == nil {
  241. if err := idtools.MkdirAndChown(path.Join(dir, "upper"), s.Mode(), root); err != nil {
  242. return err
  243. }
  244. if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
  245. return err
  246. }
  247. if err := idtools.MkdirAndChown(path.Join(dir, "merged"), 0700, root); err != nil {
  248. return err
  249. }
  250. if err := ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666); err != nil {
  251. return err
  252. }
  253. return nil
  254. }
  255. // Otherwise, copy the upper and the lower-id from the parent
  256. lowerID, err := ioutil.ReadFile(path.Join(parentDir, "lower-id"))
  257. if err != nil {
  258. return err
  259. }
  260. if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerID, 0666); err != nil {
  261. return err
  262. }
  263. parentUpperDir := path.Join(parentDir, "upper")
  264. s, err := os.Lstat(parentUpperDir)
  265. if err != nil {
  266. return err
  267. }
  268. upperDir := path.Join(dir, "upper")
  269. if err := idtools.MkdirAndChown(upperDir, s.Mode(), root); err != nil {
  270. return err
  271. }
  272. if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
  273. return err
  274. }
  275. if err := idtools.MkdirAndChown(path.Join(dir, "merged"), 0700, root); err != nil {
  276. return err
  277. }
  278. return copy.DirCopy(parentUpperDir, upperDir, copy.Content)
  279. }
  280. func (d *Driver) dir(id string) string {
  281. return path.Join(d.home, id)
  282. }
  283. // Remove cleans the directories that are created for this id.
  284. func (d *Driver) Remove(id string) error {
  285. d.locker.Lock(id)
  286. defer d.locker.Unlock(id)
  287. return system.EnsureRemoveAll(d.dir(id))
  288. }
  289. // Get creates and mounts the required file system for the given id and returns the mount path.
  290. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err error) {
  291. d.locker.Lock(id)
  292. defer d.locker.Unlock(id)
  293. dir := d.dir(id)
  294. if _, err := os.Stat(dir); err != nil {
  295. return nil, err
  296. }
  297. // If id has a root, just return it
  298. rootDir := path.Join(dir, "root")
  299. if _, err := os.Stat(rootDir); err == nil {
  300. return containerfs.NewLocalContainerFS(rootDir), nil
  301. }
  302. mergedDir := path.Join(dir, "merged")
  303. if count := d.ctr.Increment(mergedDir); count > 1 {
  304. return containerfs.NewLocalContainerFS(mergedDir), nil
  305. }
  306. defer func() {
  307. if err != nil {
  308. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  309. unix.Unmount(mergedDir, 0)
  310. }
  311. }
  312. }()
  313. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  314. if err != nil {
  315. return nil, err
  316. }
  317. var (
  318. lowerDir = path.Join(d.dir(string(lowerID)), "root")
  319. upperDir = path.Join(dir, "upper")
  320. workDir = path.Join(dir, "work")
  321. opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
  322. )
  323. if err := unix.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
  324. return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  325. }
  326. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  327. // user namespace requires this to move a directory from lower to upper.
  328. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  329. if err != nil {
  330. return nil, err
  331. }
  332. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  333. return nil, err
  334. }
  335. return containerfs.NewLocalContainerFS(mergedDir), nil
  336. }
  337. // Put unmounts the mount path created for the give id.
  338. func (d *Driver) Put(id string) error {
  339. d.locker.Lock(id)
  340. defer d.locker.Unlock(id)
  341. // If id has a root, just return
  342. if _, err := os.Stat(path.Join(d.dir(id), "root")); err == nil {
  343. return nil
  344. }
  345. mountpoint := path.Join(d.dir(id), "merged")
  346. if count := d.ctr.Decrement(mountpoint); count > 0 {
  347. return nil
  348. }
  349. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  350. logrus.Debugf("Failed to unmount %s overlay: %v", id, err)
  351. }
  352. return nil
  353. }
  354. // ApplyDiff applies the new layer on top of the root, if parent does not exist with will return an ErrApplyDiffFallback error.
  355. func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
  356. dir := d.dir(id)
  357. if parent == "" {
  358. return 0, ErrApplyDiffFallback
  359. }
  360. parentRootDir := path.Join(d.dir(parent), "root")
  361. if _, err := os.Stat(parentRootDir); err != nil {
  362. return 0, ErrApplyDiffFallback
  363. }
  364. // We now know there is a parent, and it has a "root" directory containing
  365. // the full root filesystem. We can just hardlink it and apply the
  366. // layer. This relies on two things:
  367. // 1) ApplyDiff is only run once on a clean (no writes to upper layer) container
  368. // 2) ApplyDiff doesn't do any in-place writes to files (would break hardlinks)
  369. // These are all currently true and are not expected to break
  370. tmpRootDir, err := ioutil.TempDir(dir, "tmproot")
  371. if err != nil {
  372. return 0, err
  373. }
  374. defer func() {
  375. if err != nil {
  376. os.RemoveAll(tmpRootDir)
  377. } else {
  378. os.RemoveAll(path.Join(dir, "upper"))
  379. os.RemoveAll(path.Join(dir, "work"))
  380. os.RemoveAll(path.Join(dir, "merged"))
  381. os.RemoveAll(path.Join(dir, "lower-id"))
  382. }
  383. }()
  384. if err = copy.DirCopy(parentRootDir, tmpRootDir, copy.Hardlink); err != nil {
  385. return 0, err
  386. }
  387. options := &archive.TarOptions{UIDMaps: d.uidMaps, GIDMaps: d.gidMaps}
  388. if size, err = graphdriver.ApplyUncompressedLayer(tmpRootDir, diff, options); err != nil {
  389. return 0, err
  390. }
  391. rootDir := path.Join(dir, "root")
  392. if err := os.Rename(tmpRootDir, rootDir); err != nil {
  393. return 0, err
  394. }
  395. return
  396. }
  397. // Exists checks to see if the id is already mounted.
  398. func (d *Driver) Exists(id string) bool {
  399. _, err := os.Stat(d.dir(id))
  400. return err == nil
  401. }