overlay.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // +build linux
  2. package overlay
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "sync"
  11. "syscall"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/daemon/graphdriver"
  14. "github.com/docker/docker/pkg/archive"
  15. "github.com/docker/docker/pkg/chrootarchive"
  16. "github.com/docker/docker/pkg/idtools"
  17. "github.com/opencontainers/runc/libcontainer/label"
  18. )
  19. // This is a small wrapper over the NaiveDiffWriter that lets us have a custom
  20. // implementation of ApplyDiff()
  21. var (
  22. // ErrApplyDiffFallback is returned to indicate that a normal ApplyDiff is applied as a fallback from Naive diff writer.
  23. ErrApplyDiffFallback = fmt.Errorf("Fall back to normal ApplyDiff")
  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 a overlay layer is created there are two cases, either the
  62. // parent has a "root" dir, then we start out with a 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. // ActiveMount contains information about the count, path and whether is mounted or not.
  75. // This information is part of the Driver, that contains list of active mounts that are part of this overlay.
  76. type ActiveMount struct {
  77. count int
  78. path string
  79. mounted bool
  80. }
  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. sync.Mutex // Protects concurrent modification to active
  85. active map[string]*ActiveMount
  86. uidMaps []idtools.IDMap
  87. gidMaps []idtools.IDMap
  88. }
  89. var backingFs = "<unknown>"
  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 a overlay filesystem is not supported over a 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. // check if they are running over btrfs or aufs
  108. switch fsMagic {
  109. case graphdriver.FsMagicBtrfs:
  110. logrus.Error("'overlay' is not supported over btrfs.")
  111. return nil, graphdriver.ErrIncompatibleFS
  112. case graphdriver.FsMagicAufs:
  113. logrus.Error("'overlay' is not supported over aufs.")
  114. return nil, graphdriver.ErrIncompatibleFS
  115. case graphdriver.FsMagicZfs:
  116. logrus.Error("'overlay' is not supported over zfs.")
  117. return nil, graphdriver.ErrIncompatibleFS
  118. }
  119. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  120. if err != nil {
  121. return nil, err
  122. }
  123. // Create the driver home dir
  124. if err := idtools.MkdirAllAs(home, 0755, rootUID, rootGID); err != nil && !os.IsExist(err) {
  125. return nil, err
  126. }
  127. d := &Driver{
  128. home: home,
  129. active: make(map[string]*ActiveMount),
  130. uidMaps: uidMaps,
  131. gidMaps: gidMaps,
  132. }
  133. return NaiveDiffDriverWithApply(d, uidMaps, gidMaps), nil
  134. }
  135. func supportsOverlay() error {
  136. // We can try to modprobe overlay first before looking at
  137. // proc/filesystems for when overlay is supported
  138. exec.Command("modprobe", "overlay").Run()
  139. f, err := os.Open("/proc/filesystems")
  140. if err != nil {
  141. return err
  142. }
  143. defer f.Close()
  144. s := bufio.NewScanner(f)
  145. for s.Scan() {
  146. if s.Text() == "nodev\toverlay" {
  147. return nil
  148. }
  149. }
  150. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  151. return graphdriver.ErrNotSupported
  152. }
  153. func (d *Driver) String() string {
  154. return "overlay"
  155. }
  156. // Status returns current driver information in a two dimensional string array.
  157. // Output contains "Backing Filesystem" used in this implementation.
  158. func (d *Driver) Status() [][2]string {
  159. return [][2]string{
  160. {"Backing Filesystem", backingFs},
  161. }
  162. }
  163. // GetMetadata returns meta data about the overlay driver such as root, LowerDir, UpperDir, WorkDir and MergeDir used to store data.
  164. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  165. dir := d.dir(id)
  166. if _, err := os.Stat(dir); err != nil {
  167. return nil, err
  168. }
  169. metadata := make(map[string]string)
  170. // If id has a root, it is an image
  171. rootDir := path.Join(dir, "root")
  172. if _, err := os.Stat(rootDir); err == nil {
  173. metadata["RootDir"] = rootDir
  174. return metadata, nil
  175. }
  176. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  177. if err != nil {
  178. return nil, err
  179. }
  180. metadata["LowerDir"] = path.Join(d.dir(string(lowerID)), "root")
  181. metadata["UpperDir"] = path.Join(dir, "upper")
  182. metadata["WorkDir"] = path.Join(dir, "work")
  183. metadata["MergedDir"] = path.Join(dir, "merged")
  184. return metadata, nil
  185. }
  186. // Cleanup simply returns nil and do not change the existing filesystem.
  187. // This is required to satisfy the graphdriver.Driver interface.
  188. func (d *Driver) Cleanup() error {
  189. return nil
  190. }
  191. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  192. // The parent filesystem is used to configure these directories for the overlay.
  193. func (d *Driver) Create(id, parent, mountLabel string) (retErr error) {
  194. dir := d.dir(id)
  195. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  196. if err != nil {
  197. return err
  198. }
  199. if err := idtools.MkdirAllAs(path.Dir(dir), 0700, rootUID, rootGID); err != nil {
  200. return err
  201. }
  202. if err := idtools.MkdirAs(dir, 0700, rootUID, rootGID); err != nil {
  203. return err
  204. }
  205. defer func() {
  206. // Clean up on failure
  207. if retErr != nil {
  208. os.RemoveAll(dir)
  209. }
  210. }()
  211. // Toplevel images are just a "root" dir
  212. if parent == "" {
  213. if err := idtools.MkdirAs(path.Join(dir, "root"), 0755, rootUID, rootGID); err != nil {
  214. return err
  215. }
  216. return nil
  217. }
  218. parentDir := d.dir(parent)
  219. // Ensure parent exists
  220. if _, err := os.Lstat(parentDir); err != nil {
  221. return err
  222. }
  223. // If parent has a root, just do a overlay to it
  224. parentRoot := path.Join(parentDir, "root")
  225. if s, err := os.Lstat(parentRoot); err == nil {
  226. if err := idtools.MkdirAs(path.Join(dir, "upper"), s.Mode(), rootUID, rootGID); err != nil {
  227. return err
  228. }
  229. if err := idtools.MkdirAs(path.Join(dir, "work"), 0700, rootUID, rootGID); err != nil {
  230. return err
  231. }
  232. if err := idtools.MkdirAs(path.Join(dir, "merged"), 0700, rootUID, rootGID); err != nil {
  233. return err
  234. }
  235. if err := ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666); err != nil {
  236. return err
  237. }
  238. return nil
  239. }
  240. // Otherwise, copy the upper and the lower-id from the parent
  241. lowerID, err := ioutil.ReadFile(path.Join(parentDir, "lower-id"))
  242. if err != nil {
  243. return err
  244. }
  245. if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerID, 0666); err != nil {
  246. return err
  247. }
  248. parentUpperDir := path.Join(parentDir, "upper")
  249. s, err := os.Lstat(parentUpperDir)
  250. if err != nil {
  251. return err
  252. }
  253. upperDir := path.Join(dir, "upper")
  254. if err := idtools.MkdirAs(upperDir, s.Mode(), rootUID, rootGID); err != nil {
  255. return err
  256. }
  257. if err := idtools.MkdirAs(path.Join(dir, "work"), 0700, rootUID, rootGID); err != nil {
  258. return err
  259. }
  260. if err := idtools.MkdirAs(path.Join(dir, "merged"), 0700, rootUID, rootGID); err != nil {
  261. return err
  262. }
  263. return copyDir(parentUpperDir, upperDir, 0)
  264. }
  265. func (d *Driver) dir(id string) string {
  266. return path.Join(d.home, id)
  267. }
  268. // Remove cleans the directories that are created for this id.
  269. func (d *Driver) Remove(id string) error {
  270. if err := os.RemoveAll(d.dir(id)); err != nil && !os.IsNotExist(err) {
  271. return err
  272. }
  273. return nil
  274. }
  275. // Get creates and mounts the required file system for the given id and returns the mount path.
  276. func (d *Driver) Get(id string, mountLabel string) (string, error) {
  277. // Protect the d.active from concurrent access
  278. d.Lock()
  279. defer d.Unlock()
  280. mount := d.active[id]
  281. if mount != nil {
  282. mount.count++
  283. return mount.path, nil
  284. }
  285. mount = &ActiveMount{count: 1}
  286. dir := d.dir(id)
  287. if _, err := os.Stat(dir); err != nil {
  288. return "", err
  289. }
  290. // If id has a root, just return it
  291. rootDir := path.Join(dir, "root")
  292. if _, err := os.Stat(rootDir); err == nil {
  293. mount.path = rootDir
  294. d.active[id] = mount
  295. return mount.path, nil
  296. }
  297. lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  298. if err != nil {
  299. return "", err
  300. }
  301. lowerDir := path.Join(d.dir(string(lowerID)), "root")
  302. upperDir := path.Join(dir, "upper")
  303. workDir := path.Join(dir, "work")
  304. mergedDir := path.Join(dir, "merged")
  305. opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
  306. if err := syscall.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
  307. return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  308. }
  309. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  310. // user namespace requires this to move a directory from lower to upper.
  311. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  312. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  313. return "", err
  314. }
  315. mount.path = mergedDir
  316. mount.mounted = true
  317. d.active[id] = mount
  318. return mount.path, nil
  319. }
  320. // Put unmounts the mount path created for the give id.
  321. func (d *Driver) Put(id string) error {
  322. // Protect the d.active from concurrent access
  323. d.Lock()
  324. defer d.Unlock()
  325. mount := d.active[id]
  326. if mount == nil {
  327. logrus.Debugf("Put on a non-mounted device %s", id)
  328. // but it might be still here
  329. if d.Exists(id) {
  330. mergedDir := path.Join(d.dir(id), "merged")
  331. err := syscall.Unmount(mergedDir, 0)
  332. if err != nil {
  333. logrus.Debugf("Failed to unmount %s overlay: %v", id, err)
  334. }
  335. }
  336. return nil
  337. }
  338. mount.count--
  339. if mount.count > 0 {
  340. return nil
  341. }
  342. defer delete(d.active, id)
  343. if mount.mounted {
  344. err := syscall.Unmount(mount.path, 0)
  345. if err != nil {
  346. logrus.Debugf("Failed to unmount %s overlay: %v", id, err)
  347. }
  348. return 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 a ErrApplyDiffFallback error.
  353. func (d *Driver) ApplyDiff(id string, parent string, diff archive.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 = chrootarchive.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. }