overlay.go 13 KB

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