github.com/kobeld/docker@v1.12.0-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  	d := &Driver{
   103  		dataset:          rootDataset,
   104  		options:          options,
   105  		filesystemsCache: filesystemsCache,
   106  		uidMaps:          uidMaps,
   107  		gidMaps:          gidMaps,
   108  		ctr:              graphdriver.NewRefCounter(graphdriver.NewDefaultChecker()),
   109  	}
   110  	return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil
   111  }
   112  
   113  func parseOptions(opt []string) (zfsOptions, error) {
   114  	var options zfsOptions
   115  	options.fsName = ""
   116  	for _, option := range opt {
   117  		key, val, err := parsers.ParseKeyValueOpt(option)
   118  		if err != nil {
   119  			return options, err
   120  		}
   121  		key = strings.ToLower(key)
   122  		switch key {
   123  		case "zfs.fsname":
   124  			options.fsName = val
   125  		default:
   126  			return options, fmt.Errorf("Unknown option %s", key)
   127  		}
   128  	}
   129  	return options, nil
   130  }
   131  
   132  func lookupZfsDataset(rootdir string) (string, error) {
   133  	var stat syscall.Stat_t
   134  	if err := syscall.Stat(rootdir, &stat); err != nil {
   135  		return "", fmt.Errorf("Failed to access '%s': %s", rootdir, err)
   136  	}
   137  	wantedDev := stat.Dev
   138  
   139  	mounts, err := mount.GetMounts()
   140  	if err != nil {
   141  		return "", err
   142  	}
   143  	for _, m := range mounts {
   144  		if err := syscall.Stat(m.Mountpoint, &stat); err != nil {
   145  			logrus.Debugf("[zfs] failed to stat '%s' while scanning for zfs mount: %v", m.Mountpoint, err)
   146  			continue // may fail on fuse file systems
   147  		}
   148  
   149  		if stat.Dev == wantedDev && m.Fstype == "zfs" {
   150  			return m.Source, nil
   151  		}
   152  	}
   153  
   154  	return "", fmt.Errorf("Failed to find zfs dataset mounted on '%s' in /proc/mounts", rootdir)
   155  }
   156  
   157  // Driver holds information about the driver, such as zfs dataset, options and cache.
   158  type Driver struct {
   159  	dataset          *zfs.Dataset
   160  	options          zfsOptions
   161  	sync.Mutex       // protects filesystem cache against concurrent access
   162  	filesystemsCache map[string]bool
   163  	uidMaps          []idtools.IDMap
   164  	gidMaps          []idtools.IDMap
   165  	ctr              *graphdriver.RefCounter
   166  }
   167  
   168  func (d *Driver) String() string {
   169  	return "zfs"
   170  }
   171  
   172  // Cleanup is used to implement graphdriver.ProtoDriver. There is no cleanup required for this driver.
   173  func (d *Driver) Cleanup() error {
   174  	return nil
   175  }
   176  
   177  // Status returns information about the ZFS filesystem. It returns a two dimensional array of information
   178  // such as pool name, dataset name, disk usage, parent quota and compression used.
   179  // Currently it return 'Zpool', 'Zpool Health', 'Parent Dataset', 'Space Used By Parent',
   180  // 'Space Available', 'Parent Quota' and 'Compression'.
   181  func (d *Driver) Status() [][2]string {
   182  	parts := strings.Split(d.dataset.Name, "/")
   183  	pool, err := zfs.GetZpool(parts[0])
   184  
   185  	var poolName, poolHealth string
   186  	if err == nil {
   187  		poolName = pool.Name
   188  		poolHealth = pool.Health
   189  	} else {
   190  		poolName = fmt.Sprintf("error while getting pool information %v", err)
   191  		poolHealth = "not available"
   192  	}
   193  
   194  	quota := "no"
   195  	if d.dataset.Quota != 0 {
   196  		quota = strconv.FormatUint(d.dataset.Quota, 10)
   197  	}
   198  
   199  	return [][2]string{
   200  		{"Zpool", poolName},
   201  		{"Zpool Health", poolHealth},
   202  		{"Parent Dataset", d.dataset.Name},
   203  		{"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
   204  		{"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
   205  		{"Parent Quota", quota},
   206  		{"Compression", d.dataset.Compression},
   207  	}
   208  }
   209  
   210  // GetMetadata returns image/container metadata related to graph driver
   211  func (d *Driver) GetMetadata(id string) (map[string]string, error) {
   212  	return nil, nil
   213  }
   214  
   215  func (d *Driver) cloneFilesystem(name, parentName string) error {
   216  	snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond())
   217  	parentDataset := zfs.Dataset{Name: parentName}
   218  	snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
   219  	if err != nil {
   220  		return err
   221  	}
   222  
   223  	_, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"})
   224  	if err == nil {
   225  		d.Lock()
   226  		d.filesystemsCache[name] = true
   227  		d.Unlock()
   228  	}
   229  
   230  	if err != nil {
   231  		snapshot.Destroy(zfs.DestroyDeferDeletion)
   232  		return err
   233  	}
   234  	return snapshot.Destroy(zfs.DestroyDeferDeletion)
   235  }
   236  
   237  func (d *Driver) zfsPath(id string) string {
   238  	return d.options.fsName + "/" + id
   239  }
   240  
   241  func (d *Driver) mountPath(id string) string {
   242  	return path.Join(d.options.mountPath, "graph", getMountpoint(id))
   243  }
   244  
   245  // CreateReadWrite creates a layer that is writable for use as a container
   246  // file system.
   247  func (d *Driver) CreateReadWrite(id, parent, mountLabel string, storageOpt map[string]string) error {
   248  	return d.Create(id, parent, mountLabel, storageOpt)
   249  }
   250  
   251  // Create prepares the dataset and filesystem for the ZFS driver for the given id under the parent.
   252  func (d *Driver) Create(id string, parent string, mountLabel string, storageOpt map[string]string) error {
   253  	err := d.create(id, parent, storageOpt)
   254  	if err == nil {
   255  		return nil
   256  	}
   257  	if zfsError, ok := err.(*zfs.Error); ok {
   258  		if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
   259  			return err
   260  		}
   261  		// aborted build -> cleanup
   262  	} else {
   263  		return err
   264  	}
   265  
   266  	dataset := zfs.Dataset{Name: d.zfsPath(id)}
   267  	if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
   268  		return err
   269  	}
   270  
   271  	// retry
   272  	return d.create(id, parent, storageOpt)
   273  }
   274  
   275  func (d *Driver) create(id, parent string, storageOpt map[string]string) error {
   276  	name := d.zfsPath(id)
   277  	quota, err := parseStorageOpt(storageOpt)
   278  	if err != nil {
   279  		return err
   280  	}
   281  	if parent == "" {
   282  		mountoptions := map[string]string{"mountpoint": "legacy"}
   283  		fs, err := zfs.CreateFilesystem(name, mountoptions)
   284  		if err == nil {
   285  			err = setQuota(name, quota)
   286  			if err == nil {
   287  				d.Lock()
   288  				d.filesystemsCache[fs.Name] = true
   289  				d.Unlock()
   290  			}
   291  		}
   292  		return err
   293  	}
   294  	err = d.cloneFilesystem(name, d.zfsPath(parent))
   295  	if err == nil {
   296  		err = setQuota(name, quota)
   297  	}
   298  	return err
   299  }
   300  
   301  func parseStorageOpt(storageOpt map[string]string) (string, error) {
   302  	// Read size to change the disk quota per container
   303  	for k, v := range storageOpt {
   304  		key := strings.ToLower(k)
   305  		switch key {
   306  		case "size":
   307  			return v, nil
   308  		default:
   309  			return "0", fmt.Errorf("Unknown option %s", key)
   310  		}
   311  	}
   312  	return "0", nil
   313  }
   314  
   315  func setQuota(name string, quota string) error {
   316  	if quota == "0" {
   317  		return nil
   318  	}
   319  	fs, err := zfs.GetDataset(name)
   320  	if err != nil {
   321  		return err
   322  	}
   323  	return fs.SetProperty("quota", quota)
   324  }
   325  
   326  // Remove deletes the dataset, filesystem and the cache for the given id.
   327  func (d *Driver) Remove(id string) error {
   328  	name := d.zfsPath(id)
   329  	dataset := zfs.Dataset{Name: name}
   330  	err := dataset.Destroy(zfs.DestroyRecursive)
   331  	if err == nil {
   332  		d.Lock()
   333  		delete(d.filesystemsCache, name)
   334  		d.Unlock()
   335  	}
   336  	return err
   337  }
   338  
   339  // Get returns the mountpoint for the given id after creating the target directories if necessary.
   340  func (d *Driver) Get(id, mountLabel string) (string, error) {
   341  	mountpoint := d.mountPath(id)
   342  	if count := d.ctr.Increment(mountpoint); count > 1 {
   343  		return mountpoint, nil
   344  	}
   345  
   346  	filesystem := d.zfsPath(id)
   347  	options := label.FormatMountLabel("", mountLabel)
   348  	logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
   349  
   350  	rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
   351  	if err != nil {
   352  		d.ctr.Decrement(mountpoint)
   353  		return "", err
   354  	}
   355  	// Create the target directories if they don't exist
   356  	if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil {
   357  		d.ctr.Decrement(mountpoint)
   358  		return "", err
   359  	}
   360  
   361  	if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
   362  		d.ctr.Decrement(mountpoint)
   363  		return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
   364  	}
   365  
   366  	// this could be our first mount after creation of the filesystem, and the root dir may still have root
   367  	// permissions instead of the remapped root uid:gid (if user namespaces are enabled):
   368  	if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
   369  		mount.Unmount(mountpoint)
   370  		d.ctr.Decrement(mountpoint)
   371  		return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
   372  	}
   373  
   374  	return mountpoint, nil
   375  }
   376  
   377  // Put removes the existing mountpoint for the given id if it exists.
   378  func (d *Driver) Put(id string) error {
   379  	mountpoint := d.mountPath(id)
   380  	if count := d.ctr.Decrement(mountpoint); count > 0 {
   381  		return nil
   382  	}
   383  	mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint)
   384  	if err != nil || !mounted {
   385  		return err
   386  	}
   387  
   388  	logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
   389  
   390  	if err := mount.Unmount(mountpoint); err != nil {
   391  		return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
   392  	}
   393  	return nil
   394  }
   395  
   396  // Exists checks to see if the cache entry exists for the given id.
   397  func (d *Driver) Exists(id string) bool {
   398  	d.Lock()
   399  	defer d.Unlock()
   400  	return d.filesystemsCache[d.zfsPath(id)] == true
   401  }