github.com/dpiddy/docker@v1.12.2-rc1/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, mountLabel string, storageOpt map[string]string) error {
   259  	return d.Create(id, parent, mountLabel, storageOpt)
   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 string, parent string, mountLabel string, storageOpt map[string]string) error {
   264  	err := d.create(id, parent, storageOpt)
   265  	if err == nil {
   266  		return nil
   267  	}
   268  	if zfsError, ok := err.(*zfs.Error); ok {
   269  		if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
   270  			return err
   271  		}
   272  		// aborted build -> cleanup
   273  	} else {
   274  		return err
   275  	}
   276  
   277  	dataset := zfs.Dataset{Name: d.zfsPath(id)}
   278  	if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
   279  		return err
   280  	}
   281  
   282  	// retry
   283  	return d.create(id, parent, storageOpt)
   284  }
   285  
   286  func (d *Driver) create(id, parent string, storageOpt map[string]string) error {
   287  	name := d.zfsPath(id)
   288  	quota, err := parseStorageOpt(storageOpt)
   289  	if err != nil {
   290  		return err
   291  	}
   292  	if parent == "" {
   293  		mountoptions := map[string]string{"mountpoint": "legacy"}
   294  		fs, err := zfs.CreateFilesystem(name, mountoptions)
   295  		if err == nil {
   296  			err = setQuota(name, quota)
   297  			if err == nil {
   298  				d.Lock()
   299  				d.filesystemsCache[fs.Name] = true
   300  				d.Unlock()
   301  			}
   302  		}
   303  		return err
   304  	}
   305  	err = d.cloneFilesystem(name, d.zfsPath(parent))
   306  	if err == nil {
   307  		err = setQuota(name, quota)
   308  	}
   309  	return err
   310  }
   311  
   312  func parseStorageOpt(storageOpt map[string]string) (string, error) {
   313  	// Read size to change the disk quota per container
   314  	for k, v := range storageOpt {
   315  		key := strings.ToLower(k)
   316  		switch key {
   317  		case "size":
   318  			return v, nil
   319  		default:
   320  			return "0", fmt.Errorf("Unknown option %s", key)
   321  		}
   322  	}
   323  	return "0", nil
   324  }
   325  
   326  func setQuota(name string, quota string) error {
   327  	if quota == "0" {
   328  		return nil
   329  	}
   330  	fs, err := zfs.GetDataset(name)
   331  	if err != nil {
   332  		return err
   333  	}
   334  	return fs.SetProperty("quota", quota)
   335  }
   336  
   337  // Remove deletes the dataset, filesystem and the cache for the given id.
   338  func (d *Driver) Remove(id string) error {
   339  	name := d.zfsPath(id)
   340  	dataset := zfs.Dataset{Name: name}
   341  	err := dataset.Destroy(zfs.DestroyRecursive)
   342  	if err == nil {
   343  		d.Lock()
   344  		delete(d.filesystemsCache, name)
   345  		d.Unlock()
   346  	}
   347  	return err
   348  }
   349  
   350  // Get returns the mountpoint for the given id after creating the target directories if necessary.
   351  func (d *Driver) Get(id, mountLabel string) (string, error) {
   352  	mountpoint := d.mountPath(id)
   353  	if count := d.ctr.Increment(mountpoint); count > 1 {
   354  		return mountpoint, nil
   355  	}
   356  
   357  	filesystem := d.zfsPath(id)
   358  	options := label.FormatMountLabel("", mountLabel)
   359  	logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
   360  
   361  	rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
   362  	if err != nil {
   363  		d.ctr.Decrement(mountpoint)
   364  		return "", err
   365  	}
   366  	// Create the target directories if they don't exist
   367  	if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil {
   368  		d.ctr.Decrement(mountpoint)
   369  		return "", err
   370  	}
   371  
   372  	if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
   373  		d.ctr.Decrement(mountpoint)
   374  		return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
   375  	}
   376  
   377  	// this could be our first mount after creation of the filesystem, and the root dir may still have root
   378  	// permissions instead of the remapped root uid:gid (if user namespaces are enabled):
   379  	if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
   380  		mount.Unmount(mountpoint)
   381  		d.ctr.Decrement(mountpoint)
   382  		return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
   383  	}
   384  
   385  	return mountpoint, nil
   386  }
   387  
   388  // Put removes the existing mountpoint for the given id if it exists.
   389  func (d *Driver) Put(id string) error {
   390  	mountpoint := d.mountPath(id)
   391  	if count := d.ctr.Decrement(mountpoint); count > 0 {
   392  		return nil
   393  	}
   394  	mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint)
   395  	if err != nil || !mounted {
   396  		return err
   397  	}
   398  
   399  	logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
   400  
   401  	if err := mount.Unmount(mountpoint); err != nil {
   402  		return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
   403  	}
   404  	return nil
   405  }
   406  
   407  // Exists checks to see if the cache entry exists for the given id.
   408  func (d *Driver) Exists(id string) bool {
   409  	d.Lock()
   410  	defer d.Unlock()
   411  	return d.filesystemsCache[d.zfsPath(id)] == true
   412  }