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