zrepl/zfs/versions.go
Christian Schwarz 98def6e940 endpoint: refactor, fix stale holds on initial replication failure, holds release subcmds, more efficient ZFS queries
The motivation for this recatoring are based on two independent issues:

- @JMoVS found that the changes merged as part of #259 slowed his OS X
  based installation down significantly.
  Analysis of the zfs command logging introduced in #296 showed that
  `zfs holds` took most of the execution time, and they pointed out
  that not all of those `zfs holds` invocations were actually necessary.
  I.e.: zrepl was inefficient about retrieving information from ZFS.

- @InsanePrawn found that failures on initial replication would lead
  to step holds accumulating on the sending side, i.e. they would never
  be cleaned up in the HintMostRecentCommonAncestor RPC handler.
  That was because we only sent that RPC if there was a most recent
  common ancestor detected during replication planning.
  @InsanePrawn prototyped an implementation of a `zrepl holds release`
  command to mitigate the situation.
  As part of that development work and back-and-forth with @problame,
  it became evident that the abstractions that #259 built on top of
  zfs in package endpoint (step holds, replication cursor,
  last-received-hold), were not well-represented for re-use in the
  `zrepl holds release` subocommand.

This commit refactors package endpoint to address both of these issues:

- endpoint abstractions now share an interface `Abstraction` that, among
  other things, provides a uniform `Destroy()` method.
  However, that method should not be destroyed directly but instead
  the package-level `BatchDestroy` function should be used in order
  to allow for a migration to zfs channel programs in the future.

- endpoint now has a query facitilty (`ListAbstractions`) which is
  used to find on-disk
    - step holds and bookmarks
    - replication cursors (v1, v2)
    - last-received-holds
  By describing the query in a struct, we can centralized the retrieval
  of information via the ZFS CLI and only have to be clever once.
  We are "clever" in the following ways:
  - When asking for hold-based abstractions, we only run `zfs holds` on
    snapshot that have `userrefs` > 0
    - To support this functionality, add field `UserRefs` to zfs.FilesystemVersion
      and retrieve it anywhere we retrieve zfs.FilesystemVersion from ZFS.
  - When asking only for bookmark-based abstractions, we only run
    `zfs list -t bookmark`, not with snapshots.
  - Currently unused (except for CLI) per-filesystem concurrent lookup
  - Option to only include abstractions with CreateTXG in a specified range

- refactor `endpoint`'s various ZFS info  retrieval methods to use
  `ListAbstractions`

- change the `zrepl holds list` command to consume endpoint.ListAbstractions

- Add a `ListStale` method which, given a query template,
  lists stale holds and bookmarks.
  - it uses replication cursor has different modes
- the new `zrepl holds release-{all,stale}` commands can be used
  to remove abstractions of package endpoint

- Adjust HintMostRecentCommonAncestor RPC for stale-holds cleanup:
    - send it also if no most recent common ancestor exists between sender and receiver
    - have the sender clean up its abstractions when it receives the RPC
      with no most recent common ancestor, using `ListStale`
    - Due to changed semantics, bump the protocol version.

- Adjust HintMostRecentCommonAncestor RPC for performance problems
  encountered by @JMoVS
    - by default, per (job,fs)-combination, only consider cleaning
      step holds in the createtxg range
      `[last replication cursor,conservatively-estimated-receive-side-version)`
    - this behavior ensures resumability at cost proportional to the
      time that replication was donw
    - however, as explained in a comment, we might leak holds if
      the zrepl daemon stops running
    - that  trade-off is acceptable because in the presumably rare
      this might happen the user has two tools at their hand:
    - Tool 1: run `zrepl holds release-stale`
    - Tool 2: use env var `ZREPL_ENDPOINT_SENDER_HINT_MOST_RECENT_STEP_HOLD_CLEANUP_MODE`
      to adjust the lower bound of the createtxg range (search for it in the code).
      The env var can also be used to disable hold-cleanup on the
      send-side entirely.

supersedes closes #293
supersedes closes #282
fixes #280
fixes #278

