zfs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. //go:build linux || freebsd
  2. package zfs // import "github.com/docker/docker/daemon/graphdriver/zfs"
  3. import (
  4. "context"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/containerd/log"
  14. "github.com/docker/docker/daemon/graphdriver"
  15. "github.com/docker/docker/pkg/idtools"
  16. "github.com/docker/docker/pkg/parsers"
  17. zfs "github.com/mistifyio/go-zfs/v3"
  18. "github.com/moby/locker"
  19. "github.com/moby/sys/mount"
  20. "github.com/moby/sys/mountinfo"
  21. "github.com/opencontainers/selinux/go-selinux/label"
  22. "github.com/pkg/errors"
  23. "golang.org/x/sys/unix"
  24. )
  25. type zfsOptions struct {
  26. fsName string
  27. mountPath string
  28. }
  29. func init() {
  30. graphdriver.Register("zfs", Init)
  31. }
  32. // Logger returns a zfs logger implementation.
  33. type Logger struct{}
  34. // Log wraps log message from ZFS driver with a prefix '[zfs]'.
  35. func (*Logger) Log(cmd []string) {
  36. log.G(context.TODO()).WithField("storage-driver", "zfs").Debugf("[zfs] %s", strings.Join(cmd, " "))
  37. }
  38. // Init returns a new ZFS driver.
  39. // It takes base mount path and an array of options which are represented as key value pairs.
  40. // Each option is in the for key=value. 'zfs.fsname' is expected to be a valid key in the options.
  41. func Init(base string, opt []string, idMap idtools.IdentityMapping) (graphdriver.Driver, error) {
  42. var err error
  43. logger := log.G(context.TODO()).WithField("storage-driver", "zfs")
  44. if _, err := exec.LookPath("zfs"); err != nil {
  45. logger.Debugf("zfs command is not available: %v", err)
  46. return nil, graphdriver.ErrPrerequisites
  47. }
  48. file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 0o600)
  49. if err != nil {
  50. logger.Debugf("cannot open /dev/zfs: %v", err)
  51. return nil, graphdriver.ErrPrerequisites
  52. }
  53. defer file.Close()
  54. options, err := parseOptions(opt)
  55. if err != nil {
  56. return nil, err
  57. }
  58. options.mountPath = base
  59. rootdir := path.Dir(base)
  60. if options.fsName == "" {
  61. err = checkRootdirFs(rootdir)
  62. if err != nil {
  63. return nil, err
  64. }
  65. }
  66. if options.fsName == "" {
  67. options.fsName, err = lookupZfsDataset(rootdir)
  68. if err != nil {
  69. return nil, err
  70. }
  71. }
  72. zfs.SetLogger(new(Logger))
  73. filesystems, err := zfs.Filesystems(options.fsName)
  74. if err != nil {
  75. return nil, fmt.Errorf("Cannot find root filesystem %s: %v", options.fsName, err)
  76. }
  77. filesystemsCache := make(map[string]bool, len(filesystems))
  78. var rootDataset *zfs.Dataset
  79. for _, fs := range filesystems {
  80. if fs.Name == options.fsName {
  81. rootDataset = fs
  82. }
  83. filesystemsCache[fs.Name] = true
  84. }
  85. if rootDataset == nil {
  86. return nil, fmt.Errorf("BUG: zfs get all -t filesystem -rHp '%s' should contain '%s'", options.fsName, options.fsName)
  87. }
  88. dirID := idtools.Identity{
  89. UID: idtools.CurrentIdentity().UID,
  90. GID: idMap.RootPair().GID,
  91. }
  92. if err := idtools.MkdirAllAndChown(base, 0o710, dirID); err != nil {
  93. return nil, fmt.Errorf("Failed to create '%s': %v", base, err)
  94. }
  95. d := &Driver{
  96. dataset: rootDataset,
  97. options: options,
  98. filesystemsCache: filesystemsCache,
  99. idMap: idMap,
  100. ctr: graphdriver.NewRefCounter(graphdriver.NewDefaultChecker()),
  101. locker: locker.New(),
  102. }
  103. return graphdriver.NewNaiveDiffDriver(d, idMap), nil
  104. }
  105. func parseOptions(opt []string) (zfsOptions, error) {
  106. var options zfsOptions
  107. options.fsName = ""
  108. for _, option := range opt {
  109. key, val, err := parsers.ParseKeyValueOpt(option)
  110. if err != nil {
  111. return options, err
  112. }
  113. key = strings.ToLower(key)
  114. switch key {
  115. case "zfs.fsname":
  116. options.fsName = val
  117. default:
  118. return options, fmt.Errorf("Unknown option %s", key)
  119. }
  120. }
  121. return options, nil
  122. }
  123. func lookupZfsDataset(rootdir string) (string, error) {
  124. var stat unix.Stat_t
  125. if err := unix.Stat(rootdir, &stat); err != nil {
  126. return "", fmt.Errorf("Failed to access '%s': %s", rootdir, err)
  127. }
  128. wantedDev := stat.Dev
  129. mounts, err := mountinfo.GetMounts(nil)
  130. if err != nil {
  131. return "", err
  132. }
  133. for _, m := range mounts {
  134. if err := unix.Stat(m.Mountpoint, &stat); err != nil {
  135. log.G(context.TODO()).WithField("storage-driver", "zfs").Debugf("failed to stat '%s' while scanning for zfs mount: %v", m.Mountpoint, err)
  136. continue // may fail on fuse file systems
  137. }
  138. if stat.Dev == wantedDev && m.FSType == "zfs" {
  139. return m.Source, nil
  140. }
  141. }
  142. return "", fmt.Errorf("Failed to find zfs dataset mounted on '%s' in /proc/mounts", rootdir)
  143. }
  144. // Driver holds information about the driver, such as zfs dataset, options and cache.
  145. type Driver struct {
  146. dataset *zfs.Dataset
  147. options zfsOptions
  148. sync.Mutex // protects filesystem cache against concurrent access
  149. filesystemsCache map[string]bool
  150. idMap idtools.IdentityMapping
  151. ctr *graphdriver.RefCounter
  152. locker *locker.Locker
  153. }
  154. func (d *Driver) String() string {
  155. return "zfs"
  156. }
  157. // Cleanup is called on daemon shutdown, it is a no-op for ZFS.
  158. // TODO(@cpuguy83): Walk layer tree and check mounts?
  159. func (d *Driver) Cleanup() error {
  160. return nil
  161. }
  162. // Status returns information about the ZFS filesystem. It returns a two dimensional array of information
  163. // such as pool name, dataset name, disk usage, parent quota and compression used.
  164. // Currently it return 'Zpool', 'Zpool Health', 'Parent Dataset', 'Space Used By Parent',
  165. // 'Space Available', 'Parent Quota' and 'Compression'.
  166. func (d *Driver) Status() [][2]string {
  167. parts := strings.Split(d.dataset.Name, "/")
  168. pool, err := zfs.GetZpool(parts[0])
  169. var poolName, poolHealth string
  170. if err == nil {
  171. poolName = pool.Name
  172. poolHealth = pool.Health
  173. } else {
  174. poolName = fmt.Sprintf("error while getting pool information %v", err)
  175. poolHealth = "not available"
  176. }
  177. quota := "no"
  178. if d.dataset.Quota != 0 {
  179. quota = strconv.FormatUint(d.dataset.Quota, 10)
  180. }
  181. return [][2]string{
  182. {"Zpool", poolName},
  183. {"Zpool Health", poolHealth},
  184. {"Parent Dataset", d.dataset.Name},
  185. {"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
  186. {"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
  187. {"Parent Quota", quota},
  188. {"Compression", d.dataset.Compression},
  189. }
  190. }
  191. // GetMetadata returns image/container metadata related to graph driver
  192. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  193. return map[string]string{
  194. "Mountpoint": d.mountPath(id),
  195. "Dataset": d.zfsPath(id),
  196. }, nil
  197. }
  198. func (d *Driver) cloneFilesystem(name, parentName string) error {
  199. snapshotName := strconv.Itoa(time.Now().Nanosecond())
  200. parentDataset := zfs.Dataset{Name: parentName}
  201. snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
  202. if err != nil {
  203. return err
  204. }
  205. _, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"})
  206. if err == nil {
  207. d.Lock()
  208. d.filesystemsCache[name] = true
  209. d.Unlock()
  210. }
  211. if err != nil {
  212. snapshot.Destroy(zfs.DestroyDeferDeletion)
  213. return err
  214. }
  215. return snapshot.Destroy(zfs.DestroyDeferDeletion)
  216. }
  217. func (d *Driver) zfsPath(id string) string {
  218. return d.options.fsName + "/" + id
  219. }
  220. func (d *Driver) mountPath(id string) string {
  221. return path.Join(d.options.mountPath, "graph", getMountpoint(id))
  222. }
  223. // CreateReadWrite creates a layer that is writable for use as a container
  224. // file system.
  225. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  226. return d.Create(id, parent, opts)
  227. }
  228. // Create prepares the dataset and filesystem for the ZFS driver for the given id under the parent.
  229. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
  230. var storageOpt map[string]string
  231. if opts != nil {
  232. storageOpt = opts.StorageOpt
  233. }
  234. err := d.create(id, parent, storageOpt)
  235. if err == nil {
  236. return nil
  237. }
  238. if zfsError, ok := err.(*zfs.Error); ok {
  239. if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
  240. return err
  241. }
  242. // aborted build -> cleanup
  243. } else {
  244. return err
  245. }
  246. dataset := zfs.Dataset{Name: d.zfsPath(id)}
  247. if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
  248. return err
  249. }
  250. // retry
  251. return d.create(id, parent, storageOpt)
  252. }
  253. func (d *Driver) create(id, parent string, storageOpt map[string]string) error {
  254. name := d.zfsPath(id)
  255. quota, err := parseStorageOpt(storageOpt)
  256. if err != nil {
  257. return err
  258. }
  259. if parent == "" {
  260. mountoptions := map[string]string{"mountpoint": "legacy"}
  261. fs, err := zfs.CreateFilesystem(name, mountoptions)
  262. if err == nil {
  263. err = setQuota(name, quota)
  264. if err == nil {
  265. d.Lock()
  266. d.filesystemsCache[fs.Name] = true
  267. d.Unlock()
  268. }
  269. }
  270. return err
  271. }
  272. err = d.cloneFilesystem(name, d.zfsPath(parent))
  273. if err == nil {
  274. err = setQuota(name, quota)
  275. }
  276. return err
  277. }
  278. func parseStorageOpt(storageOpt map[string]string) (string, error) {
  279. // Read size to change the disk quota per container
  280. for k, v := range storageOpt {
  281. key := strings.ToLower(k)
  282. switch key {
  283. case "size":
  284. return v, nil
  285. default:
  286. return "0", fmt.Errorf("Unknown option %s", key)
  287. }
  288. }
  289. return "0", nil
  290. }
  291. func setQuota(name string, quota string) error {
  292. if quota == "0" {
  293. return nil
  294. }
  295. fs, err := zfs.GetDataset(name)
  296. if err != nil {
  297. return err
  298. }
  299. return fs.SetProperty("quota", quota)
  300. }
  301. // Remove deletes the dataset, filesystem and the cache for the given id.
  302. func (d *Driver) Remove(id string) error {
  303. d.locker.Lock(id)
  304. defer d.locker.Unlock(id)
  305. name := d.zfsPath(id)
  306. dataset := zfs.Dataset{Name: name}
  307. err := dataset.Destroy(zfs.DestroyRecursive)
  308. if err == nil {
  309. d.Lock()
  310. delete(d.filesystemsCache, name)
  311. d.Unlock()
  312. }
  313. return err
  314. }
  315. // Get returns the mountpoint for the given id after creating the target directories if necessary.
  316. func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) {
  317. d.locker.Lock(id)
  318. defer d.locker.Unlock(id)
  319. mountpoint := d.mountPath(id)
  320. if count := d.ctr.Increment(mountpoint); count > 1 {
  321. return mountpoint, nil
  322. }
  323. defer func() {
  324. if retErr != nil {
  325. if c := d.ctr.Decrement(mountpoint); c <= 0 {
  326. if mntErr := unix.Unmount(mountpoint, 0); mntErr != nil {
  327. log.G(context.TODO()).WithField("storage-driver", "zfs").Errorf("Error unmounting %v: %v", mountpoint, mntErr)
  328. }
  329. if rmErr := unix.Rmdir(mountpoint); rmErr != nil && !os.IsNotExist(rmErr) {
  330. log.G(context.TODO()).WithField("storage-driver", "zfs").Debugf("Failed to remove %s: %v", id, rmErr)
  331. }
  332. }
  333. }
  334. }()
  335. filesystem := d.zfsPath(id)
  336. options := label.FormatMountLabel("", mountLabel)
  337. log.G(context.TODO()).WithField("storage-driver", "zfs").Debugf(`mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
  338. root := d.idMap.RootPair()
  339. // Create the target directories if they don't exist
  340. if err := idtools.MkdirAllAndChown(mountpoint, 0o755, root); err != nil {
  341. return "", err
  342. }
  343. if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
  344. return "", errors.Wrap(err, "error creating zfs mount")
  345. }
  346. // this could be our first mount after creation of the filesystem, and the root dir may still have root
  347. // permissions instead of the remapped root uid:gid (if user namespaces are enabled):
  348. if err := root.Chown(mountpoint); err != nil {
  349. return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
  350. }
  351. return mountpoint, nil
  352. }
  353. // Put removes the existing mountpoint for the given id if it exists.
  354. func (d *Driver) Put(id string) error {
  355. d.locker.Lock(id)
  356. defer d.locker.Unlock(id)
  357. mountpoint := d.mountPath(id)
  358. if count := d.ctr.Decrement(mountpoint); count > 0 {
  359. return nil
  360. }
  361. logger := log.G(context.TODO()).WithField("storage-driver", "zfs")
  362. logger.Debugf(`unmount("%s")`, mountpoint)
  363. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  364. logger.Warnf("Failed to unmount %s mount %s: %v", id, mountpoint, err)
  365. }
  366. if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) {
  367. logger.Debugf("Failed to remove %s mount point %s: %v", id, mountpoint, err)
  368. }
  369. return nil
  370. }
  371. // Exists checks to see if the cache entry exists for the given id.
  372. func (d *Driver) Exists(id string) bool {
  373. d.Lock()
  374. defer d.Unlock()
  375. return d.filesystemsCache[d.zfsPath(id)]
  376. }