overlay.go 14 KB

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