Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ed84bf6d8 | ||
|
|
35eed79b1a | ||
|
|
94412d9ef3 |
@@ -286,7 +286,9 @@ needed.
|
|||||||
remove orphaned blobs from remote storage. By default keeps only the latest
|
remove orphaned blobs from remote storage. By default keeps only the latest
|
||||||
snapshot per name; use `--keep-newer-than` for a rolling window.
|
snapshot per name; use `--keep-newer-than` for a rolling window.
|
||||||
* `--keep-newer-than <duration>`: With `--prune`, keep snapshots newer than
|
* `--keep-newer-than <duration>`: With `--prune`, keep snapshots newer than
|
||||||
this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`)
|
this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`).
|
||||||
|
Without `--prune`, or with a value that is not a valid duration, the
|
||||||
|
command fails before the backup starts.
|
||||||
|
|
||||||
**`snapshot list`**: Show every snapshot known to this host — the union
|
**`snapshot list`**: Show every snapshot known to this host — the union
|
||||||
of the local index and the backup destination store — with timestamps
|
of the local index and the backup destination store — with timestamps
|
||||||
@@ -370,7 +372,9 @@ on the destination in one go, use `vaultik remote nuke --force`.
|
|||||||
store — its remote key (or an unambiguous leading part of it) as shown
|
store — its remote key (or an unambiguous leading part of it) as shown
|
||||||
by `snapshot list`. See
|
by `snapshot list`. See
|
||||||
[restoring on another machine](#restoring-on-another-machine).
|
[restoring on another machine](#restoring-on-another-machine).
|
||||||
* Optional path arguments to restore specific files/directories (default: all)
|
* Optional path arguments to restore specific files/directories (default: all).
|
||||||
|
A path that matches nothing in the snapshot is named in a warning, and the
|
||||||
|
command exits non-zero after restoring the paths that match
|
||||||
* Preserves file permissions, timestamps, ownership (ownership requires root),
|
* Preserves file permissions, timestamps, ownership (ownership requires root),
|
||||||
symlinks, and empty directories
|
symlinks, and empty directories
|
||||||
* `--verify`: After restoring, verify every file's chunk hashes match
|
* `--verify`: After restoring, verify every file's chunk hashes match
|
||||||
@@ -401,7 +405,9 @@ orphaned blob figures are reported as unknown; `--json` gives them as
|
|||||||
`null`, lists the remote key of each unreadable manifest in
|
`null`, lists the remote key of each unreadable manifest in
|
||||||
`unreadable_manifests` and counts the manifests under skipped names in
|
`unreadable_manifests` and counts the manifests under skipped names in
|
||||||
`skipped_manifest_count`. An unreadable manifest also leaves its
|
`skipped_manifest_count`. An unreadable manifest also leaves its
|
||||||
snapshot's blob count and blob size unknown, `null` in `--json`.
|
snapshot's blob count and blob size unknown, `null` in `--json`. A file
|
||||||
|
under `blobs/` whose name is not a blob hash is not counted as a blob,
|
||||||
|
since `prune` never deletes it.
|
||||||
* `--json`: Output as JSON
|
* `--json`: Output as JSON
|
||||||
|
|
||||||
**`remote nuke`**: Delete every snapshot's metadata and every blob from the
|
**`remote nuke`**: Delete every snapshot's metadata and every blob from the
|
||||||
|
|||||||
@@ -22,14 +22,13 @@ the tag exists and is exercised; what is left is merging `next` to
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
- 2026-10-13: Made an S3 listing that the server cuts short an error
|
- 2026-10-13: Stopped `remote info` counting a file under `blobs/` that
|
||||||
([issue #297](https://git.eeqj.de/sneak/vaultik/issues/297)). A page
|
is not a blob as an orphaned blob
|
||||||
marked truncated with no continuation token, as a server answering V2
|
([issue #295](https://git.eeqj.de/sneak/vaultik/issues/295)). A stray
|
||||||
listings V1-style sends, ended the listing without an error, so
|
file such as `.DS_Store` was reported as an orphaned blob and the
|
||||||
`prune` saw only the snapshots on the first page and could delete
|
report advised running `prune`, which skips such a file and deleted
|
||||||
blobs the rest still use. Such a page is now a listing error, and
|
nothing. `remote info` now takes its blob list from the same listing
|
||||||
`prune`, `snapshot list` and `remote nuke` handle it as a destination
|
`prune` uses, in the table and in `--json`.
|
||||||
that cannot be listed.
|
|
||||||
|
|
||||||
- 2026-10-13: Made `snapshot remove` fail for a snapshot that does not
|
- 2026-10-13: Made `snapshot remove` fail for a snapshot that does not
|
||||||
exist ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)).
|
exist ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)).
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Flags of `snapshot create` used to build argument vectors below.
|
||||||
|
const (
|
||||||
|
flagPrune = "--prune"
|
||||||
|
flagKeepNewerThan = "--keep-newer-than"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup checks that a
|
||||||
|
// --keep-newer-than the post-backup prune could not use stops `snapshot
|
||||||
|
// create` before the backup: the command fails and the destination
|
||||||
|
// store stays empty. It used to be read only by the prune, after the
|
||||||
|
// snapshot was uploaded, and without --prune it was ignored.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "decimal in a day count",
|
||||||
|
args: []string{flagPrune, flagKeepNewerThan, "1.5d"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown unit",
|
||||||
|
args: []string{flagPrune, flagKeepNewerThan, "4x"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "without --prune",
|
||||||
|
args: []string{flagKeepNewerThan, "4w"},
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
code, _, _ := runEntry(t, append(
|
||||||
|
[]string{flagConfig, configPath, cmdSnapshot, cmdCreate},
|
||||||
|
testCase.args...)...)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
|
||||||
|
stored, err := os.ReadDir(storeDir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, stored, "nothing may be uploaded")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreateReportsPostBackupPruneFailure makes the
|
||||||
|
// post-backup prune fail after a good backup, by planting a manifest
|
||||||
|
// that cannot be decoded, and checks that the failure is reported as the
|
||||||
|
// prune's and not as a failed snapshot creation.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
// A remote key is 64 lowercase hex characters. The prune reads every
|
||||||
|
// manifest on the store and fails on one it cannot decode.
|
||||||
|
plantedDir := filepath.Join(storeDir, "metadata", strings.Repeat("a", 64))
|
||||||
|
require.NoError(t, os.MkdirAll(plantedDir, 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(plantedDir, "manifest.json.zst"),
|
||||||
|
[]byte("not a valid manifest"), 0o600))
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Contains(t, stderr, "Backup completed, but post-backup prune failed")
|
||||||
|
assert.NotContains(t, stderr, "Snapshot creation failed")
|
||||||
|
|
||||||
|
snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Len(t, snapshots, 2,
|
||||||
|
"the new snapshot is on the store beside the planted one")
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeBackupConfig builds a hermetic config with one small file in its
|
||||||
|
// source directory and an empty destination store directory. Returns the
|
||||||
|
// config path and the store directory.
|
||||||
|
func writeBackupConfig(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
configPath := writeHermeticPruneConfig(t, false)
|
||||||
|
|
||||||
|
// writeHermeticPruneConfig puts the source and store directories
|
||||||
|
// beside the config file.
|
||||||
|
dir := filepath.Dir(configPath)
|
||||||
|
sourceDir := filepath.Join(dir, "source")
|
||||||
|
|
||||||
|
require.NoError(t, os.Mkdir(sourceDir, 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(sourceDir, "file.txt"), []byte("hello"), 0o600))
|
||||||
|
|
||||||
|
return configPath, filepath.Join(dir, "store")
|
||||||
|
}
|
||||||
@@ -71,6 +71,11 @@ otherwise from the platform config directory (~/.config/vaultik/config.yml
|
|||||||
on Linux), then /etc/vaultik/config.yml.`,
|
on Linux), then /etc/vaultik/config.yml.`,
|
||||||
Args: cobra.ArbitraryArgs,
|
Args: cobra.ArbitraryArgs,
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
err := opts.Validate()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// Pass snapshot names from args
|
// Pass snapshot names from args
|
||||||
opts.Snapshots = args
|
opts.Snapshots = args
|
||||||
// --skip-errors is a global flag on the root command.
|
// --skip-errors is a global flag on the root command.
|
||||||
@@ -97,6 +102,13 @@ on Linux), then /etc/vaultik/config.yml.`,
|
|||||||
}, func(v *vaultik.Vaultik) error {
|
}, func(v *vaultik.Vaultik) error {
|
||||||
return v.CreateSnapshot(opts)
|
return v.CreateSnapshot(opts)
|
||||||
}, func(err error) {
|
}, func(err error) {
|
||||||
|
if errors.Is(err, vaultik.ErrPostBackupPruneFailed) {
|
||||||
|
log.Error("Post-backup prune failed", "error", err)
|
||||||
|
ReportErrorf("Backup completed, but %v", err)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
log.Error("Snapshot creation failed", "error", err)
|
log.Error("Snapshot creation failed", "error", err)
|
||||||
ReportErrorf("Snapshot creation failed: %v", err)
|
ReportErrorf("Snapshot creation failed: %v", err)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ This command will restore files from the specified snapshot to the
|
|||||||
target directory.
|
target directory.
|
||||||
If no paths are specified, all files are restored.
|
If no paths are specified, all files are restored.
|
||||||
If paths are specified, only matching files/directories are restored.
|
If paths are specified, only matching files/directories are restored.
|
||||||
|
A path that matches nothing in the snapshot is named in a warning, and
|
||||||
|
the command exits non-zero after restoring the paths that match.
|
||||||
|
|
||||||
The snapshot may be named by its ID or, when restoring on a host with no
|
The snapshot may be named by its ID or, when restoring on a host with no
|
||||||
local index, by the remote key that 'snapshot list' prints for a
|
local index, by the remote key that 'snapshot list' prints for a
|
||||||
|
|||||||
+2
-29
@@ -18,13 +18,6 @@ import (
|
|||||||
"github.com/aws/smithy-go/logging"
|
"github.com/aws/smithy-go/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrNoContinuationToken is returned by ListObjects and ListObjectsStream
|
|
||||||
// when the server marks a page of a listing truncated but sends no
|
|
||||||
// continuation token to fetch the rest with, as a server answering V2
|
|
||||||
// listings V1-style does.
|
|
||||||
var ErrNoContinuationToken = errors.New(
|
|
||||||
"server marked the listing truncated but sent no continuation token")
|
|
||||||
|
|
||||||
// Client wraps the AWS S3 client for vaultik operations.
|
// Client wraps the AWS S3 client for vaultik operations.
|
||||||
// It provides a simplified interface for S3 operations with automatic
|
// It provides a simplified interface for S3 operations with automatic
|
||||||
// prefix handling and connection management. All operations are performed
|
// prefix handling and connection management. All operations are performed
|
||||||
@@ -221,7 +214,7 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro
|
|||||||
})
|
})
|
||||||
|
|
||||||
for paginator.HasMorePages() {
|
for paginator.HasMorePages() {
|
||||||
page, err := nextListPage(ctx, paginator)
|
page, err := paginator.NextPage(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -242,26 +235,6 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro
|
|||||||
return keys, nil
|
return keys, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// nextListPage fetches the next page of a listing. The SDK paginator takes
|
|
||||||
// a page marked truncated without a continuation token for the last page
|
|
||||||
// and stops without an error, so such a page is ErrNoContinuationToken
|
|
||||||
// here instead.
|
|
||||||
func nextListPage(
|
|
||||||
ctx context.Context, paginator *s3.ListObjectsV2Paginator,
|
|
||||||
) (*s3.ListObjectsV2Output, error) {
|
|
||||||
page, err := paginator.NextPage(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
truncated := aws.ToBool(page.IsTruncated)
|
|
||||||
if truncated && aws.ToString(page.NextContinuationToken) == "" {
|
|
||||||
return nil, ErrNoContinuationToken
|
|
||||||
}
|
|
||||||
|
|
||||||
return page, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// HeadObject checks if an object exists in S3.
|
// HeadObject checks if an object exists in S3.
|
||||||
// Returns true if the object exists, false otherwise.
|
// Returns true if the object exists, false otherwise.
|
||||||
// The key is automatically prefixed with the configured prefix.
|
// The key is automatically prefixed with the configured prefix.
|
||||||
@@ -327,7 +300,7 @@ func (c *Client) ListObjectsStream(
|
|||||||
})
|
})
|
||||||
|
|
||||||
for paginator.HasMorePages() {
|
for paginator.HasMorePages() {
|
||||||
page, err := nextListPage(ctx, paginator)
|
page, err := paginator.NextPage(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ch <- ObjectInfo{Err: err}
|
ch <- ObjectInfo{Err: err}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"slices"
|
"slices"
|
||||||
@@ -23,16 +22,13 @@ import (
|
|||||||
// s3TestBucket is the bucket created for each in-process S3 server.
|
// s3TestBucket is the bucket created for each in-process S3 server.
|
||||||
const s3TestBucket = "test-bucket"
|
const s3TestBucket = "test-bucket"
|
||||||
|
|
||||||
// Credentials for the tests' S3 clients. The test servers accept any.
|
// Credentials for the tests that build a storer from a config.Config. The
|
||||||
|
// in-process S3 server accepts any.
|
||||||
const (
|
const (
|
||||||
s3TestAccessKeyID = "key"
|
s3TestAccessKeyID = "key"
|
||||||
s3TestSecretAccessKey = "secret"
|
s3TestSecretAccessKey = "secret"
|
||||||
)
|
)
|
||||||
|
|
||||||
// s3TestRegion is the region of the S3 clients built here with
|
|
||||||
// s3.NewClient. The test servers ignore it.
|
|
||||||
const s3TestRegion = "us-east-1"
|
|
||||||
|
|
||||||
// newS3Storer builds an s3:// backend backed by a fresh in-process
|
// newS3Storer builds an s3:// backend backed by a fresh in-process
|
||||||
// S3 server. It reuses the same in-memory S3 harness (gofakes3 + s3mem
|
// S3 server. It reuses the same in-memory S3 harness (gofakes3 + s3mem
|
||||||
// over httptest) that internal/s3 and the not-found regression test use,
|
// over httptest) that internal/s3 and the not-found regression test use,
|
||||||
@@ -59,7 +55,7 @@ func newS3Storer(t *testing.T) storage.Storer {
|
|||||||
Bucket: s3TestBucket,
|
Bucket: s3TestBucket,
|
||||||
AccessKeyID: "test",
|
AccessKeyID: "test",
|
||||||
SecretAccessKey: "test",
|
SecretAccessKey: "test",
|
||||||
Region: s3TestRegion,
|
Region: "us-east-1",
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("new client: %v", err)
|
t.Fatalf("new client: %v", err)
|
||||||
@@ -97,68 +93,6 @@ func TestS3StorerMissingKeyMapsToErrNotFound(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestS3ListingCutShortIsAnError checks that List and ListStream fail on a
|
|
||||||
// listing page marked truncated that carries no continuation token, as a
|
|
||||||
// server answering V2 listings V1-style sends it. Taken as the last page,
|
|
||||||
// it would hide every later key, and prune would treat the blobs of the
|
|
||||||
// snapshots listed there as unreferenced.
|
|
||||||
func TestS3ListingCutShortIsAnError(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
const (
|
|
||||||
prefix = "metadata/"
|
|
||||||
truncatedPage = `<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
||||||
<Name>test-bucket</Name>
|
|
||||||
<Prefix>metadata/</Prefix>
|
|
||||||
<KeyCount>1</KeyCount>
|
|
||||||
<MaxKeys>1</MaxKeys>
|
|
||||||
<IsTruncated>true</IsTruncated>
|
|
||||||
<Contents>
|
|
||||||
<Key>metadata/snap/manifest.json.zst</Key>
|
|
||||||
<Size>8</Size>
|
|
||||||
</Contents>
|
|
||||||
</ListBucketResult>`
|
|
||||||
)
|
|
||||||
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(
|
|
||||||
func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
_, _ = io.WriteString(w, truncatedPage)
|
|
||||||
}))
|
|
||||||
t.Cleanup(srv.Close)
|
|
||||||
|
|
||||||
client, err := s3.NewClient(context.Background(), s3.Config{
|
|
||||||
Endpoint: srv.URL,
|
|
||||||
Bucket: s3TestBucket,
|
|
||||||
AccessKeyID: s3TestAccessKeyID,
|
|
||||||
SecretAccessKey: s3TestSecretAccessKey,
|
|
||||||
Region: s3TestRegion,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("new client: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
storer := storage.NewS3Storer(client)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
keys, err := storer.List(ctx, prefix)
|
|
||||||
if !errors.Is(err, s3.ErrNoContinuationToken) {
|
|
||||||
t.Errorf("List = %q, %v; want ErrNoContinuationToken", keys, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var streamErr error
|
|
||||||
|
|
||||||
for obj := range storer.ListStream(ctx, prefix) {
|
|
||||||
if obj.Err != nil {
|
|
||||||
streamErr = obj.Err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !errors.Is(streamErr, s3.ErrNoContinuationToken) {
|
|
||||||
t.Errorf("ListStream error = %v, want ErrNoContinuationToken", streamErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestS3URLPrefixKeyLayout pins the bucket keys an s3:// URL reads and
|
// TestS3URLPrefixKeyLayout pins the bucket keys an s3:// URL reads and
|
||||||
// writes: the README's remote storage layout, with the prefix joined to
|
// writes: the README's remote storage layout, with the prefix joined to
|
||||||
// each key by one "/". s3://b/p and s3://b/p/ must be the same
|
// each key by one "/". s3://b/p and s3://b/p/ must be the same
|
||||||
|
|||||||
@@ -167,10 +167,6 @@ const (
|
|||||||
// metadataKeyParts is the minimum "/"-separated segment count of a
|
// metadataKeyParts is the minimum "/"-separated segment count of a
|
||||||
// metadata object key (metadata/<snapshot-id>/<filename>).
|
// metadata object key (metadata/<snapshot-id>/<filename>).
|
||||||
metadataKeyParts = 3
|
metadataKeyParts = 3
|
||||||
|
|
||||||
// blobKeyParts is the minimum "/"-separated segment count of a blob
|
|
||||||
// object key (blobs/<aa>/<bb>/<hash>).
|
|
||||||
blobKeyParts = 4
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// SnapshotMetadataInfo contains information about a single snapshot's metadata
|
// SnapshotMetadataInfo contains information about a single snapshot's metadata
|
||||||
@@ -454,23 +450,16 @@ func (v *Vaultik) scanRemoteBlobStorage(
|
|||||||
v.stdoutf("Scanning blobs...\n")
|
v.stdoutf("Scanning blobs...\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
blobCh := v.Storage.ListStream(v.ctx, "blobs/")
|
// Use prune's listing, so a file under blobs/ that prune would never
|
||||||
allBlobs := make(map[string]int64)
|
// delete is not counted as a blob, and so not as an orphaned one.
|
||||||
|
allBlobs, err := v.listAllRemoteBlobs()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
for obj := range blobCh {
|
for _, size := range allBlobs {
|
||||||
if obj.Err != nil {
|
|
||||||
return fmt.Errorf("listing blobs: %w", obj.Err)
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(obj.Key, "/")
|
|
||||||
if len(parts) < blobKeyParts {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
hash := parts[3]
|
|
||||||
allBlobs[hash] = obj.Size
|
|
||||||
result.TotalBlobCount++
|
result.TotalBlobCount++
|
||||||
result.TotalBlobSize += obj.Size
|
result.TotalBlobSize += size
|
||||||
}
|
}
|
||||||
|
|
||||||
// A blob named only by a manifest that could not be read, or by one
|
// A blob named only by a manifest that could not be read, or by one
|
||||||
|
|||||||
@@ -23,6 +23,10 @@ var errNukeRequiresForce = errors.New(
|
|||||||
// metadata.
|
// metadata.
|
||||||
const metadataDirName = "metadata"
|
const metadataDirName = "metadata"
|
||||||
|
|
||||||
|
// blobKeyParts is the "/"-separated segment count of a blob object key
|
||||||
|
// (blobs/<aa>/<bb>/<hash>).
|
||||||
|
const blobKeyParts = 4
|
||||||
|
|
||||||
// NukeRemote deletes every snapshot's metadata and every blob from remote
|
// NukeRemote deletes every snapshot's metadata and every blob from remote
|
||||||
// storage, along with any object an upload cut off part-way left under a
|
// storage, along with any object an upload cut off part-way left under a
|
||||||
// temporary `.partial` name. After this returns successfully the bucket
|
// temporary `.partial` name. After this returns successfully the bucket
|
||||||
|
|||||||
@@ -185,6 +185,39 @@ func TestRemoteInfo_SkipsNonConformingMetadataName(t *testing.T) {
|
|||||||
assert.NotContains(t, doc, "unreadable_manifests")
|
assert.NotContains(t, doc, "unreadable_manifests")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRemoteInfo_DoesNotCountNonBlobFileUnderBlobs checks that a file
|
||||||
|
// under blobs/ whose name is not a blob hash is not counted as a blob.
|
||||||
|
// prune never deletes such a file, so counting it as an orphaned blob
|
||||||
|
// would advise a prune that removes nothing.
|
||||||
|
func TestRemoteInfo_DoesNotCountNonBlobFileUnderBlobs(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
env := newListEnv(t)
|
||||||
|
env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC))
|
||||||
|
addBlob(t, env.store.testStorer, testBlobHashA)
|
||||||
|
require.NoError(t, env.store.Put(context.Background(),
|
||||||
|
"blobs/"+testBlobHashA[:2]+"/"+testBlobHashA[2:4]+"/.DS_Store",
|
||||||
|
bytes.NewReader([]byte("junk"))))
|
||||||
|
|
||||||
|
require.NoError(t, env.v.RemoteInfo(false))
|
||||||
|
|
||||||
|
text := env.stdout.String()
|
||||||
|
assert.Contains(t, text, "Total blobs on remote: 1 (")
|
||||||
|
assert.Contains(t, text, "Orphaned (unreferenced): 0 (")
|
||||||
|
assert.NotContains(t, text, "vaultik prune")
|
||||||
|
|
||||||
|
env.stdout.Reset()
|
||||||
|
require.NoError(t, env.v.RemoteInfo(true))
|
||||||
|
|
||||||
|
var doc map[string]any
|
||||||
|
|
||||||
|
require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc))
|
||||||
|
assert.InDelta(t, 1, doc["total_blob_count"], 0)
|
||||||
|
assert.InDelta(t, 0, doc["orphaned_blob_count"], 0)
|
||||||
|
assert.InDelta(t, 0, doc["orphaned_blob_size"], 0)
|
||||||
|
}
|
||||||
|
|
||||||
// TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown checks that
|
// TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown checks that
|
||||||
// a directory under metadata/ holding no manifest.json.zst, such as one
|
// a directory under metadata/ holding no manifest.json.zst, such as one
|
||||||
// left by a backup interrupted before its manifest upload, leaves the
|
// left by a backup interrupted before its manifest upload, leaves the
|
||||||
|
|||||||
+43
-15
@@ -27,6 +27,7 @@ import (
|
|||||||
// Sentinel errors for restore failures.
|
// Sentinel errors for restore failures.
|
||||||
var (
|
var (
|
||||||
errFilesFailedRestore = errors.New("file(s) failed to restore")
|
errFilesFailedRestore = errors.New("file(s) failed to restore")
|
||||||
|
errPathsNotInSnapshot = errors.New("requested path(s) not in the snapshot")
|
||||||
errFilesFailedVerify = errors.New("files failed verification")
|
errFilesFailedVerify = errors.New("files failed verification")
|
||||||
errDecryptionKeyRequired = errors.New(
|
errDecryptionKeyRequired = errors.New(
|
||||||
"decryption key required for restore\n\n" +
|
"decryption key required for restore\n\n" +
|
||||||
@@ -149,7 +150,7 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error {
|
|||||||
repos := database.NewRepositories(tempDB)
|
repos := database.NewRepositories(tempDB)
|
||||||
|
|
||||||
// Step 2: Get list of files to restore
|
// Step 2: Get list of files to restore
|
||||||
files, err := v.getFilesToRestore(v.ctx, repos, opts.Paths)
|
files, unmatched, err := v.getFilesToRestore(v.ctx, repos, opts.Paths)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("getting files to restore: %w", err)
|
return fmt.Errorf("getting files to restore: %w", err)
|
||||||
}
|
}
|
||||||
@@ -158,7 +159,7 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error {
|
|||||||
log.Warn("No files found to restore")
|
log.Warn("No files found to restore")
|
||||||
v.UI.Warningf("No files found to restore.")
|
v.UI.Warningf("No files found to restore.")
|
||||||
|
|
||||||
return nil
|
return v.reportUnmatchedPaths(unmatched)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info("Found files to restore", "count", len(files))
|
log.Info("Found files to restore", "count", len(files))
|
||||||
@@ -198,14 +199,16 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error {
|
|||||||
v.UI.Duration(result.Duration),
|
v.UI.Duration(result.Duration),
|
||||||
)
|
)
|
||||||
|
|
||||||
return v.finishRestore(repos, files, opts, result)
|
return v.finishRestore(repos, files, unmatched, opts, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
// finishRestore emits the post-restore warnings, runs optional
|
// finishRestore emits the post-restore warnings, runs optional
|
||||||
// verification, and converts any failed-file count into an error.
|
// verification, and converts any failed-file count or requested path
|
||||||
|
// that matched nothing into an error.
|
||||||
func (v *Vaultik) finishRestore(
|
func (v *Vaultik) finishRestore(
|
||||||
repos *database.Repositories,
|
repos *database.Repositories,
|
||||||
files []*database.File,
|
files []*database.File,
|
||||||
|
unmatched []string,
|
||||||
opts *RestoreOptions,
|
opts *RestoreOptions,
|
||||||
result *RestoreResult,
|
result *RestoreResult,
|
||||||
) error {
|
) error {
|
||||||
@@ -223,6 +226,8 @@ func (v *Vaultik) finishRestore(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
unmatchedErr := v.reportUnmatchedPaths(unmatched)
|
||||||
|
|
||||||
// Run verification if requested
|
// Run verification if requested
|
||||||
if opts.Verify {
|
if opts.Verify {
|
||||||
err := v.handleRestoreVerification(repos, files, opts, result)
|
err := v.handleRestoreVerification(repos, files, opts, result)
|
||||||
@@ -235,7 +240,23 @@ func (v *Vaultik) finishRestore(
|
|||||||
return fmt.Errorf("%d %w", result.FilesFailed, errFilesFailedRestore)
|
return fmt.Errorf("%d %w", result.FilesFailed, errFilesFailedRestore)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return unmatchedErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// reportUnmatchedPaths warns, by name, about each requested path that
|
||||||
|
// matched nothing in the snapshot, and returns an error counting them,
|
||||||
|
// or nil when there are none.
|
||||||
|
func (v *Vaultik) reportUnmatchedPaths(unmatched []string) error {
|
||||||
|
if len(unmatched) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, path := range unmatched {
|
||||||
|
log.Warn("Requested path matches nothing in the snapshot", "path", path)
|
||||||
|
v.UI.Warningf("%s matches nothing in the snapshot.", v.UI.Path(path))
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("%d %w", len(unmatched), errPathsNotInSnapshot)
|
||||||
}
|
}
|
||||||
|
|
||||||
// restoreIdentities parses the configured age secret key once into every
|
// restoreIdentities parses the configured age secret key once into every
|
||||||
@@ -812,27 +833,34 @@ func (v *Vaultik) materializeSnapshotDB(
|
|||||||
return db, tempDir, nil
|
return db, tempDir, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// getFilesToRestore returns the list of files to restore based on path filters
|
// getFilesToRestore returns the list of files to restore based on path
|
||||||
|
// filters, and the filters, as given, that matched no file.
|
||||||
func (v *Vaultik) getFilesToRestore(
|
func (v *Vaultik) getFilesToRestore(
|
||||||
ctx context.Context, repos *database.Repositories, pathFilters []string,
|
ctx context.Context, repos *database.Repositories, pathFilters []string,
|
||||||
) ([]*database.File, error) {
|
) ([]*database.File, []string, error) {
|
||||||
// If no filters, get all files
|
// If no filters, get all files
|
||||||
if len(pathFilters) == 0 {
|
if len(pathFilters) == 0 {
|
||||||
return repos.Files.ListAll(ctx)
|
files, err := repos.Files.ListAll(ctx)
|
||||||
|
|
||||||
|
return files, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get files matching the path filters
|
// Get files matching the path filters
|
||||||
var result []*database.File
|
var (
|
||||||
|
result []*database.File
|
||||||
|
unmatched []string
|
||||||
|
)
|
||||||
|
|
||||||
seen := make(map[string]bool)
|
seen := make(map[string]bool)
|
||||||
|
|
||||||
for _, filter := range pathFilters {
|
for _, filter := range pathFilters {
|
||||||
// Normalize the filter path
|
files, err := repos.Files.ListUnderPath(ctx, filepath.Clean(filter))
|
||||||
filter = filepath.Clean(filter)
|
|
||||||
|
|
||||||
files, err := repos.Files.ListUnderPath(ctx, filter)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("listing files under %s: %w", filter, err)
|
return nil, nil, fmt.Errorf("listing files under %s: %w", filter, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(files) == 0 {
|
||||||
|
unmatched = append(unmatched, filter)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
@@ -843,7 +871,7 @@ func (v *Vaultik) getFilesToRestore(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, unmatched, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// buildChunkToBlobMap creates a mapping from chunk hash to blob information
|
// buildChunkToBlobMap creates a mapping from chunk hash to blob information
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package vaultik_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/afero"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/config"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
|
)
|
||||||
|
|
||||||
|
// These tests cover https://git.eeqj.de/sneak/vaultik/issues/309: a path
|
||||||
|
// given to restore that matches nothing in the snapshot is named in a
|
||||||
|
// warning and makes the restore fail, after the paths that do match are
|
||||||
|
// restored.
|
||||||
|
|
||||||
|
func TestRestoreNamesUnmatchedPathAndRestoresTheMatchingOne(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
fs := afero.NewOsFs()
|
||||||
|
tempDir := t.TempDir()
|
||||||
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
cfg := faultTestConfig()
|
||||||
|
files := writeFaultSourceTree(t, fs, dataDir)
|
||||||
|
|
||||||
|
store, err := storage.NewFileStorer(storeDir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
db, err := database.New(ctx, dbPath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
id := fullFaultBackup(ctx, t, fs, store, cfg,
|
||||||
|
database.NewRepositories(db), dataDir, dbPath, "unmatched")
|
||||||
|
require.NoError(t, db.Close())
|
||||||
|
|
||||||
|
matched := filepath.Join(dataDir, "small.txt")
|
||||||
|
unmatched := filepath.Join(dataDir, "typo.txt")
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
|
||||||
|
v := newReaderVaultik(ctx, cfg, store, nil, fs)
|
||||||
|
v.UI = ui.NewWithColor(&out, false)
|
||||||
|
|
||||||
|
err = v.Restore(&vaultik.RestoreOptions{
|
||||||
|
SnapshotID: id,
|
||||||
|
TargetDir: restoreDir,
|
||||||
|
Paths: []string{matched, unmatched},
|
||||||
|
})
|
||||||
|
|
||||||
|
require.Error(t, err, "a path that matches nothing must fail the restore")
|
||||||
|
assert.Contains(t, out.String(), unmatched,
|
||||||
|
"the path that matches nothing must be named")
|
||||||
|
assert.NotContains(t, out.String(), matched,
|
||||||
|
"the path that matches must not be reported")
|
||||||
|
|
||||||
|
got, err := afero.ReadFile(fs, filepath.Join(restoreDir, matched))
|
||||||
|
require.NoError(t, err, "the path that matches must still be restored")
|
||||||
|
assert.Equal(t, files[matched], got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// When no requested path matches, nothing is restored and each path is
|
||||||
|
// named. One path is relative. The other goes through the symlink that
|
||||||
|
// is the snapshot's configured path, while the entries are stored under
|
||||||
|
// the directory the symlink points to.
|
||||||
|
func TestRestoreNamesEveryPathWhenNothingMatches(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const snapshotName = "linked"
|
||||||
|
|
||||||
|
fs := afero.NewOsFs()
|
||||||
|
tempDir := t.TempDir()
|
||||||
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
|
linkDir := filepath.Join(tempDir, "srclink")
|
||||||
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
writeFaultSourceTree(t, fs, dataDir)
|
||||||
|
require.NoError(t, os.Symlink(dataDir, linkDir))
|
||||||
|
|
||||||
|
cfg := faultTestConfig()
|
||||||
|
cfg.IndexPath = dbPath
|
||||||
|
cfg.ChunkSize = config.Size(faultChunkSize)
|
||||||
|
cfg.Snapshots = map[string]config.SnapshotConfig{
|
||||||
|
snapshotName: {Paths: []string{linkDir}},
|
||||||
|
}
|
||||||
|
|
||||||
|
store, err := storage.NewFileStorer(storeDir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
db, err := database.New(ctx, dbPath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
v := newBackupVaultik(ctx, cfg, store, repos, db, fs)
|
||||||
|
|
||||||
|
require.NoError(t, backUp(v, snapshotName))
|
||||||
|
|
||||||
|
id := localSnapshotID(ctx, t, repos, snapshotName)
|
||||||
|
require.NoError(t, db.Close())
|
||||||
|
|
||||||
|
throughLink := filepath.Join(linkDir, "sub")
|
||||||
|
relative := strings.TrimPrefix(filepath.Join(dataDir, "small.txt"), "/")
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
|
||||||
|
reader := newReaderVaultik(ctx, cfg, store, nil, fs)
|
||||||
|
reader.UI = ui.NewWithColor(&out, false)
|
||||||
|
|
||||||
|
err = reader.Restore(&vaultik.RestoreOptions{
|
||||||
|
SnapshotID: id,
|
||||||
|
TargetDir: restoreDir,
|
||||||
|
Paths: []string{throughLink, relative},
|
||||||
|
})
|
||||||
|
|
||||||
|
require.Error(t, err, "a restore that matches nothing must fail")
|
||||||
|
assert.Contains(t, out.String(), throughLink,
|
||||||
|
"the path through the symlink must be named")
|
||||||
|
assert.Contains(t, out.String(), relative,
|
||||||
|
"the relative path must be named")
|
||||||
|
|
||||||
|
_, err = fs.Stat(restoreDir)
|
||||||
|
assert.True(t, os.IsNotExist(err), "nothing must be restored")
|
||||||
|
}
|
||||||
@@ -28,8 +28,14 @@ var (
|
|||||||
errNoAgeRecipients = errors.New(
|
errNoAgeRecipients = errors.New(
|
||||||
"creating a snapshot needs at least one public key in " +
|
"creating a snapshot needs at least one public key in " +
|
||||||
"age_recipients (generate a keypair with: age-keygen)")
|
"age_recipients (generate a keypair with: age-keygen)")
|
||||||
|
errKeepNewerThanNeedsPrune = errors.New("--keep-newer-than requires --prune")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrPostBackupPruneFailed wraps a failure of the post-backup prune,
|
||||||
|
// which runs only after every snapshot was created and uploaded, so the
|
||||||
|
// caller can report it apart from a failed backup.
|
||||||
|
var ErrPostBackupPruneFailed = errors.New("post-backup prune failed")
|
||||||
|
|
||||||
// listRecentLimit caps how many snapshot rows are fetched from the
|
// listRecentLimit caps how many snapshot rows are fetched from the
|
||||||
// local index for listing and purge operations.
|
// local index for listing and purge operations.
|
||||||
const listRecentLimit = 10000
|
const listRecentLimit = 10000
|
||||||
@@ -45,6 +51,26 @@ type SnapshotCreateOptions struct {
|
|||||||
Snapshots []string // Optional list of snapshot names to process (empty = all)
|
Snapshots []string // Optional list of snapshot names to process (empty = all)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate fails when KeepNewerThan is set without Prune or is not a
|
||||||
|
// valid duration. Only the post-backup prune reads KeepNewerThan, after
|
||||||
|
// the backup, so the caller checks it before starting one.
|
||||||
|
func (opts *SnapshotCreateOptions) Validate() error {
|
||||||
|
if opts.KeepNewerThan == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if !opts.Prune {
|
||||||
|
return errKeepNewerThanNeedsPrune
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := parseDuration(opts.KeepNewerThan)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("--keep-newer-than: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// CreateSnapshot executes the snapshot creation operation
|
// CreateSnapshot executes the snapshot creation operation
|
||||||
func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error {
|
func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error {
|
||||||
// config.Load accepts an empty list, since listing, verifying and
|
// config.Load accepts an empty list, since listing, verifying and
|
||||||
@@ -123,7 +149,7 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error {
|
|||||||
if opts.Prune {
|
if opts.Prune {
|
||||||
err = v.runPostBackupPrune(snapshotNames, opts.KeepNewerThan)
|
err = v.runPostBackupPrune(snapshotNames, opts.KeepNewerThan)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("post-backup prune: %w", err)
|
return fmt.Errorf("%w: %w", ErrPostBackupPruneFailed, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user