zfs.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package zfs
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "path"
  7. "strconv"
  8. "strings"
  9. "syscall"
  10. "time"
  11. log "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/daemon/graphdriver"
  13. "github.com/docker/docker/pkg/mount"
  14. "github.com/docker/docker/pkg/parsers"
  15. zfs "github.com/mistifyio/go-zfs"
  16. )
  17. type ZfsOptions struct {
  18. fsName string
  19. mountPath string
  20. }
  21. func init() {
  22. graphdriver.Register("zfs", Init)
  23. }
  24. type Logger struct{}
  25. func (*Logger) Log(cmd []string) {
  26. log.Debugf("[zfs] %s", strings.Join(cmd, " "))
  27. }
  28. func Init(base string, opt []string) (graphdriver.Driver, error) {
  29. var err error
  30. options, err := parseOptions(opt)
  31. if err != nil {
  32. return nil, err
  33. }
  34. options.mountPath = base
  35. rootdir := path.Dir(base)
  36. if options.fsName == "" {
  37. err = checkRootdirFs(rootdir)
  38. if err != nil {
  39. return nil, err
  40. }
  41. }
  42. if _, err := exec.LookPath("zfs"); err != nil {
  43. return nil, fmt.Errorf("zfs command is not available: %v", err)
  44. }
  45. file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 600)
  46. if err != nil {
  47. return nil, fmt.Errorf("cannot open /dev/zfs: %v", err)
  48. }
  49. defer file.Close()
  50. if options.fsName == "" {
  51. options.fsName, err = lookupZfsDataset(rootdir)
  52. if err != nil {
  53. return nil, err
  54. }
  55. }
  56. zfs.SetLogger(new(Logger))
  57. dataset, err := zfs.GetDataset(options.fsName)
  58. if err != nil {
  59. return nil, fmt.Errorf("Cannot open %s", options.fsName)
  60. }
  61. d := &Driver{
  62. dataset: dataset,
  63. options: options,
  64. }
  65. return graphdriver.NaiveDiffDriver(d), nil
  66. }
  67. func parseOptions(opt []string) (ZfsOptions, error) {
  68. var options ZfsOptions
  69. options.fsName = ""
  70. for _, option := range opt {
  71. key, val, err := parsers.ParseKeyValueOpt(option)
  72. if err != nil {
  73. return options, err
  74. }
  75. key = strings.ToLower(key)
  76. switch key {
  77. case "zfs.fsname":
  78. options.fsName = val
  79. default:
  80. return options, fmt.Errorf("Unknown option %s", key)
  81. }
  82. }
  83. return options, nil
  84. }
  85. func checkRootdirFs(rootdir string) error {
  86. var buf syscall.Statfs_t
  87. if err := syscall.Statfs(rootdir, &buf); err != nil {
  88. return fmt.Errorf("Failed to access '%s': %s", rootdir, err)
  89. }
  90. if graphdriver.FsMagic(buf.Type) != graphdriver.FsMagicZfs {
  91. log.Debugf("[zfs] no zfs dataset found for rootdir '%s'", rootdir)
  92. return graphdriver.ErrPrerequisites
  93. }
  94. return nil
  95. }
  96. func lookupZfsDataset(rootdir string) (string, error) {
  97. var stat syscall.Stat_t
  98. if err := syscall.Stat(rootdir, &stat); err != nil {
  99. return "", fmt.Errorf("Failed to access '%s': %s", rootdir, err)
  100. }
  101. wantedDev := stat.Dev
  102. mounts, err := mount.GetMounts()
  103. if err != nil {
  104. return "", err
  105. }
  106. for _, m := range mounts {
  107. if err := syscall.Stat(m.Mountpoint, &stat); err != nil {
  108. log.Debugf("[zfs] failed to stat '%s' while scanning for zfs mount: %v", m.Mountpoint, err)
  109. continue // may fail on fuse file systems
  110. }
  111. if stat.Dev == wantedDev && m.Fstype == "zfs" {
  112. return m.Source, nil
  113. }
  114. }
  115. return "", fmt.Errorf("Failed to find zfs dataset mounted on '%s' in /proc/mounts", rootdir)
  116. }
  117. type Driver struct {
  118. dataset *zfs.Dataset
  119. options ZfsOptions
  120. }
  121. func (d *Driver) String() string {
  122. return "zfs"
  123. }
  124. func (d *Driver) Cleanup() error {
  125. return nil
  126. }
  127. func (d *Driver) Status() [][2]string {
  128. parts := strings.Split(d.dataset.Name, "/")
  129. pool, err := zfs.GetZpool(parts[0])
  130. var poolName, poolHealth string
  131. if err == nil {
  132. poolName = pool.Name
  133. poolHealth = pool.Health
  134. } else {
  135. poolName = fmt.Sprintf("error while getting pool information %v", err)
  136. poolHealth = "not available"
  137. }
  138. quota := "no"
  139. if d.dataset.Quota != 0 {
  140. quota = strconv.FormatUint(d.dataset.Quota, 10)
  141. }
  142. return [][2]string{
  143. {"Zpool", poolName},
  144. {"Zpool Health", poolHealth},
  145. {"Parent Dataset", d.dataset.Name},
  146. {"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
  147. {"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
  148. {"Parent Quota", quota},
  149. {"Compression", d.dataset.Compression},
  150. }
  151. }
  152. func cloneFilesystem(name, parentName string) error {
  153. snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond())
  154. parentDataset := zfs.Dataset{Name: parentName}
  155. snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
  156. if err != nil {
  157. return err
  158. }
  159. _, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"})
  160. if err != nil {
  161. snapshot.Destroy(zfs.DestroyDeferDeletion)
  162. return err
  163. }
  164. return snapshot.Destroy(zfs.DestroyDeferDeletion)
  165. }
  166. func (d *Driver) ZfsPath(id string) string {
  167. return d.options.fsName + "/" + id
  168. }
  169. func (d *Driver) MountPath(id string) string {
  170. return path.Join(d.options.mountPath, "graph", id)
  171. }
  172. func (d *Driver) Create(id string, parent string) error {
  173. err := d.create(id, parent)
  174. if err == nil {
  175. return nil
  176. }
  177. if zfsError, ok := err.(*zfs.Error); ok {
  178. if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
  179. return err
  180. }
  181. // aborted build -> cleanup
  182. } else {
  183. return err
  184. }
  185. dataset := zfs.Dataset{Name: d.ZfsPath(id)}
  186. if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
  187. return err
  188. }
  189. // retry
  190. return d.create(id, parent)
  191. }
  192. func (d *Driver) create(id, parent string) error {
  193. name := d.ZfsPath(id)
  194. if parent == "" {
  195. mountoptions := map[string]string{"mountpoint": "legacy"}
  196. _, err := zfs.CreateFilesystem(name, mountoptions)
  197. return err
  198. }
  199. return cloneFilesystem(name, d.ZfsPath(parent))
  200. }
  201. func (d *Driver) Remove(id string) error {
  202. dataset := zfs.Dataset{Name: d.ZfsPath(id)}
  203. return dataset.Destroy(zfs.DestroyRecursive)
  204. }
  205. func (d *Driver) Get(id, mountLabel string) (string, error) {
  206. mountpoint := d.MountPath(id)
  207. filesystem := d.ZfsPath(id)
  208. log.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, mountLabel)
  209. // Create the target directories if they don't exist
  210. if err := os.MkdirAll(mountpoint, 0755); err != nil && !os.IsExist(err) {
  211. return "", err
  212. }
  213. err := mount.Mount(filesystem, mountpoint, "zfs", mountLabel)
  214. if err != nil {
  215. return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
  216. }
  217. return mountpoint, nil
  218. }
  219. func (d *Driver) Put(id string) error {
  220. mountpoint := d.MountPath(id)
  221. log.Debugf(`[zfs] unmount("%s")`, mountpoint)
  222. if err := mount.Unmount(mountpoint); err != nil {
  223. return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
  224. }
  225. return nil
  226. }
  227. func (d *Driver) Exists(id string) bool {
  228. _, err := zfs.GetDataset(d.ZfsPath(id))
  229. return err == nil
  230. }