github.com/ojongerius/docker@v1.11.2/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  	"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 a 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(),
   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  // Create prepares the dataset and filesystem for the ZFS driver for the given id under the parent.
   246  func (d *Driver) Create(id string, parent string, mountLabel string) error {
   247  	err := d.create(id, parent)
   248  	if err == nil {
   249  		return nil
   250  	}
   251  	if zfsError, ok := err.(*zfs.Error); ok {
   252  		if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
   253  			return err
   254  		}
   255  		// aborted build -> cleanup
   256  	} else {
   257  		return err
   258  	}
   259  
   260  	dataset := zfs.Dataset{Name: d.zfsPath(id)}
   261  	if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
   262  		return err
   263  	}
   264  
   265  	// retry
   266  	return d.create(id, parent)
   267  }
   268  
   269  func (d *Driver) create(id, parent string) error {
   270  	name := d.zfsPath(id)
   271  	if parent == "" {
   272  		mountoptions := map[string]string{"mountpoint": "legacy"}
   273  		fs, err := zfs.CreateFilesystem(name, mountoptions)
   274  		if err == nil {
   275  			d.Lock()
   276  			d.filesystemsCache[fs.Name] = true
   277  			d.Unlock()
   278  		}
   279  		return err
   280  	}
   281  	return d.cloneFilesystem(name, d.zfsPath(parent))
   282  }
   283  
   284  // Remove deletes the dataset, filesystem and the cache for the given id.
   285  func (d *Driver) Remove(id string) error {
   286  	name := d.zfsPath(id)
   287  	dataset := zfs.Dataset{Name: name}
   288  	err := dataset.Destroy(zfs.DestroyRecursive)
   289  	if err == nil {
   290  		d.Lock()
   291  		delete(d.filesystemsCache, name)
   292  		d.Unlock()
   293  	}
   294  	return err
   295  }
   296  
   297  // Get returns the mountpoint for the given id after creating the target directories if necessary.
   298  func (d *Driver) Get(id, mountLabel string) (string, error) {
   299  	mountpoint := d.mountPath(id)
   300  	if count := d.ctr.Increment(id); count > 1 {
   301  		return mountpoint, nil
   302  	}
   303  
   304  	filesystem := d.zfsPath(id)
   305  	options := label.FormatMountLabel("", mountLabel)
   306  	logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)
   307  
   308  	rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
   309  	if err != nil {
   310  		d.ctr.Decrement(id)
   311  		return "", err
   312  	}
   313  	// Create the target directories if they don't exist
   314  	if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil {
   315  		d.ctr.Decrement(id)
   316  		return "", err
   317  	}
   318  
   319  	if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
   320  		d.ctr.Decrement(id)
   321  		return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
   322  	}
   323  
   324  	// this could be our first mount after creation of the filesystem, and the root dir may still have root
   325  	// permissions instead of the remapped root uid:gid (if user namespaces are enabled):
   326  	if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
   327  		mount.Unmount(mountpoint)
   328  		d.ctr.Decrement(id)
   329  		return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
   330  	}
   331  
   332  	return mountpoint, nil
   333  }
   334  
   335  // Put removes the existing mountpoint for the given id if it exists.
   336  func (d *Driver) Put(id string) error {
   337  	if count := d.ctr.Decrement(id); count > 0 {
   338  		return nil
   339  	}
   340  	mountpoint := d.mountPath(id)
   341  	mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint)
   342  	if err != nil || !mounted {
   343  		return err
   344  	}
   345  
   346  	logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)
   347  
   348  	if err := mount.Unmount(mountpoint); err != nil {
   349  		return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
   350  	}
   351  	return nil
   352  }
   353  
   354  // Exists checks to see if the cache entry exists for the given id.
   355  func (d *Driver) Exists(id string) bool {
   356  	d.Lock()
   357  	defer d.Unlock()
   358  	return d.filesystemsCache[d.zfsPath(id)] == true
   359  }