zfs

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 31, 2022 License: MIT Imports: 15 Imported by: 1

README

go-zfs

Go package that enables ZFS pool and dataset management by wrapping zfs and zpool CLI commands.

Go Reference GitHub tag (latest SemVer) Actions Status Coverage GitHub last commit GitHub issues GitHub pull requests License Status

Packages

zfs

The primary package used for interacting with ZFS, through the *zfs.Manager type.

import "github.com/krystal/go-zfs"

zfsprops

A helper package which defines a long list of string constants for most native properties available, based on OpenZFS' zfsprops manpage.

import "github.com/krystal/go-zfs/zfsprops"

zpoolprops

A helper package which defines a long list of string constants for most zpool properties available, based on OpenZFS' zpoolprops manpage.

import "github.com/krystal/go-zfs/zpoolprops"

Usage

Create a new *zfs.Manager instance to manage ZFS pools and datasets with:

z := zfs.New()

Get details for a specific dataset:

ds, err := z.GetDataset(ctx, "tank/my-data")
fmt.Printf("Name: %s\n", ds.Name)
Name: tank/my-data

Get used dataset property via Used() helper method, which returns the value as a uint64 of bytes:

if v, ok := ds.Used(); ok {
	fmt.Printf("Used: %d bytes\n", v)
}
Used: 150470656 bytes

Get used dataset property by directly accessing the Properties map, returning a Property type which has a string Value.

if prop, ok := ds.Properties[zfsprops.Used]; ok {
	fmt.Printf("Used: %s bytes\n", prop.Value)
}
Used: 150470656 bytes

Create a new pool, using both zpoolprops and zfsprops helper packages:

err = z.CreatePool(ctx, &zfs.CreatePoolOptions{
	Name: "scratch",
	Properties: map[string]string{
		zpoolprops.Ashift:                   "12",
		zpoolprops.AutoTrim:                 "on",
		zpoolprops.Feature("async_destroy"): "enabled",
	},
	FilesystemProperties: map[string]string{
		zfsprops.Atime:       "off",
		zfsprops.CanMount:    "on",
		zfsprops.Compression: "lz4",
	},
	Mountpoint: "/mnt/scratch",
	Vdevs:      []string{"mirror", "/dev/sde", "/dev/sdf"},
})

Create and get a new dataset:

err = z.CreateDataset(ctx, &zfs.CreateDatasetOptions{
	Name: "scratch/http/cache",
	Properties: map[string]string{
		zfsprops.Compression: "off",
	},
	CreateParents: true,
})

ds, err = z.GetDataset(ctx, "scratch/http/cache")
fmt.Printf("Name: %s\n", ds.Name)
Name: scratch/http/cache

Set dataset quota to 100 GiB and turn on atime:

err = z.SetDatasetProperties(ctx, "scratch/http/cache", map[string]string{
	zfsprops.Quota: "100G",
	zfsprops.Atime: "on",
})

Documentation

Please see the Go Reference for documentation and examples.

License

MIT

Documentation

Overview

Package zfs enables ZFS pool and dataset management by wrapping "zfs" and "zpool" CLI commands.

All interactions with ZFS are done through Manager.

Index

Constants

View Source
const (
	HealthDegraded    = "DEGRADED"
	HealthFaulted     = "FAULTED"
	HealthOffline     = "OFFLINE"
	HealthOnline      = "ONLINE"
	HealthRemoved     = "REMOVED"
	HealthUnavailable = "UNAVAIL"
)

Variables

View Source
var (
	Err                     = errors.New("")
	ErrZFS                  = fmt.Errorf("%wzfs", Err)
	ErrZpool                = fmt.Errorf("%wzpool", Err)
	ErrNotFound             = fmt.Errorf("%wnot found", Err)
	ErrInvalidName          = fmt.Errorf("%winvalid name", Err)
	ErrInvalidProperty      = fmt.Errorf("%winvalid property", Err)
	ErrInvalidCreateOptions = fmt.Errorf("%winvalid create options", Err)
)

Functions

func Join

func Join(parts ...string) string

Join joins the given parts with a "/" separator. Useful for building dataset names.

Types

type CreateDatasetOptions

