github.com/ph/moby@v1.13.1/daemon/graphdriver/zfs/zfs.go (about)

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