Debian Codegraph @

zfs.go

raw symbols SCIP
1 // Package zfs provides wrappers around the ZFS command line tools.
2 package zfs
3
4 import (
5 "errors"
6 "fmt"
7 "io"
8 "strconv"
9 "strings"
10 )
11
12 // ZFS dataset types, which can indicate if a dataset is a filesystem, snapshot, or volume.
13 const (
14 DatasetFilesystem = "filesystem"
15 DatasetSnapshot = "snapshot"
16 DatasetVolume = "volume"
17 )
18
19 // Dataset is a ZFS dataset. A dataset could be a clone, filesystem, snapshot, or volume.
20 // The Type struct member can be used to determine a dataset's type.
21 //
22 // The field definitions can be found in the ZFS manual:
23 // https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
24 type Dataset struct {
25 Name string
26 Origin string
27 Used uint64
28 Avail uint64
29 Mountpoint string
30 Compression string
31 Type string
32 Written uint64
33 Volsize uint64
34 Logicalused uint64
35 Usedbydataset uint64
36 Quota uint64
37 Referenced uint64
38 }
39
40 // InodeType is the type of inode as reported by Diff.
41 type InodeType int
42
43 // Types of Inodes.
44 const (
45 _ = iota // 0 == unknown type
46 BlockDevice InodeType = iota
47 CharacterDevice
48 Directory
49 Door
50 NamedPipe
51 SymbolicLink
52 EventPort
53 Socket
54 File
55 )
56
57 // ChangeType is the type of inode change as reported by Diff.
58 type ChangeType int
59
60 // Types of Changes.
61 const (
62 _ = iota // 0 == unknown type
63 Removed ChangeType = iota
64 Created
65 Modified
66 Renamed
67 )
68
69 // DestroyFlag is the options flag passed to Destroy.
70 type DestroyFlag int
71
72 // Valid destroy options.
73 const (
74 DestroyDefault DestroyFlag = 1 << iota
75 DestroyRecursive = 1 << iota
76 DestroyRecursiveClones = 1 << iota
77 DestroyDeferDeletion = 1 << iota
78 DestroyForceUmount = 1 << iota
79 )
80
81 // InodeChange represents a change as reported by Diff.
82 type InodeChange struct {
83 Change ChangeType
84 Type InodeType
85 Path string
86 NewPath string
87 ReferenceCountChange int
88 }
89
90 // Logger can be used to log commands/actions.
91 type Logger interface {
92 Log(cmd []string)
93 }
94
95 type defaultLogger struct{}
96
97 func (*defaultLogger) Log([]string) {
98 }
99
100 var logger Logger = &defaultLogger{}
101
102 // SetLogger set a log handler to log all commands including arguments before they are executed.
103 func SetLogger(l Logger) {
104 if l != nil {
105 logger = l
106 }
107 }
108
109 // zfs is a helper function to wrap typical calls to zfs that ignores stdout.
110 func zfs(arg ...string) error {
111 _, err := zfsOutput(arg...)
112 return err
113 }
114
115 // zfs is a helper function to wrap typical calls to zfs.
116 func zfsOutput(arg ...string) ([][]string, error) {
117 c := command{Command: "zfs"}
118 return c.Run(arg...)
119 }
120
121 // Datasets returns a slice of ZFS datasets, regardless of type.
122 // A filter argument may be passed to select a dataset with the matching name, or empty string ("") may be used to select all datasets.
123 func Datasets(filter string) ([]*Dataset, error) {
124 return listByType("all", filter)
125 }
126
127 // Snapshots returns a slice of ZFS snapshots.
128 // A filter argument may be passed to select a snapshot with the matching name, or empty string ("") may be used to select all snapshots.
129 func Snapshots(filter string) ([]*Dataset, error) {
130 return listByType(DatasetSnapshot, filter)
131 }
132
133 // Filesystems returns a slice of ZFS filesystems.
134 // A filter argument may be passed to select a filesystem with the matching name, or empty string ("") may be used to select all filesystems.
135 func Filesystems(filter string) ([]*Dataset, error) {
136 return listByType(DatasetFilesystem, filter)
137 }
138
139 // Volumes returns a slice of ZFS volumes.
140 // A filter argument may be passed to select a volume with the matching name, or empty string ("") may be used to select all volumes.
141 func Volumes(filter string) ([]*Dataset, error) {
142 return listByType(DatasetVolume, filter)
143 }
144
145 // GetDataset retrieves a single ZFS dataset by name.
146 // This dataset could be any valid ZFS dataset type, such as a clone, filesystem, snapshot, or volume.
147 func GetDataset(name string) (*Dataset, error) {
148 out, err := zfsOutput("list", "-Hp", "-o", dsPropListOptions, name)
149 if err != nil {
150 return nil, err
151 }
152
153 ds := &Dataset{Name: name}
154 for _, line := range out {
155 if err := ds.parseLine(line); err != nil {
156 return nil, err
157 }
158 }
159
160 return ds, nil
161 }
162
163 // Clone clones a ZFS snapshot and returns a clone dataset.
164 // An error will be returned if the input dataset is not of snapshot type.
165 func (d *Dataset) Clone(dest string, properties map[string]string) (*Dataset, error) {
166 if d.Type != DatasetSnapshot {
167 return nil, errors.New("can only clone snapshots")
168 }
169 args := make([]string, 2, 4)
170 args[0] = "clone"
171 args[1] = "-p"
172 if properties != nil {
173 args = append(args, propsSlice(properties)...)
174 }
175 args = append(args, []string{d.Name, dest}...)
176 if err := zfs(args...); err != nil {
177 return nil, err
178 }
179 return GetDataset(dest)
180 }
181
182 // Unmount unmounts currently mounted ZFS file systems.
183 func (d *Dataset) Unmount(force bool) (*Dataset, error) {
184 if d.Type == DatasetSnapshot {
185 return nil, errors.New("cannot unmount snapshots")
186 }
187 args := make([]string, 1, 3)
188 args[0] = "umount"
189 if force {
190 args = append(args, "-f")
191 }
192 args = append(args, d.Name)
193 if err := zfs(args...); err != nil {
194 return nil, err
195 }
196 return GetDataset(d.Name)
197 }
198
199 // Mount mounts ZFS file systems.
200 func (d *Dataset) Mount(overlay bool, options []string) (*Dataset, error) {
201 if d.Type == DatasetSnapshot {
202 return nil, errors.New("cannot mount snapshots")
203 }
204 args := make([]string, 1, 5)
205 args[0] = "mount"
206 if overlay {
207 args = append(args, "-O")
208 }
209 if options != nil {
210 args = append(args, "-o")
211 args = append(args, strings.Join(options, ","))
212 }
213 args = append(args, d.Name)
214 if err := zfs(args...); err != nil {
215 return nil, err
216 }
217 return GetDataset(d.Name)
218 }
219
220 // ReceiveSnapshot receives a ZFS stream from the input io.Reader.
221 // A new snapshot is created with the specified name, and streams the input data into the newly-created snapshot.
222 func ReceiveSnapshot(input io.Reader, name string) (*Dataset, error) {
223 c := command{Command: "zfs", Stdin: input}
224 if _, err := c.Run("receive", name); err != nil {
225 return nil, err
226 }
227 return GetDataset(name)
228 }
229
230 // SendSnapshot sends a ZFS stream of a snapshot to the input io.Writer.
231 // An error will be returned if the input dataset is not of snapshot type.
232 func (d *Dataset) SendSnapshot(output io.Writer) error {
233 if d.Type != DatasetSnapshot {
234 return errors.New("can only send snapshots")
235 }
236
237 c := command{Command: "zfs", Stdout: output}
238 _, err := c.Run("send", d.Name)
239 return err
240 }
241
242 // IncrementalSend sends a ZFS stream of a snapshot to the input io.Writer using the baseSnapshot as the starting point.
243 // An error will be returned if the input dataset is not of snapshot type.
244 func (d *Dataset) IncrementalSend(baseSnapshot *Dataset, output io.Writer) error {
245 if d.Type != DatasetSnapshot || baseSnapshot.Type != DatasetSnapshot {
246 return errors.New("can only send snapshots")
247 }
248 c := command{Command: "zfs", Stdout: output}
249 _, err := c.Run("send", "-i", baseSnapshot.Name, d.Name)
250 return err
251 }
252
253 // CreateVolume creates a new ZFS volume with the specified name, size, and properties.
254 //
255 // A full list of available ZFS properties may be found in the ZFS manual:
256 // https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
257 func CreateVolume(name string, size uint64, properties map[string]string) (*Dataset, error) {
258 args := make([]string, 4, 5)
259 args[0] = "create"
260 args[1] = "-p"
261 args[2] = "-V"
262 args[3] = strconv.FormatUint(size, 10)
263 if properties != nil {
264 args = append(args, propsSlice(properties)...)
265 }
266 args = append(args, name)
267 if err := zfs(args...); err != nil {
268 return nil, err
269 }
270 return GetDataset(name)
271 }
272
273 // Destroy destroys a ZFS dataset.
274 // If the destroy bit flag is set, any descendents of the dataset will be recursively destroyed, including snapshots.
275 // If the deferred bit flag is set, the snapshot is marked for deferred deletion.
276 func (d *Dataset) Destroy(flags DestroyFlag) error {
277 args := make([]string, 1, 3)
278 args[0] = "destroy"
279 if flags&DestroyRecursive != 0 {
280 args = append(args, "-r")
281 }
282
283 if flags&DestroyRecursiveClones != 0 {
284 args = append(args, "-R")
285 }
286
287 if flags&DestroyDeferDeletion != 0 {
288 args = append(args, "-d")
289 }
290
291 if flags&DestroyForceUmount != 0 {
292 args = append(args, "-f")
293 }
294
295 args = append(args, d.Name)
296 err := zfs(args...)
297 return err
298 }
299
300 // SetProperty sets a ZFS property on the receiving dataset.
301 //
302 // A full list of available ZFS properties may be found in the ZFS manual:
303 // https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
304 func (d *Dataset) SetProperty(key, val string) error {
305 prop := strings.Join([]string{key, val}, "=")
306 err := zfs("set", prop, d.Name)
307 return err
308 }
309
310 // GetProperty returns the current value of a ZFS property from the receiving dataset.
311 //
312 // A full list of available ZFS properties may be found in the ZFS manual:
313 // https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
314 func (d *Dataset) GetProperty(key string) (string, error) {
315 out, err := zfsOutput("get", "-H", key, d.Name)
316 if err != nil {
317 return "", err
318 }
319
320 return out[0][2], nil
321 }
322
323 // Rename renames a dataset.
324 func (d *Dataset) Rename(name string, createParent, recursiveRenameSnapshots bool) (*Dataset, error) {
325 args := make([]string, 3, 5)
326 args[0] = "rename"
327 args[1] = d.Name
328 args[2] = name
329 if createParent {
330 args = append(args, "-p")
331 }
332 if recursiveRenameSnapshots {
333 args = append(args, "-r")
334 }
335 if err := zfs(args...); err != nil {
336 return d, err
337 }
338
339 return GetDataset(name)
340 }
341
342 // Snapshots returns a slice of all ZFS snapshots of a given dataset.
343 func (d *Dataset) Snapshots() ([]*Dataset, error) {
344 return Snapshots(d.Name)
345 }
346
347 // CreateFilesystem creates a new ZFS filesystem with the specified name and properties.
348 //
349 // A full list of available ZFS properties may be found in the ZFS manual:
350 // https://openzfs.github.io/openzfs-docs/man/7/zfsprops.7.html.
351 func CreateFilesystem(name string, properties map[string]string) (*Dataset, error) {
352 args := make([]string, 1, 4)
353 args[0] = "create"
354
355 if properties != nil {
356 args = append(args, propsSlice(properties)...)
357 }
358
359 args = append(args, name)
360 if err := zfs(args...); err != nil {
361 return nil, err
362 }
363 return GetDataset(name)
364 }
365
366 // Snapshot creates a new ZFS snapshot of the receiving dataset, using the specified name.
367 // Optionally, the snapshot can be taken recursively, creating snapshots of all descendent filesystems in a single, atomic operation.
368 func (d *Dataset) Snapshot(name string, recursive bool) (*Dataset, error) {
369 args := make([]string, 1, 4)
370 args[0] = "snapshot"
371 if recursive {
372 args = append(args, "-r")
373 }
374 snapName := fmt.Sprintf("%s@%s", d.Name, name)
375 args = append(args, snapName)
376 if err := zfs(args...); err != nil {
377 return nil, err
378 }
379 return GetDataset(snapName)
380 }
381
382 // Rollback rolls back the receiving ZFS dataset to a previous snapshot.
383 // Optionally, intermediate snapshots can be destroyed.
384 // A ZFS snapshot rollback cannot be completed without this option, if more recent snapshots exist.
385 // An error will be returned if the input dataset is not of snapshot type.
386 func (d *Dataset) Rollback(destroyMoreRecent bool) error {
387 if d.Type != DatasetSnapshot {
388 return errors.New("can only rollback snapshots")
389 }
390
391 args := make([]string, 1, 3)
392 args[0] = "rollback"
393 if destroyMoreRecent {
394 args = append(args, "-r")
395 }
396 args = append(args, d.Name)
397
398 err := zfs(args...)
399 return err
400 }
401
402 // Children returns a slice of children of the receiving ZFS dataset.
403 // A recursion depth may be specified, or a depth of 0 allows unlimited recursion.
404 func (d *Dataset) Children(depth uint64) ([]*Dataset, error) {
405 args := []string{"list"}
406 if depth > 0 {
407 args = append(args, "-d")
408 args = append(args, strconv.FormatUint(depth, 10))
409 } else {
410 args = append(args, "-r")
411 }
412 args = append(args, "-t", "all", "-Hp", "-o", dsPropListOptions)
413 args = append(args, d.Name)
414
415 out, err := zfsOutput(args...)
416 if err != nil {
417 return nil, err
418 }
419
420 var datasets []*Dataset
421 name := ""
422 var ds *Dataset
423 for _, line := range out {
424 if name != line[0] {
425 name = line[0]
426 ds = &Dataset{Name: name}
427 datasets = append(datasets, ds)
428 }
429 if err := ds.parseLine(line); err != nil {
430 return nil, err
431 }
432 }
433 return datasets[1:], nil
434 }
435
436 // Diff returns changes between a snapshot and the given ZFS dataset.
437 // The snapshot name must include the filesystem part as it is possible to compare clones with their origin snapshots.
438 func (d *Dataset) Diff(snapshot string) ([]*InodeChange, error) {
439 args := []string{"diff", "-FH", snapshot, d.Name}
440 out, err := zfsOutput(args...)
441 if err != nil {
442 return nil, err
443 }
444 inodeChanges, err := parseInodeChanges(out)
445 if err != nil {
446 return nil, err
447 }
448 return inodeChanges, nil
449 }