type CreateDatasetOptions struct {
	// Name of the dataset. (required)
	Name string

	// Properties is a map of properties (-o) to set on the dataset.
	Properties map[string]string

	// CreateParents indicates whether to create any missing parent datasets by
	// passing the -p flag.
	CreateParents bool

	// Unmounted indicates whether to create the dataset without mounting it by
	// passing the -u flag.
	//
	// Ignored when VolumeSize is set.
	Unmounted bool

	// VolumeSize indicates we are creating a volume dataset instead of a
	// filesystem dataset. Hence to create a filesystem, VolumeSize must be
	// empty.
	VolumeSize string

	// BlockSize is the block size to use for the volume dataset by passing the
	// -b flag.
	//
	// Ignored when VolumeSize is empty.
	BlockSize string

	// Sparse indicates whether to create a sparse volume by passing the -s
	// flag.
	//
	// Ignored when VolumeSize is empty.
	Sparse bool
}

CreateDatasetOptions are options for creating a new dataset.

type CreatePoolOptions

type CreatePoolOptions struct {
	// Name of the pool. (required)
	Name string

	// Vdevs is a list of vdevs to pass to zpool create. (required)
	Vdevs []string

	// Properties is a map of properties (-o) to set on the pool.
	Properties map[string]string

	// FilesystemProperties is a map of filesystem properties (-O) to set on the
	// pool.
	FilesystemProperties map[string]string

	// Mountpoint is the mountpoint (-m) for the pool.
	Mountpoint string

	// Root is the root (-R) for the pool.
	Root string

	// Force indicates whether to force flag (-f) should be set.
	Force bool

	// DisableFeatures indicates whether to disable features flag (-d) should be
	// set.
	DisableFeatures bool

	// Args is a list of additional arguments to pass to zpool create.
	Args []string
}

CreatePoolOptions are options for creating a new zpool.

type Dataset

type Dataset struct {
	Properties
	Name string
}

func NewDataset

func NewDataset(name string, properties Properties) *Dataset

func (*Dataset) Atime

func (p *Dataset) Atime() (bool, bool)

Atime return the value of the "atime" property as a bool.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Available

func (p *Dataset) Available() (uint64, bool)

Available returns the value of the "free" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) CanMount

func (p *Dataset) CanMount() (bool, bool)

CanMount return the value of the "canmount" property as a bool.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Checksum

func (p *Dataset) Checksum() (string, bool)

Checksum returns the value of the "checksum" property.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) CompressRatio

func (p *Dataset) CompressRatio() (float64, bool)

CompressRatio returns the value of the "compressratio" property as a float64.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Compression

func (p *Dataset) Compression() (string, bool)

Compression returns the value of the "compression" property.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Copies

func (p *Dataset) Copies() (uint64, bool)

Copies returns the value of the "copies" property as a uint64.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Creation

func (p *Dataset) Creation() (time.Time, bool)

Creation returns the value of the "creation" property as a time.Time.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Devices

func (p *Dataset) Devices() (bool, bool)

Devices return the value of the "devices" property as a bool.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Exec

func (p *Dataset) Exec() (bool, bool)

Exec returns the value of the "exec" property as a bool.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) LogicalReferenced

func (p *Dataset) LogicalReferenced() (uint64, bool)

LogicalReferenced returns the value of the "logicalreferenced" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) LogicalUsed

func (p *Dataset) LogicalUsed() (uint64, bool)

LogicalUsed returns the value of the "logicalused" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Mountpoint

func (p *Dataset) Mountpoint() (string, bool)

Mountpoint returns the value of the "mountpoint" property.

The second return value indicates if the property is present in the Dataset instance. If the raw mountpoint value is "none", an empty string will be returned instead of "none".

func (*Dataset) Quota

func (p *Dataset) Quota() (uint64, bool)

Quota returns the value of the "quota" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) ReadOnly

func (p *Dataset) ReadOnly() (bool, bool)

ReadOnly returns the value of the "readonly" property as a bool.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) RefCompressRatio

func (p *Dataset) RefCompressRatio() (float64, bool)

RefCompressRatio returns the value of the "refcompressratio" property as a float64.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) RefQuota

func (p *Dataset) RefQuota() (uint64, bool)

RefQuota returns the value of the "refquota" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) RefReservation

func (p *Dataset) RefReservation() (uint64, bool)

RefReservation returns the value of the "refreservation" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) RelAtime