Additionaly, we fixed a couple of bugs:

- zfs: fix half-nil error reporting of dataset-does-not-exist for ZFSListChan and ZFSBookmark

- endpoint: Sender's `HintMostRecentCommonAncestor` handler would not
  check whether access to the specified filesystem was allowed.
2020-04-07 18:57:55 +02:00

268 lines
6.8 KiB
Go

package zfs
import (
"bytes"
"context"
"fmt"
"io"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
)
type VersionType string
const (
Bookmark VersionType = "bookmark"
Snapshot VersionType = "snapshot"
)
type VersionTypeSet map[VersionType]bool
var (
AllVersionTypes = VersionTypeSet{
Bookmark: true,
Snapshot: true,
}
Bookmarks = VersionTypeSet{
Bookmark: true,
}
Snapshots = VersionTypeSet{
Snapshot: true,
}
)
func (s VersionTypeSet) zfsListTFlagRepr() string {
var types []string
for t := range s {
types = append(types, t.String())
}
return strings.Join(types, ",")
}
func (s VersionTypeSet) String() string { return s.zfsListTFlagRepr() }
func (t VersionType) DelimiterChar() string {
switch t {
case Bookmark:
return "#"
case Snapshot:
return "@"
default:
panic(fmt.Sprintf("unexpected VersionType %#v", t))
}
}
func (t VersionType) String() string {
return string(t)
}
func DecomposeVersionString(v string) (fs string, versionType VersionType, name string, err error) {
if len(v) < 3 {
err = fmt.Errorf("snapshot or bookmark name implausibly short: %s", v)
return
}
snapSplit := strings.SplitN(v, "@", 2)
bookmarkSplit := strings.SplitN(v, "#", 2)
if len(snapSplit)*len(bookmarkSplit) != 2 {
err = fmt.Errorf("dataset cannot be snapshot and bookmark at the same time: %s", v)
return
}
if len(snapSplit) == 2 {
return snapSplit[0], Snapshot, snapSplit[1], nil
} else {
return bookmarkSplit[0], Bookmark, bookmarkSplit[1], nil
}
}
// The data in a FilesystemVersion is guaranteed to stem from a ZFS CLI invocation.
type FilesystemVersion struct {
Type VersionType
// Display name. Should not be used for identification, only for user output
Name string
// GUID as exported by ZFS. Uniquely identifies a snapshot across pools
Guid uint64
// The TXG in which the snapshot was created. For bookmarks,
// this is the GUID of the snapshot it was initially tied to.
CreateTXG uint64
// The time the dataset was created
Creation time.Time
// userrefs field (snapshots only)
UserRefs OptionUint64
}
type OptionUint64 struct {
Value uint64
Valid bool
}
func (v FilesystemVersion) GetCreateTXG() uint64 { return v.CreateTXG }
func (v FilesystemVersion) GetGUID() uint64 { return v.Guid }
func (v FilesystemVersion) GetGuid() uint64 { return v.Guid }
func (v FilesystemVersion) GetName() string { return v.Name }
func (v FilesystemVersion) IsSnapshot() bool { return v.Type == Snapshot }
func (v FilesystemVersion) IsBookmark() bool { return v.Type == Bookmark }
func (v FilesystemVersion) RelName() string {
return fmt.Sprintf("%s%s", v.Type.DelimiterChar(), v.Name)
}
func (v FilesystemVersion) String() string { return v.RelName() }
func (v FilesystemVersion) ToAbsPath(p *DatasetPath) string {
var b bytes.Buffer
b.WriteString(p.ToString())
b.WriteString(v.Type.DelimiterChar())
b.WriteString(v.Name)
return b.String()
}
func (v FilesystemVersion) FullPath(fs string) string {
return fmt.Sprintf("%s%s", fs, v.RelName())
}
func (v FilesystemVersion) ToSendArgVersion() ZFSSendArgVersion {
return ZFSSendArgVersion{
RelName: v.RelName(),
GUID: v.Guid,
}
}
type ParseFilesystemVersionArgs struct {
fullname string
guid, createtxg, creation, userrefs string
}
func ParseFilesystemVersion(args ParseFilesystemVersionArgs) (v FilesystemVersion, err error) {
_, v.Type, v.Name, err = DecomposeVersionString(args.fullname)
if err != nil {
return v, err
}
if v.Guid, err = strconv.ParseUint(args.guid, 10, 64); err != nil {
err = errors.Wrapf(err, "cannot parse GUID %q", args.guid)
return v, err
}
if v.CreateTXG, err = strconv.ParseUint(args.createtxg, 10, 64); err != nil {
err = errors.Wrapf(err, "cannot parse CreateTXG %q", args.createtxg)
return v, err
}
creationUnix, err := strconv.ParseInt(args.creation, 10, 64)
if err != nil {
err = errors.Wrapf(err, "cannot parse creation date %q", args.creation)
return v, err
} else {
v.Creation = time.Unix(creationUnix, 0)
}
switch v.Type {
case Bookmark:
if args.userrefs != "-" {
return v, errors.Errorf("expecting %q for bookmark property userrefs, got %q", "-", args.userrefs)
}
v.UserRefs = OptionUint64{Valid: false}
case Snapshot:
if v.UserRefs.Value, err = strconv.ParseUint(args.userrefs, 10, 64); err != nil {
err = errors.Wrapf(err, "cannot parse userrefs %q", args.userrefs)
return v, err
}
v.UserRefs.Valid = true
default:
panic(v.Type)
}
return v, nil
}
type ListFilesystemVersionsOptions struct {
// the prefix of the version name, without the delimiter char
// empty means any prefix matches
ShortnamePrefix string
// which types should be returned
// nil or len(0) means any prefix matches
Types VersionTypeSet
}
func (o *ListFilesystemVersionsOptions) typesFlagArgs() string {
if len(o.Types) == 0 {
return AllVersionTypes.zfsListTFlagRepr()
} else {
return o.Types.zfsListTFlagRepr()
}
}
func (o *ListFilesystemVersionsOptions) matches(v FilesystemVersion) bool {
return (len(o.Types) == 0 || o.Types[v.Type]) && strings.HasPrefix(v.Name, o.ShortnamePrefix)
}
// returned versions are sorted by createtxg FIXME drop sort by createtxg requirement
func ZFSListFilesystemVersions(fs *DatasetPath, options ListFilesystemVersionsOptions) (res []FilesystemVersion, err error) {
listResults := make(chan ZFSListResult)
promTimer := prometheus.NewTimer(prom.ZFSListFilesystemVersionDuration.WithLabelValues(fs.ToString()))
defer promTimer.ObserveDuration()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go ZFSListChan(ctx, listResults,
[]string{"name", "guid", "createtxg", "creation", "userrefs"},
fs,
"-r", "-d", "1",
"-t", options.typesFlagArgs(),
"-s", "createtxg", fs.ToString())
res = make([]FilesystemVersion, 0)
for listResult := range listResults {
if listResult.Err != nil {
if listResult.Err == io.ErrUnexpectedEOF {
// Since we specified the fs on the command line, we'll treat this like the filesystem doesn't exist
return []FilesystemVersion{}, nil
}
return nil, listResult.Err
}
line := listResult.Fields
args := ParseFilesystemVersionArgs{
fullname: line[0],
guid: line[1],
createtxg: line[2],
creation: line[3],
userrefs: line[4],
}
v, err := ParseFilesystemVersion(args)
if err != nil {
return nil, err
}
if options.matches(v) {
res = append(res, v)
}
}
return
}
func ZFSGetFilesystemVersion(ctx context.Context, ds string) (v FilesystemVersion, _ error) {
props, err := zfsGet(ctx, ds, []string{"createtxg", "guid", "creation", "userrefs"}, sourceAny)
if err != nil {
return v, err
}
return ParseFilesystemVersion(ParseFilesystemVersionArgs{
fullname: ds,
createtxg: props.Get("createtxg"),
guid: props.Get("guid"),
creation: props.Get("creation"),
userrefs: props.Get("userrefs"),
})
}