github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/daemon/graphdriver/zfs/zfs.go (about)

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