func (p *Dataset) RelAtime() (bool, bool)

RelAtime returns the value of the "relatime" property as a bool.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Reservation

func (p *Dataset) Reservation() (uint64, bool)

Reservation returns the value of the "reservation" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) SetUID

func (p *Dataset) SetUID() (bool, bool)

SetUID sets the value of the "setuid" property as a bool.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Sync

func (p *Dataset) Sync() (string, bool)

Sync returns the value of the "sync" property.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Type

func (p *Dataset) Type() (DatasetType, bool)

Type returns the value of the "type" property as a DatasetType.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) Used

func (p *Dataset) Used() (uint64, bool)

Used returns the value of the "used" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) UsedByChildren

func (p *Dataset) UsedByChildren() (uint64, bool)

UsedByChildren returns the value of the "usedbychildren" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) UsedByDataset

func (p *Dataset) UsedByDataset() (uint64, bool)

UsedByDataset returns the value of the "usedbydataset" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) UsedByRefReservation

func (p *Dataset) UsedByRefReservation() (uint64, bool)

UsedByRefreservation returns the value of the "usedbyrefreservation" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) UsedBySnapshots

func (p *Dataset) UsedBySnapshots() (uint64, bool)

UsedBySnapshots returns the value of the "usedbysnapshots" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

func (*Dataset) VolSize

func (p *Dataset) VolSize() (uint64, bool)

VolSize returns the value of the "volsize" property as number of bytes.

The second return value indicates if the property is present in the Dataset instance.

type DatasetType

type DatasetType string
const (
	AllTypes       DatasetType = "all"
	BookmarkType   DatasetType = "bookmark"
	FilesystemType DatasetType = "filesystem"
	SnapshotType   DatasetType = "snapshot"
	VolumeType     DatasetType = "volume"
)

func JoinTypes

func JoinTypes(types ...DatasetType) DatasetType

JoinTypes combines the given dataset types into a DatasetType value which can be used to query for datasets of multiple types.

type DestroyDatasetFlag

type DestroyDatasetFlag int

DestroyDatasetFlag is a value that is passed to DestroyDataset to specify the destruction behavior for datasets.

const (
	// DestroyRecursive indicates that the -r flag should be passed to zfs
	// destroy.
	//
	// When destroying filesystems and volumes:
	//
	//    Recursively destroy all children.
	//
	// When destroying snapshots:
	//
	//    Destroy (or mark for deferred deletion) all snapshots with this name
	//    in descendent file systems.
	DestroyRecursive DestroyDatasetFlag = iota + 1

	// DestroyRecursiveClones indicates that the -R flag should be passed to zfs
	// destroy.
	//
	// When destroying filesystems and volumes:
	//
	//    Recursively destroy all dependents, including cloned file systems
	//    outside the target hierarchy.
	//
	// When destroying snapshots:
	//
	//    Recursively destroy all clones of these snapshots, including the
	//    clones, snapshots, and children.  If this flag is specified,
	//    DestroyDeferDeletion will have no effect.
	DestroyRecursiveClones

	// DestroyDeferDeletion indicates that the -d flag should be passed to zfs
	// destroy.
	//
	// Destroy immediately. If a snapshot cannot be destroyed now, mark
	// it for deferred destruction.
	//
	// Only valid when destroying snapshots.
	DestroyDeferDeletion

	// DestroyForceUnmount indicates that the -f flag should be passed to zfs
	// destroy.
	//
	// Force an unmount of any file systems using the unmount -f command. This
	// option has no effect on non-filesystems or unmounted filesystems.
	DestroyForceUnmount
)

type ImportPoolOptions

type ImportPoolOptions struct {
	// Name of the pool to import.
	Name string

	// Properties is a map of properties (-o) to set on the pool.
	Properties map[string]string

	// Force indicates whether to force flag (-f) should be set.
	Force bool

	// Args is a list of additional arguments to pass to zpool import.
	Args []string

	// DirOrDevice is a list of directories or devices, each passed with the -d
	// flag to zpool import.
	DirOrDevice []string
}

ImportPoolOptions are options for importing a pool.

type Manager

type Manager struct {
	Runner runner.Runner
}

Manager is used to perform all zfs and zpool operations.

