zfs.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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/idtools"
  16. "github.com/docker/docker/pkg/mount"
  17. "github.com/docker/docker/pkg/parsers"
  18. zfs "github.com/mistifyio/go-zfs"
  19. "github.com/opencontainers/runc/libcontainer/label"
  20. )
  21. type zfsOptions struct {
  22. fsName string
  23. mountPath string
  24. }
  25. func init() {
  26. graphdriver.Register("zfs", Init)
  27. }
  28. // Logger returns a zfs logger implementation.
  29. type Logger struct{}
  30. // Log wraps log message from ZFS driver with a prefix '[zfs]'.
  31. func (*Logger) Log(cmd []string) {
  32. logrus.Debugf("[zfs] %s", strings.Join(cmd, " "))
  33. }
  34. // Init returns a new ZFS driver.
  35. // It takes base mount path and a array of options which are represented as key value pairs.
  36. // Each option is in the for key=value. 'zfs.fsname' is expected to be a valid key in the options.
  37. func Init(base string, opt []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  38. var err error
  39. if _, err := exec.LookPath("zfs"); err != nil {
  40. logrus.Debugf("[zfs] zfs command is not available: %v", err)
  41. return nil, graphdriver.ErrPrerequisites
  42. }
  43. file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 600)
  44. if err != nil {
  45. logrus.Debugf("[zfs] cannot open /dev/zfs: %v", err)
  46. return nil, graphdriver.ErrPrerequisites
  47. }
  48. defer file.Close()
  49. options, err := parseOptions(opt)
  50. if err != nil {
  51. return nil, err
  52. }
  53. options.mountPath = base
  54. rootdir := path.Dir(base)
  55. if options.fsName == "" {
  56. err = checkRootdirFs(rootdir)
  57. if err != nil {
  58. return nil, err
  59. }
  60. }
  61. if options.fsName == "" {
  62. options.fsName, err = lookupZfsDataset(rootdir)
  63. if err != nil {
  64. return nil, err
  65. }
  66. }
  67. zfs.SetLogger(new(Logger))
  68. filesystems, err := zfs.Filesystems(options.fsName)
  69. if err != nil {
  70. return nil, fmt.Errorf("Cannot find root filesystem %s: %v", options.fsName, err)
  71. }
  72. filesystemsCache := make(map[string]bool, len(filesystems))
  73. var rootDataset *zfs.Dataset
  74. for _, fs := range filesystems {
  75. if fs.Name == options.fsName {
  76. rootDataset = fs
  77. }
  78. filesystemsCache[fs.Name] = true
  79. }
  80. if rootDataset == nil {
  81. return nil, fmt.Errorf("BUG: zfs get all -t filesystem -rHp '%s' should contain '%s'", options.fsName, options.fsName)
  82. }
  83. d := &Driver{
  84. dataset: rootDataset,
  85. options: options,
  86. filesystemsCache: filesystemsCache,
  87. uidMaps: uidMaps,
  88. gidMaps: gidMaps,
  89. }
  90. return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil
  91. }
  92. func parseOptions(opt []string) (zfsOptions, error) {
  93. var options zfsOptions
  94. options.fsName = ""
  95. for _, option := range opt {
  96. key, val, err := parsers.ParseKeyValueOpt(option)
  97. if err != nil {
  98. return options, err
  99. }
  100. key = strings.ToLower(key)
  101. switch key {
  102. case "zfs.fsname":
  103. options.fsName = val
  104. default:
  105. return options, fmt.Errorf("Unknown option %s", key)
  106. }
  107. }
  108. return options, nil
  109. }
  110. func lookupZfsDataset(rootdir string) (string, error) {
  111. var stat syscall.Stat_t
  112. if err := syscall.Stat(rootdir, &stat); err != nil {
  113. return "", fmt.Errorf("Failed to access '%s': %s", rootdir, err)
  114. }
  115. wantedDev := stat.Dev
  116. mounts, err := mount.GetMounts()
  117. if err != nil {
  118. return "", err
  119. }
  120. for _, m := range mounts {
  121. if err := syscall.Stat(m.Mountpoint, &stat); err != nil {
  122. logrus.Debugf("[zfs] failed to stat '%s' while scanning for zfs mount: %v", m.Mountpoint, err)
  123. continue // may fail on fuse file systems
  124. }
  125. if stat.Dev == wantedDev && m.Fstype == "zfs" {
  126. return m.Source, nil
  127. }
  128. }
  129. return "", fmt.Errorf("Failed to find zfs dataset mounted on '%s' in /proc/mounts", rootdir)
  130. }
  131. // Driver holds information about the driver, such as zfs dataset, options and cache.
  132. type Driver struct {
  133. dataset *zfs.Dataset
  134. options zfsOptions
  135. sync.Mutex // protects filesystem cache against concurrent access
  136. filesystemsCache map[string]bool
  137. uidMaps []idtools.IDMap
  138. gidMaps []idtools.IDMap
  139. }
  140. func (d *Driver) String() string {
  141. return "zfs"
  142. }
  143. // Cleanup is used to implement graphdriver.ProtoDriver. There is no cleanup required for this driver.
  144. func (d *Driver) Cleanup() error {
  145. return nil
  146. }
  147. // Status returns information about the ZFS filesystem. It returns a two dimensional array of information
  148. // such as pool name, dataset name, disk usage, parent quota and compression used.
  149. // Currently it return 'Zpool', 'Zpool Health', 'Parent Dataset', 'Space Used By Parent',
  150. // 'Space Available', 'Parent Quota' and 'Compression'.
  151. func (d *Driver) Status() [][2]string {
  152. parts := strings.Split(d.dataset.Name, "/")
  153. pool, err := zfs.GetZpool(parts[0])
  154. var poolName, poolHealth string
  155. if err == nil {
  156. poolName = pool.Name
  157. poolHealth = pool.Health
  158. } else {
  159. poolName = fmt.Sprintf("error while getting pool information %v", err)
  160. poolHealth = "not available"
  161. }
  162. quota := "no"
  163. if d.dataset.Quota != 0 {
  164. quota = strconv.FormatUint(d.dataset.Quota, 10)
  165. }
  166. return [][2]string{
  167. {"Zpool", poolName},
  168. {"Zpool Health", poolHealth},
  169. {"Parent Dataset", d.dataset.Name},
  170. {"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
  171. {"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
  172. {"Parent Quota", quota},
  173. {"Compression", d.dataset.Compression},
  174. }
  175. }
  176. // GetMetadata returns image/container metadata related to graph driver
  177. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  178. return nil, nil
  179. }
  180. func (d *Driver) cloneFilesystem(name, parentName string) error {
  181. snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond())
  182. parentDataset := zfs.Dataset{Name: parentName}
  183. snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
  184. if err != nil {
  185. return err
  186. }
  187. _, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"})
  188. if err == nil {
  189. d.Lock()
  190. d.filesystemsCache[name] = true
  191. d.Unlock()
  192. }
  193. if err != nil {
  194. snapshot.Destroy(zfs.DestroyDeferDeletion)
  195. return err
  196. }
  197. return snapshot.Destroy(zfs.DestroyDeferDeletion)
  198. }
  199. func (d *Driver) zfsPath(id string) string {
  200. return d.options.fsName + "/" + id
  201. }
  202. func (d *Driver) mountPath(id string) string {
  203. return path.Join(d.options.mountPath, "graph", getMountpoint(id))
  204. }
  205. // Create prepares the dataset and filesystem for the ZFS driver for the given id under the parent.
  206. func (d *Driver) Create(id string, parent string, mountLabel string, storageOpt map[string]string) error {
  207. if len(storageOpt) != 0 {
  208. return fmt.Errorf("--storage-opt is not supported for zfs")
  209. }
  210. err := d.create(id, parent)
  211. if err == nil {
  212. return nil
  213. }
  214. if zfsError, ok := err.(*zfs.Error); ok {
  215. if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
  216. return err
  217. }
  218. // aborted build -> cleanup
  219. } else {
  220. return err
  221. }
  222. dataset := zfs.Dataset{Name: d.zfsPath(id)}
  223. if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
  224. return err
  225. }
  226. // retry
  227. return d.create(id, parent)
  228. }
  229. func (d *Driver) create(id, parent string) error {
  230. name := d.zfsPath(id)
  231. if parent == "" {
  232. mountoptions := map[string]string{"mountpoint": "legacy"}
  233. fs, err := zfs.CreateFilesystem(name, mountoptions)
  234. if err == nil {
  235. d.Lock()
  236. d.filesystemsCache[fs.Name] = true
  237. d.Unlock()
  238. }
  239. return err
  240. }
  241. return d.cloneFilesystem(name, d.zfsPath(parent))
  242. }
  243. // Remove deletes the dataset, filesystem and the cache for the given id.
  244. func (d *Driver) Remove(id string) error {
  245. name := d.zfsPath(id)
  246. dataset := zfs.Dataset{Name: name}
  247. err := dataset.Destroy(zfs.DestroyRecursive)
  248. if err == nil {
  249. d.Lock()
  250. delete(d.filesystemsCache, name)
  251. d.Unlock()
  252. }
  253. return err
  254. }
  255. // Get returns the mountpoint for the given id after creating the target directories if necessary.
  256. func (d *Driver) Get(id, mountLabel string) (string, error) {
  257. mountpoint := d.mountPath(id)
  258. filesystem := d.zfsPath(id)
  259. options := label.FormatMountLabel("", mountLabel)
  260. logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
  261. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  262. if err != nil {
  263. return "", err
  264. }
  265. // Create the target directories if they don't exist
  266. if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil {
  267. return "", err
  268. }
  269. if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
  270. return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
  271. }
  272. // this could be our first mount after creation of the filesystem, and the root dir may still have root
  273. // permissions instead of the remapped root uid:gid (if user namespaces are enabled):
  274. if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
  275. return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
  276. }
  277. return mountpoint, nil
  278. }
  279. // Put removes the existing mountpoint for the given id if it exists.
  280. func (d *Driver) Put(id string) error {
  281. mountpoint := d.mountPath(id)
  282. mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint)
  283. if err != nil || !mounted {
  284. return err
  285. }
  286. logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
  287. if err := mount.Unmount(mountpoint); err != nil {
  288. return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
  289. }
  290. return nil
  291. }
  292. // Exists checks to see if the cache entry exists for the given id.
  293. func (d *Driver) Exists(id string) bool {
  294. d.Lock()
  295. defer d.Unlock()
  296. return d.filesystemsCache[d.zfsPath(id)] == true
  297. }