zfs.go 6.8 KB

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