A runner.Runner is used to execute all commands. You can use a custom runner to modify the behavior of the executed commands. The runner package for example provides a "Sudo" runner struct that executes all commands via sudo.

func New

func New() *Manager

New returns a new Manager instance which is used to perform all zfs and zpool operations.

The default Runner assigned will execute all zfs and zpool commands on the local host machine, without sudo. As zfs operations typically need to be performed as root, you most likely need to run the Go application as root, or use a runner.Sudo instance to execute zfs and zpool commands via sudo.

func (*Manager) CreateDataset

func (m *Manager) CreateDataset(
	ctx context.Context,
	options *CreateDatasetOptions,
) error

CreateDataset creates a new dataset with the given options.

func (*Manager) CreatePool

func (m *Manager) CreatePool(
	ctx context.Context,
	options *CreatePoolOptions,
) error

CreatePool create a new pool with the given options.

func (*Manager) DestroyDataset

func (m *Manager) DestroyDataset(
	ctx context.Context,
	name string,
	flags ...DestroyDatasetFlag,
) error

DestroyDataset destroys the named dataset.

func (*Manager) DestroyPool

func (m *Manager) DestroyPool(
	ctx context.Context,
	name string,
	force bool,
) error

DestroyPool destroys the named pool, optionally passing the force flag (-f) to zpool destroy.

func (*Manager) ExportPool

func (m *Manager) ExportPool(
	ctx context.Context,
	name string,
	force bool,
) error

ExportPool exports the named pool, optionally passing the force flag (-f) to zpool export.

func (*Manager) GetDataset

func (m *Manager) GetDataset(
	ctx context.Context,
	name string,
	properties ...string,
) (*Dataset, error)

GetDataset returns a *Dataset instance for named dataset.

If properties are specified, only those properties are returned for the dataset, otherwise all properties are returned.

func (*Manager) GetDatasetProperty

func (m *Manager) GetDatasetProperty(
	ctx context.Context,
	name string,
	property string,
) (string, error)

GetDatasetProperty returns the value of the given property for the given dataset.

func (*Manager) GetPool

func (m *Manager) GetPool(
	ctx context.Context,
	name string,
	properties ...string,
) (*Pool, error)

GetPool returns a *Pool instance for named pool.

If properties are specified, only those properties are returned for the pool, otherwise all properties are returned.

func (*Manager) GetPoolProperty

func (m *Manager) GetPoolProperty(
	ctx context.Context,
	name string,
	property string,
) (string, error)

GetProperty returns the value of property on zpool with name.

func (*Manager) ImportPool

func (m *Manager) ImportPool(
	ctx context.Context,
	options *ImportPoolOptions,
) error

ImportPool imports the named pool based on the given options.

func (*Manager) InheritDatasetProperty

func (m *Manager) InheritDatasetProperty(
	ctx context.Context,
	name string,
	property string,
	recursive bool,
) error

InheritDatasetProperty sets property to inherit from parent dataset.

func (*Manager) ListDatasetNames

func (m *Manager) ListDatasetNames(
	ctx context.Context,
	filter string,
	depth uint64,
	typ DatasetType,
) ([]string, error)

ListDatasetNames returns a string slice of dataset names matching the given arguments.

func (*Manager) ListDatasets

func (m *Manager) ListDatasets(
	ctx context.Context,
	filter string,
	depth uint64,
	typ DatasetType,
	properties ...string,
) ([]*Dataset, error)

ListDatasets returns a slice of *Dataset instances based on the given arguments.

If properties are specified, only those properties are returned for each dataset, otherwise all properties are returned.

func (*Manager) ListPoolNames

func (m *Manager) ListPoolNames(ctx context.Context) ([]string, error)

ListPoolNames returns a string slice of all pool names.

func (*Manager) ListPools

func (m *Manager) ListPools(
	ctx context.Context,
	properties ...string,
) ([]*Pool, error)

ListPools returns a slice of *Pool instances for all pools.

If properties are specified, only those properties are returned for each pool, otherwise all properties are returned.

func (*Manager) SetDatasetProperties

func (m *Manager) SetDatasetProperties(
	ctx context.Context,
	name string,
	properties map[string]string,
) error

SetDatasetProperties sets given properties on dataset with name.

func (*Manager) SetDatasetProperty

func (m *Manager) SetDatasetProperty(
	ctx context.Context,
	name string,
	property string,
	value string,
) error

