overlay.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. "syscall"
  13. "github.com/Sirupsen/logrus"
  14. "github.com/docker/docker/daemon/graphdriver"
  15. "github.com/docker/docker/daemon/graphdriver/overlayutils"
  16. "github.com/docker/docker/pkg/archive"
  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. )
  24. // This is a small wrapper over the NaiveDiffWriter that lets us have a custom
  25. // implementation of ApplyDiff()
  26. var (
  27. // ErrApplyDiffFallback is returned to indicate that a normal ApplyDiff is applied as a fallback from Naive diff writer.
  28. ErrApplyDiffFallback = fmt.Errorf("Fall back to normal ApplyDiff")
  29. backingFs = "<unknown>"
  30. )
  31. // ApplyDiffProtoDriver wraps the ProtoDriver by extending the interface with ApplyDiff method.
  32. type ApplyDiffProtoDriver interface {
  33. graphdriver.ProtoDriver
  34. // ApplyDiff writes the diff to the archive for the given id and parent id.
  35. // It returns the size in bytes written if successful, an error ErrApplyDiffFallback is returned otherwise.
  36. ApplyDiff(id, parent string, diff io.Reader) (size int64, err error)
  37. }
  38. type naiveDiffDriverWithApply struct {
  39. graphdriver.Driver
  40. applyDiff ApplyDiffProtoDriver
  41. }
  42. // NaiveDiffDriverWithApply returns a NaiveDiff driver with custom ApplyDiff.
  43. func NaiveDiffDriverWithApply(driver ApplyDiffProtoDriver, uidMaps, gidMaps []idtools.IDMap) graphdriver.Driver {
  44. return &naiveDiffDriverWithApply{
  45. Driver: graphdriver.NewNaiveDiffDriver(driver, uidMaps, gidMaps),
  46. applyDiff: driver,
  47. }
  48. }
  49. // ApplyDiff creates a diff layer with either the NaiveDiffDriver or with a fallback.
  50. func (d *naiveDiffDriverWithApply) ApplyDiff(id, parent string, diff io.Reader) (int64, error) {
  51. b, err := d.applyDiff.ApplyDiff(id, parent, diff)
  52. if err == ErrApplyDiffFallback {
  53. return d.Driver.ApplyDiff(id, parent, diff)
  54. }
  55. return b, err
  56. }
  57. // This backend uses the overlay union filesystem for containers
  58. // plus hard link file sharing for images.
  59. // Each container/image can have a "root" subdirectory which is a plain
  60. // filesystem hierarchy, or they can use overlay.
  61. // If they use overlay there is a "upper" directory and a "lower-id"
  62. // file, as well as "merged" and "work" directories. The "upper"
  63. // directory has the upper layer of the overlay, and "lower-id" contains
  64. // the id of the parent whose "root" directory shall be used as the lower
  65. // layer in the overlay. The overlay itself is mounted in the "merged"
  66. // directory, and the "work" dir is needed for overlay to work.
  67. // When an overlay layer is created there are two cases, either the
  68. // parent has a "root" dir, then we start out with an empty "upper"
  69. // directory overlaid on the parents root. This is typically the
  70. // case with the init layer of a container which is based on an image.
  71. // If there is no "root" in the parent, we inherit the lower-id from
  72. // the parent and start by making a copy in the parent's "upper" dir.
  73. // This is typically the case for a container layer which copies
  74. // its parent -init upper layer.
  75. // Additionally we also have a custom implementation of ApplyLayer
  76. // which makes a recursive copy of the parent "root" layer using
  77. // hardlinks to share file data, and then applies the layer on top
  78. // of that. This means all child images share file (but not directory)
  79. // data with the parent.
  80. // Driver contains information about the home directory and the list of active mounts that are created using this driver.
  81. type Driver struct {
  82. home string
  83. uidMaps []idtools.IDMap
  84. gidMaps []idtools.IDMap
  85. ctr *graphdriver.RefCounter
  86. supportsDType bool
  87. locker *locker.Locker
  88. }
  89. func init() {
  90. graphdriver.Register("overlay", Init)
  91. }
  92. // Init returns the NaiveDiffDriver, a native diff driver for overlay filesystem.
  93. // If overlay filesystem is not supported on the host, graphdriver.ErrNotSupported is returned as error.
  94. // If an overlay filesystem is not supported over an existing filesystem then error graphdriver.ErrIncompatibleFS is returned.
  95. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  96. if err := supportsOverlay(); err != nil {
  97. return nil, graphdriver.ErrNotSupported
  98. }
  99. fsMagic, err := graphdriver.GetFSMagic(home)
  100. if err != nil {
  101. return nil, err
  102. }
  103. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  104. backingFs = fsName
  105. }
  106. switch fsMagic {
  107. case graphdriver.FsMagicAufs, graphdriver.FsMagicBtrfs, graphdriver.FsMagicOverlay, graphdriver.FsMagicZfs, graphdriver.FsMagicEcryptfs:
  108. logrus.Errorf("'overlay' is not supported over %s", backingFs)
  109. return nil, graphdriver.ErrIncompatibleFS
  110. }
  111. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  112. if err != nil {
  113. return nil, err
  114. }
  115. // Create the driver home dir
  116. if err := idtools.MkdirAllAs(home, 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  117. return nil, err
  118. }
  119. if err := mount.MakePrivate(home); err != nil {
  120. return nil, err
  121. }
  122. supportsDType, err := fsutils.SupportsDType(home)
  123. if err != nil {
  124. return nil, err
  125. }
  126. if !supportsDType {
  127. // not a fatal error until v17.12 (#27443)
  128. logrus.Warn(overlayutils.ErrDTypeNotSupported("overlay", backingFs))
  129. }
  130. d := &Driver{
  131. home: home,
  132. uidMaps: uidMaps,
  133. gidMaps: gidMaps,
  134. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  135. supportsDType: supportsDType,
  136. locker: locker.New(),
  137. }
  138. return NaiveDiffDriverWithApply(d, uidMaps, gidMaps), nil
  139. }
  140. func supportsOverlay() error {
  141. // We can try to modprobe overlay first before looking at
  142. // proc/filesystems for when overlay is supported
  143. exec.Command("modprobe", "overlay").Run()
  144. f, err := os.Open("/proc/filesystems")
  145. if err != nil {
  146. return err
  147. }
  148. defer f.Close()
  149. s := bufio.NewScanner(f)
  150. for s.Scan() {
  151. if s.Text() == "nodev\toverlay" {
  152. return nil
  153. }
  154. }
  155. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  156. return graphdriver.ErrNotSupported
  157. }
  158. func (d *Driver) String() string {
  159. return "overlay"
  160. }
  161. // Status returns current driver information in a two dimensional string array.
  162. // Output contains "Backing Filesystem" used in this implementation.
  163. func (d *Driver) Status() [][2]string {
  164. return [][2]string{
  165. {"Backing Filesystem", backingFs},
  166. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  167. }
  168. }
  169. // GetMetadata returns meta data about the overlay driver such as root, LowerDir, UpperDir, WorkDir and MergeDir used to store data.
  170. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  171. dir := d.dir(id)
  172. if _, err := os.Stat(dir); err != nil {
  173. return nil, err
  174. }
  175. metadata := make(map[string]string)
  176. // If id has a root, it is an image
  177. rootDir := path.Join(dir, "root")
  178. if _, err := os.Stat(rootDir); err == nil {
  179. metadata["RootDir"] = rootDir
  180. return metadata, nil
  181. }
  182. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  183. if err != nil {
  184. return nil, err
  185. }
  186. metadata["LowerDir"] = path.Join(d.dir(string(lowerID)), "root")
  187. metadata["UpperDir"] = path.Join(dir, "upper")
  188. metadata["WorkDir"] = path.Join(dir, "work")
  189. metadata["MergedDir"] = path.Join(dir, "merged")
  190. return metadata, nil
  191. }
  192. // Cleanup any state created by overlay which should be cleaned when daemon
  193. // is being shutdown. For now, we just have to unmount the bind mounted
  194. // we had created.
  195. func (d *Driver) Cleanup() error {
  196. return mount.Unmount(d.home)
  197. }
  198. // CreateReadWrite creates a layer that is writable for use as a container
  199. // file system.
  200. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  201. return d.Create(id, parent, opts)
  202. }
  203. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  204. // The parent filesystem is used to configure these directories for the overlay.
  205. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  206. if opts != nil && len(opts.StorageOpt) != 0 {
  207. return fmt.Errorf("--storage-opt is not supported for overlay")
  208. }
  209. dir := d.dir(id)
  210. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  211. if err != nil {
  212. return err
  213. }
  214. if err := idtools.MkdirAllAs(path.Dir(dir), 0700, rootUID, rootGID); err != nil {
  215. return err
  216. }
  217. if err := idtools.MkdirAs(dir, 0700, rootUID, rootGID); err != nil {
  218. return err
  219. }
  220. defer func() {
  221. // Clean up on failure
  222. if retErr != nil {
  223. os.RemoveAll(dir)
  224. }
  225. }()
  226. // Toplevel images are just a "root" dir
  227. if parent == "" {
  228. if err := idtools.MkdirAs(path.Join(dir, "root"), 0755, rootUID, rootGID); err != nil {
  229. return err
  230. }
  231. return nil
  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.MkdirAs(path.Join(dir, "upper"), s.Mode(), rootUID, rootGID); err != nil {
  242. return err
  243. }
  244. if err := idtools.MkdirAs(path.Join(dir, "work"), 0700, rootUID, rootGID); err != nil {
  245. return err
  246. }
  247. if err := idtools.MkdirAs(path.Join(dir, "merged"), 0700, rootUID, rootGID); 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.MkdirAs(upperDir, s.Mode(), rootUID, rootGID); err != nil {
  270. return err
  271. }
  272. if err := idtools.MkdirAs(path.Join(dir, "work"), 0700, rootUID, rootGID); err != nil {
  273. return err
  274. }
  275. if err := idtools.MkdirAs(path.Join(dir, "merged"), 0700, rootUID, rootGID); err != nil {
  276. return err
  277. }
  278. return copyDir(parentUpperDir, upperDir, 0)
  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 string, mountLabel string) (s string, 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 "", 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 rootDir, nil
  301. }
  302. mergedDir := path.Join(dir, "merged")
  303. if count := d.ctr.Increment(mergedDir); count > 1 {
  304. return mergedDir, nil
  305. }
  306. defer func() {
  307. if err != nil {
  308. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  309. syscall.Unmount(mergedDir, 0)
  310. }
  311. }
  312. }()
  313. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  314. if err != nil {
  315. return "", 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 := syscall.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
  324. return "", 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 "", err
  331. }
  332. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  333. return "", err
  334. }
  335. return 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 := syscall.Unmount(mountpoint, 0); 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 = copyDir(parentRootDir, tmpRootDir, copyHardlink); 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. }