overlayfs.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // +build linux
  2. package overlayfs
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. log "github.com/Sirupsen/logrus"
  14. "github.com/docker/docker/daemon/graphdriver"
  15. "github.com/docker/docker/pkg/archive"
  16. "github.com/docker/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 = fmt.Errorf("Fall back to normal ApplyDiff")
  22. )
  23. type ApplyDiffProtoDriver interface {
  24. graphdriver.ProtoDriver
  25. ApplyDiff(id, parent string, diff archive.ArchiveReader) (bytes int64, err error)
  26. }
  27. type naiveDiffDriverWithApply struct {
  28. graphdriver.Driver
  29. applyDiff ApplyDiffProtoDriver
  30. }
  31. func NaiveDiffDriverWithApply(driver ApplyDiffProtoDriver) graphdriver.Driver {
  32. return &naiveDiffDriverWithApply{
  33. Driver: graphdriver.NaiveDiffDriver(driver),
  34. applyDiff: driver,
  35. }
  36. }
  37. func (d *naiveDiffDriverWithApply) ApplyDiff(id, parent string, diff archive.ArchiveReader) (int64, error) {
  38. b, err := d.applyDiff.ApplyDiff(id, parent, diff)
  39. if err == ErrApplyDiffFallback {
  40. return d.Driver.ApplyDiff(id, parent, diff)
  41. }
  42. return b, err
  43. }
  44. // This backend uses the overlayfs union filesystem for containers
  45. // plus hard link file sharing for images.
  46. // Each container/image can have a "root" subdirectory which is a plain
  47. // filesystem hierarchy, or they can use overlayfs.
  48. // If they use overlayfs there is a "upper" directory and a "lower-id"
  49. // file, as well as "merged" and "work" directories. The "upper"
  50. // directory has the upper layer of the overlay, and "lower-id" contains
  51. // the id of the parent whose "root" directory shall be used as the lower
  52. // layer in the overlay. The overlay itself is mounted in the "merged"
  53. // directory, and the "work" dir is needed for overlayfs to work.
  54. // When a overlay layer is created there are two cases, either the
  55. // parent has a "root" dir, then we start out with a empty "upper"
  56. // directory overlaid on the parents root. This is typically the
  57. // case with the init layer of a container which is based on an image.
  58. // If there is no "root" in the parent, we inherit the lower-id from
  59. // the parent and start by making a copy if the parents "upper" dir.
  60. // This is typically the case for a container layer which copies
  61. // its parent -init upper layer.
  62. // Additionally we also have a custom implementation of ApplyLayer
  63. // which makes a recursive copy of the parent "root" layer using
  64. // hardlinks to share file data, and then applies the layer on top
  65. // of that. This means all child images share file (but not directory)
  66. // data with the parent.
  67. type ActiveMount struct {
  68. count int
  69. path string
  70. mounted bool
  71. }
  72. type Driver struct {
  73. home string
  74. sync.Mutex // Protects concurrent modification to active
  75. active map[string]*ActiveMount
  76. }
  77. func init() {
  78. graphdriver.Register("overlayfs", Init)
  79. }
  80. func Init(home string, options []string) (graphdriver.Driver, error) {
  81. if err := supportsOverlayfs(); err != nil {
  82. return nil, graphdriver.ErrNotSupported
  83. }
  84. // Create the driver home dir
  85. if err := os.MkdirAll(home, 0755); err != nil && !os.IsExist(err) {
  86. return nil, err
  87. }
  88. d := &Driver{
  89. home: home,
  90. active: make(map[string]*ActiveMount),
  91. }
  92. return NaiveDiffDriverWithApply(d), nil
  93. }
  94. func supportsOverlayfs() error {
  95. // We can try to modprobe overlayfs first before looking at
  96. // proc/filesystems for when overlayfs is supported
  97. exec.Command("modprobe", "overlayfs").Run()
  98. f, err := os.Open("/proc/filesystems")
  99. if err != nil {
  100. return err
  101. }
  102. defer f.Close()
  103. s := bufio.NewScanner(f)
  104. for s.Scan() {
  105. if strings.Contains(s.Text(), "overlayfs") {
  106. return nil
  107. }
  108. }
  109. log.Error("'overlayfs' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlayfs support loaded.")
  110. return graphdriver.ErrNotSupported
  111. }
  112. func (d *Driver) String() string {
  113. return "overlayfs"
  114. }
  115. func (d *Driver) Status() [][2]string {
  116. return nil
  117. }
  118. func (d *Driver) Cleanup() error {
  119. return nil
  120. }
  121. func (d *Driver) Create(id string, parent string) (retErr error) {
  122. dir := d.dir(id)
  123. if err := os.MkdirAll(path.Dir(dir), 0700); err != nil {
  124. return err
  125. }
  126. if err := os.Mkdir(dir, 0700); err != nil {
  127. return err
  128. }
  129. defer func() {
  130. // Clean up on failure
  131. if retErr != nil {
  132. os.RemoveAll(dir)
  133. }
  134. }()
  135. // Toplevel images are just a "root" dir
  136. if parent == "" {
  137. if err := os.Mkdir(path.Join(dir, "root"), 0755); err != nil {
  138. return err
  139. }
  140. return nil
  141. }
  142. parentDir := d.dir(parent)
  143. // Ensure parent exists
  144. if _, err := os.Lstat(parentDir); err != nil {
  145. return err
  146. }
  147. // If parent has a root, just do a overlayfs to it
  148. parentRoot := path.Join(parentDir, "root")
  149. if s, err := os.Lstat(parentRoot); err == nil {
  150. if err := os.Mkdir(path.Join(dir, "upper"), s.Mode()); err != nil {
  151. return err
  152. }
  153. if err := os.Mkdir(path.Join(dir, "work"), 0700); err != nil {
  154. return err
  155. }
  156. if err := os.Mkdir(path.Join(dir, "merged"), 0700); err != nil {
  157. return err
  158. }
  159. if err := ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666); err != nil {
  160. return err
  161. }
  162. return nil
  163. }
  164. // Otherwise, copy the upper and the lower-id from the parent
  165. lowerId, err := ioutil.ReadFile(path.Join(parentDir, "lower-id"))
  166. if err != nil {
  167. return err
  168. }
  169. if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerId, 0666); err != nil {
  170. return err
  171. }
  172. parentUpperDir := path.Join(parentDir, "upper")
  173. s, err := os.Lstat(parentUpperDir)
  174. if err != nil {
  175. return err
  176. }
  177. upperDir := path.Join(dir, "upper")
  178. if err := os.Mkdir(upperDir, s.Mode()); err != nil {
  179. return err
  180. }
  181. if err := os.Mkdir(path.Join(dir, "work"), 0700); err != nil {
  182. return err
  183. }
  184. if err := os.Mkdir(path.Join(dir, "merged"), 0700); err != nil {
  185. return err
  186. }
  187. return copyDir(parentUpperDir, upperDir, 0)
  188. }
  189. func (d *Driver) dir(id string) string {
  190. return path.Join(d.home, id)
  191. }
  192. func (d *Driver) Remove(id string) error {
  193. dir := d.dir(id)
  194. if _, err := os.Stat(dir); err != nil {
  195. return err
  196. }
  197. return os.RemoveAll(dir)
  198. }
  199. func (d *Driver) Get(id string, mountLabel string) (string, error) {
  200. // Protect the d.active from concurrent access
  201. d.Lock()
  202. defer d.Unlock()
  203. mount := d.active[id]
  204. if mount != nil {
  205. mount.count++
  206. return mount.path, nil
  207. } else {
  208. mount = &ActiveMount{count: 1}
  209. }
  210. dir := d.dir(id)
  211. if _, err := os.Stat(dir); err != nil {
  212. return "", err
  213. }
  214. // If id has a root, just return it
  215. rootDir := path.Join(dir, "root")
  216. if _, err := os.Stat(rootDir); err == nil {
  217. mount.path = rootDir
  218. d.active[id] = mount
  219. return mount.path, nil
  220. }
  221. lowerId, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
  222. if err != nil {
  223. return "", err
  224. }
  225. lowerDir := path.Join(d.dir(string(lowerId)), "root")
  226. upperDir := path.Join(dir, "upper")
  227. workDir := path.Join(dir, "work")
  228. mergedDir := path.Join(dir, "merged")
  229. opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
  230. if err := syscall.Mount("overlayfs", mergedDir, "overlayfs", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
  231. return "", err
  232. }
  233. mount.path = mergedDir
  234. mount.mounted = true
  235. d.active[id] = mount
  236. return mount.path, nil
  237. }
  238. func (d *Driver) Put(id string) {
  239. // Protect the d.active from concurrent access
  240. d.Lock()
  241. defer d.Unlock()
  242. mount := d.active[id]
  243. if mount == nil {
  244. log.Debugf("Put on a non-mounted device %s", id)
  245. return
  246. }
  247. mount.count--
  248. if mount.count > 0 {
  249. return
  250. }
  251. if mount.mounted {
  252. if err := syscall.Unmount(mount.path, 0); err != nil {
  253. log.Debugf("Failed to unmount %s overlayfs: %v", id, err)
  254. }
  255. }
  256. delete(d.active, id)
  257. }
  258. func (d *Driver) ApplyDiff(id string, parent string, diff archive.ArchiveReader) (bytes int64, err error) {
  259. dir := d.dir(id)
  260. if parent == "" {
  261. return 0, ErrApplyDiffFallback
  262. }
  263. parentRootDir := path.Join(d.dir(parent), "root")
  264. if _, err := os.Stat(parentRootDir); err != nil {
  265. return 0, ErrApplyDiffFallback
  266. }
  267. // We now know there is a parent, and it has a "root" directory containing
  268. // the full root filesystem. We can just hardlink it and apply the
  269. // layer. This relies on two things:
  270. // 1) ApplyDiff is only run once on a clean (no writes to upper layer) container
  271. // 2) ApplyDiff doesn't do any in-place writes to files (would break hardlinks)
  272. // These are all currently true and are not expected to break
  273. tmpRootDir, err := ioutil.TempDir(dir, "tmproot")
  274. if err != nil {
  275. return 0, err
  276. }
  277. defer func() {
  278. if err != nil {
  279. os.RemoveAll(tmpRootDir)
  280. } else {
  281. os.RemoveAll(path.Join(dir, "upper"))
  282. os.RemoveAll(path.Join(dir, "work"))
  283. os.RemoveAll(path.Join(dir, "merged"))
  284. os.RemoveAll(path.Join(dir, "lower-id"))
  285. }
  286. }()
  287. if err = copyDir(parentRootDir, tmpRootDir, CopyHardlink); err != nil {
  288. return 0, err
  289. }
  290. if err := archive.ApplyLayer(tmpRootDir, diff); err != nil {
  291. return 0, err
  292. }
  293. rootDir := path.Join(dir, "root")
  294. if err := os.Rename(tmpRootDir, rootDir); err != nil {
  295. return 0, err
  296. }
  297. changes, err := archive.ChangesDirs(rootDir, parentRootDir)
  298. if err != nil {
  299. return 0, err
  300. }
  301. return archive.ChangesSize(rootDir, changes), nil
  302. }
  303. func (d *Driver) Exists(id string) bool {
  304. _, err := os.Stat(d.dir(id))
  305. return err == nil
  306. }