summaryrefslogtreecommitdiff
path: root/internal/zfsutil/zfsutil.go
blob: 918289c8fd9fe2620442cc137baaae9f85d20330 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Package zfsutil wraps the zfs(8)/jail(8) CLI operations Skiff relies on as
// its only state store - no separate app-metadata database.
package zfsutil

import (
	"context"
	"fmt"
	"io"
	"strings"

	"skiff/internal/sh"
)

func snapRef(dataset, tag string) string {
	return fmt.Sprintf("%s@%s", dataset, tag)
}

// Clone creates a new dataset from a (read-only) snapshot of base, mounted
// at mountpoint. base must already have a snapshot named baseSnapshot.
func Clone(ctx context.Context, out io.Writer, base, baseSnapshot, dataset, mountpoint string) error {
	return sh.Run(ctx, out, "", "zfs", "clone", "-o", "mountpoint="+mountpoint, snapRef(base, baseSnapshot), dataset)
}

func Snapshot(ctx context.Context, out io.Writer, dataset, tag string) error {
	return sh.Run(ctx, out, "", "zfs", "snapshot", snapRef(dataset, tag))
}

// Rollback discards everything written to dataset since the snapshot named
// tag, including any newer snapshots. This is Skiff's entire undo mechanism:
// used both for the automatic post-health-check-failure rollback and for a
// manual `skiff rollback` days later.
func Rollback(ctx context.Context, out io.Writer, dataset, tag string) error {
	return sh.Run(ctx, out, "", "zfs", "rollback", "-r", snapRef(dataset, tag))
}

// DestroySnapshot removes a snapshot that was never needed as a rollback
// target - e.g. one taken right before an apply step that failed before
// anything actually changed. Left behind, it collides with the same tag on
// the next retry.
func DestroySnapshot(ctx context.Context, out io.Writer, dataset, tag string) error {
	return sh.Run(ctx, out, "", "zfs", "destroy", snapRef(dataset, tag))
}

// Snapshots lists snapshot names (without the dataset@ prefix), newest last.
func Snapshots(ctx context.Context, dataset string) ([]string, error) {
	raw, err := sh.Output(ctx, "", "zfs", "list", "-H", "-t", "snapshot", "-o", "name", "-s", "creation", "-r", dataset)
	if err != nil {
		return nil, err
	}
	var names []string
	for _, line := range strings.Split(strings.TrimSpace(raw), "\n") {
		if line == "" {
			continue
		}
		parts := strings.SplitN(line, "@", 2)
		if len(parts) == 2 {
			names = append(names, parts[1])
		}
	}
	return names, nil
}