github.com/sams1990/dockerrepo@v17.12.1-ce-rc2+incompatible/daemon/graphdriver/zfs/zfs.go (about)

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