filesystem.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package docker
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "syscall"
  7. )
  8. type Filesystem struct {
  9. RootFS string
  10. RWPath string
  11. Layers []string
  12. }
  13. func (fs *Filesystem) createMountPoints() error {
  14. if err := os.Mkdir(fs.RootFS, 0700); err != nil && !os.IsExist(err) {
  15. return err
  16. }
  17. if err := os.Mkdir(fs.RWPath, 0700); err != nil && !os.IsExist(err) {
  18. return err
  19. }
  20. return nil
  21. }
  22. func (fs *Filesystem) Mount() error {
  23. if fs.IsMounted() {
  24. return errors.New("Mount: Filesystem already mounted")
  25. }
  26. if err := fs.createMountPoints(); err != nil {
  27. return err
  28. }
  29. rwBranch := fmt.Sprintf("%v=rw", fs.RWPath)
  30. roBranches := ""
  31. for _, layer := range fs.Layers {
  32. roBranches += fmt.Sprintf("%v=ro:", layer)
  33. }
  34. branches := fmt.Sprintf("br:%v:%v", rwBranch, roBranches)
  35. return syscall.Mount("none", fs.RootFS, "aufs", 0, branches)
  36. }
  37. func (fs *Filesystem) Umount() error {
  38. if !fs.IsMounted() {
  39. return errors.New("Umount: Filesystem not mounted")
  40. }
  41. return syscall.Unmount(fs.RootFS, 0)
  42. }
  43. func (fs *Filesystem) IsMounted() bool {
  44. f, err := os.Open(fs.RootFS)
  45. if err != nil {
  46. if os.IsNotExist(err) {
  47. return false
  48. }
  49. panic(err)
  50. }
  51. list, err := f.Readdirnames(1)
  52. f.Close()
  53. if err != nil {
  54. return false
  55. }
  56. if len(list) > 0 {
  57. return true
  58. }
  59. return false
  60. }
  61. func newFilesystem(rootfs string, rwpath string, layers []string) *Filesystem {
  62. return &Filesystem{
  63. RootFS: rootfs,
  64. RWPath: rwpath,
  65. Layers: layers,
  66. }
  67. }