zfs.go 7.0 KB

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