SetDatasetProperty sets property to value on dataset with name.

func (*Manager) SetPoolProperties

func (m *Manager) SetPoolProperties(
	ctx context.Context,
	name string,
	properties map[string]string,
) error

SetPoolProperties sets given properties on pool with name.

func (*Manager) SetPoolProperty

func (m *Manager) SetPoolProperty(
	ctx context.Context,
	name string,
	property string,
	value string,
) error

SetProperty sets property to value on zpool with name.

type Pool

type Pool struct {
	// Name of the pool.
	Name string

	// Properties of the pool.
	Properties
}

func (*Pool) Allocated

func (p *Pool) Allocated() (uint64, bool)

Allocated returns the value of the "allocated" property as number of bytes.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) Capacity

func (p *Pool) Capacity() (uint64, bool)

Capacity returns the value of the "capacity" property as number of bytes.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) Fragmentation

func (p *Pool) Fragmentation() (uint64, bool)

Fragmentation returns the value of the "fragmentation" property as number of bytes.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) Free

func (p *Pool) Free() (uint64, bool)

Free returns the value of the "free" property as number of bytes.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) Freeing

func (p *Pool) Freeing() (uint64, bool)

Freeing returns the value of the "freeing" property as number of bytes.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) Health

func (p *Pool) Health() (string, bool)

Health returns the value of the "health" property.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) Leaked

func (p *Pool) Leaked() (uint64, bool)

Leaked returns the value of the "leaked" property as number of bytes.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) ReadOnly

func (p *Pool) ReadOnly() (bool, bool)

ReadOnly returns the value of the "readonly" property as a bool.

The second return value indicates if the property is present in the Pool instance.

func (*Pool) Size

func (p *Pool) Size() (uint64, bool)

Size returns the value of the "size" property as number of bytes.

The second return value indicates if the property is present in the Pool instance.

type Properties

type Properties map[string]Property

Properties is a collection of ZFS properties, that includes typed accessor helper methods.

func (Properties) Bool

func (p Properties) Bool(property string) (bool, bool)

Bool returns the value of the given property as a bool. Only "on" and "enabled" are considered true, all other value return false.

The second return value indicates if the property is present and could successfully be parsed.

func (Properties) Bytes

func (p Properties) Bytes(property string) (uint64, bool)

Bytes returns the value of the given property as number of bytes.

The second return value indicates if the property is present and could successfully be parsed.

func (Properties) Percent

func (p Properties) Percent(property string) (uint64, bool)

Percent returns the value of the given property as a uint64. It will strip any trailing "%" before parsing it as a uint64, ensuring it can handle percent-based values like "1%" and "42%".

The second return value indicates if the property is present and could successfully be parsed.

func (Properties) Ratio

func (p Properties) Ratio(property string) (float64, bool)

Ratio returns the value of the given property as a float64. It will strip any trailing "x" before parsing it as a float64, ensuring it can handle ratio-based values like "1x" and "0.5x".

The second return value indicates if the property is present and could successfully be parsed.

func (Properties) String

func (p Properties) String(property string) (string, bool)

String returns the value of the given property.

The second return value indicates if the property is present and could successfully be parsed.

func (Properties) Time

func (p Properties) Time(property string) (time.Time, bool)

Time returns the value of the given property as a time.Time. It can handle both unix timestamp values from ZFS (-p flag) and human readable time values.

The second return value indicates if the property is present and could successfully be parsed.

func (Properties) Uint64

func (p Properties) Uint64(property string) (uint64, bool)

Uint64 returns the value of the given property as a uint64.

The second return value indicates if the property is present and could successfully be parsed.

type Property

type Property struct {
	// Name is the name of the ZFS pool/dataset that the property belongs to.
	Name string

	// Property is the name of the property itself.
	Property string

	// Value is the value of the property.
	Value string

	// Source is the source of the property.
	Source string
}

Property represents a single ZFS property.

Directories

Path Synopsis
Package zfsprops is a helper package that privides a list of string constants for zfs native properties.
Package zfsprops is a helper package that privides a list of string constants for zfs native properties.
Package zpoolprops is a helper package that privides a list of string constants for zpool properties.
Package zpoolprops is a helper package that privides a list of string constants for zpool properties.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL