zfs.go 7.1 KB

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