Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43483e21d4 | ||
|
|
167c0a0746 |
@@ -349,9 +349,11 @@ the backup destination store. Blobs are NOT touched — deleting blobs
|
|||||||
requires reading every remaining remote manifest (the destination store
|
requires reading every remaining remote manifest (the destination store
|
||||||
may hold snapshots this host doesn't know about), which is what
|
may hold snapshots this host doesn't know about), which is what
|
||||||
`vaultik prune` does. On success the command prints the exact `vaultik
|
`vaultik prune` does. On success the command prints the exact `vaultik
|
||||||
prune` invocation to run as a follow-up. Local row cleanup (files,
|
prune` invocation to run as a follow-up. An ID that names no snapshot in
|
||||||
chunks, blobs the snapshot was the last referrer for) runs
|
the local index or on the destination store is an error; with
|
||||||
automatically. If the destination store is unreachable, the local-DB
|
`--local-only`, the snapshot must be in the local index. Local row
|
||||||
|
cleanup (files, chunks, blobs the snapshot was the last referrer for)
|
||||||
|
runs automatically. If the destination store is unreachable, the local-DB
|
||||||
removal still completes and a warning is emitted; run `vaultik snapshot
|
removal still completes and a warning is emitted; run `vaultik snapshot
|
||||||
remove <snapshot-id>` again once the store is reachable to remove the
|
remove <snapshot-id>` again once the store is reachable to remove the
|
||||||
snapshot's metadata from it (`vaultik prune` does not). To wipe everything
|
snapshot's metadata from it (`vaultik prune` does not). To wipe everything
|
||||||
|
|||||||
@@ -22,14 +22,24 @@ the tag exists and is exercised; what is left is merging `next` to
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
- 2026-10-13: Made a failed or interrupted backup remove the temporary
|
- 2026-10-13: Made an S3 listing that the server cuts short an error
|
||||||
file of the blob it was packing
|
([issue #297](https://git.eeqj.de/sneak/vaultik/issues/297)). A page
|
||||||
([issue #302](https://git.eeqj.de/sneak/vaultik/issues/302)). When
|
marked truncated with no continuation token, as a server answering V2
|
||||||
`snapshot create` stopped on a file error, a full temporary directory
|
listings V1-style sends, ended the listing without an error, so
|
||||||
or Ctrl-C, that blob was never finalized and its `vaultik-blob-*.tmp`
|
`prune` saw only the snapshots on the first page and could delete
|
||||||
file, up to `blob_size_limit` of encrypted data, stayed in `$TMPDIR`;
|
blobs the rest still use. Such a page is now a listing error, and
|
||||||
every such run left another. Phase 2 now removes it whenever it stops
|
`prune`, `snapshot list` and `remote nuke` handle it as a destination
|
||||||
before the last blob is finalized.
|
that cannot be listed.
|
||||||
|
|
||||||
|
- 2026-10-13: Made `snapshot remove` fail for a snapshot that does not
|
||||||
|
exist ([issue #293](https://git.eeqj.de/sneak/vaultik/issues/293)).
|
||||||
|
The command never checked the ID: it reported the snapshot removed
|
||||||
|
from the local database and from the destination store and exited 0,
|
||||||
|
under `--json`, `--dry-run` and `--local-only` too. An ID that names
|
||||||
|
no snapshot in the local index or on the destination store is now an
|
||||||
|
error; with `--local-only`, the snapshot must be in the local index.
|
||||||
|
The command now reports a removal from either side only when one
|
||||||
|
happened, and `remote_removed` is true only when metadata was deleted.
|
||||||
|
|
||||||
- 2026-10-12: Bound the local index to the destination an `s3.*` config
|
- 2026-10-12: Bound the local index to the destination an `s3.*` config
|
||||||
names ([issue #298](https://git.eeqj.de/sneak/vaultik/issues/298)).
|
names ([issue #298](https://git.eeqj.de/sneak/vaultik/issues/298)).
|
||||||
|
|||||||
@@ -245,17 +245,6 @@ func (p *Packer) Flush(ctx context.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DiscardCurrentBlob closes and removes the temp file of the blob being
|
|
||||||
// packed, if any, and drops that blob. A caller that stops before Flush
|
|
||||||
// must call it, or the temp file is left behind. Thread-safe.
|
|
||||||
func (p *Packer) DiscardCurrentBlob() {
|
|
||||||
p.mu.Lock()
|
|
||||||
defer p.mu.Unlock()
|
|
||||||
|
|
||||||
p.cleanupTempFile()
|
|
||||||
p.currentBlob = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// FinalizeBlob finalizes the current blob being assembled.
|
// FinalizeBlob finalizes the current blob being assembled.
|
||||||
// This compresses the accumulated chunks, encrypts the result, and computes
|
// This compresses the accumulated chunks, encrypts the result, and computes
|
||||||
// the content-addressed hash. The finalized blob is either passed to the
|
// the content-addressed hash. The finalized blob is either passed to the
|
||||||
|
|||||||
@@ -255,8 +255,12 @@ manifest (the destination store may hold snapshots this host doesn't
|
|||||||
know about), which is what 'vaultik prune' does. On success the command
|
know about), which is what 'vaultik prune' does. On success the command
|
||||||
prints the exact 'vaultik prune' invocation to run as a follow-up.
|
prints the exact 'vaultik prune' invocation to run as a follow-up.
|
||||||
|
|
||||||
|
An ID that names no snapshot in the local index or on the destination
|
||||||
|
store is an error.
|
||||||
|
|
||||||
Use --local-only to skip the remote half (e.g. when you want to forget a
|
Use --local-only to skip the remote half (e.g. when you want to forget a
|
||||||
snapshot locally without touching the destination store).
|
snapshot locally without touching the destination store); the snapshot
|
||||||
|
must then be in the local index.
|
||||||
|
|
||||||
If the remote is unreachable, the local-database removal still completes
|
If the remote is unreachable, the local-database removal still completes
|
||||||
and a warning is emitted; run 'vaultik snapshot remove <snapshot-id>' again
|
and a warning is emitted; run 'vaultik snapshot remove <snapshot-id>' again
|
||||||
|
|||||||
+29
-2
@@ -18,6 +18,13 @@ 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
|
||||||
@@ -214,7 +221,7 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro
|
|||||||
})
|
})
|
||||||
|
|
||||||
for paginator.HasMorePages() {
|
for paginator.HasMorePages() {
|
||||||
page, err := paginator.NextPage(ctx)
|
page, err := nextListPage(ctx, paginator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -235,6 +242,26 @@ 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.
|
||||||
@@ -300,7 +327,7 @@ func (c *Client) ListObjectsStream(
|
|||||||
})
|
})
|
||||||
|
|
||||||
for paginator.HasMorePages() {
|
for paginator.HasMorePages() {
|
||||||
page, err := paginator.NextPage(ctx)
|
page, err := nextListPage(ctx, paginator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ch <- ObjectInfo{Err: err}
|
ch <- ObjectInfo{Err: err}
|
||||||
|
|
||||||
|
|||||||
@@ -1295,11 +1295,6 @@ func (s *Scanner) batchAddFilesToSnapshot(
|
|||||||
func (s *Scanner) processPhase(
|
func (s *Scanner) processPhase(
|
||||||
ctx context.Context, filesToProcess []*FileToProcess, result *ScanResult,
|
ctx context.Context, filesToProcess []*FileToProcess, result *ScanResult,
|
||||||
) error {
|
) error {
|
||||||
// On an error or cancellation the blob being packed is never
|
|
||||||
// finalized, so its temp file must be removed here. After a
|
|
||||||
// successful flush there is no such blob and this does nothing.
|
|
||||||
defer s.packer.DiscardCurrentBlob()
|
|
||||||
|
|
||||||
// Calculate total bytes to process
|
// Calculate total bytes to process
|
||||||
var totalBytes int64
|
var totalBytes int64
|
||||||
for _, f := range filesToProcess {
|
for _, f := range filesToProcess {
|
||||||
|
|||||||
@@ -381,60 +381,3 @@ func TestScannerCancelStopsSkipErrorsRun(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestScannerRemovesBlobTempFileWhenRunStops checks that a run stopped
|
|
||||||
// part-way, by a file it cannot read or by a cancellation, removes the
|
|
||||||
// temp file of the blob it was packing.
|
|
||||||
func TestScannerRemovesBlobTempFileWhenRunStops(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// a.txt is backed up first and starts a blob; the run stops at b.txt.
|
|
||||||
const target = "/source/b.txt"
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
newFs func(cancel context.CancelFunc) afero.Fs
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "file cannot be read",
|
|
||||||
newFs: func(context.CancelFunc) afero.Fs {
|
|
||||||
return &readFailFs{Fs: afero.NewMemMapFs(), target: target}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "cancelled",
|
|
||||||
newFs: func(cancel context.CancelFunc) afero.Fs {
|
|
||||||
return &cancelOnOpenFs{
|
|
||||||
Fs: afero.NewMemMapFs(), target: target, cancel: cancel,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
fs := tt.newFs(cancel)
|
|
||||||
writeSkipErrorTestFile(t, fs, "/source/a.txt", "first file content")
|
|
||||||
writeSkipErrorTestFile(t, fs, target, "second file content")
|
|
||||||
|
|
||||||
_, err := runSkipErrorScan(ctx, t, fs, "/source", false, nil)
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("expected the scan to stop with an error, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
left, err := afero.Glob(fs, filepath.Join(os.TempDir(), "vaultik-blob-*"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("listing blob temp files: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(left) != 0 {
|
|
||||||
t.Fatalf("expected no blob temp file left, got %v", left)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"slices"
|
"slices"
|
||||||
@@ -22,13 +23,16 @@ 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 that build a storer from a config.Config. The
|
// Credentials for the tests' S3 clients. The test servers accept any.
|
||||||
// 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,
|
||||||
@@ -55,7 +59,7 @@ func newS3Storer(t *testing.T) storage.Storer {
|
|||||||
Bucket: s3TestBucket,
|
Bucket: s3TestBucket,
|
||||||
AccessKeyID: "test",
|
AccessKeyID: "test",
|
||||||
SecretAccessKey: "test",
|
SecretAccessKey: "test",
|
||||||
Region: "us-east-1",
|
Region: s3TestRegion,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("new client: %v", err)
|
t.Fatalf("new client: %v", err)
|
||||||
@@ -93,6 +97,68 @@ 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
|
||||||
|
|||||||
@@ -3,17 +3,21 @@ package vaultik_test
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"database/sql"
|
||||||
"io"
|
"io"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/klauspost/compress/zstd"
|
"github.com/klauspost/compress/zstd"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
"sneak.berlin/go/vaultik/internal/log"
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
"sneak.berlin/go/vaultik/internal/snapshot"
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
"sneak.berlin/go/vaultik/internal/storage"
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
|
"sneak.berlin/go/vaultik/internal/types"
|
||||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -214,6 +218,37 @@ func addBlob(t *testing.T, store *testStorer, hash string) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newLocalIndex returns an in-memory local index holding a completed
|
||||||
|
// snapshot row for each of ids.
|
||||||
|
func newLocalIndex(t *testing.T, ids ...string) *database.Repositories {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
db, err := database.New(ctx, ":memory:")
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = db.Close() })
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
for _, id := range ids {
|
||||||
|
completedAt := time.Now().UTC()
|
||||||
|
snap := &database.Snapshot{
|
||||||
|
ID: types.SnapshotID(id),
|
||||||
|
Hostname: snapHostname,
|
||||||
|
StartedAt: completedAt,
|
||||||
|
CompletedAt: &completedAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
err = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
return repos.Snapshots.Create(ctx, tx, snap)
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return repos
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Unit Tests for RemoveSnapshot
|
// Unit Tests for RemoveSnapshot
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -233,6 +268,7 @@ func TestRemoveSnapshot_LocalOnly_PreservesRemote(t *testing.T) {
|
|||||||
addBlob(t, store, blobA)
|
addBlob(t, store, blobA)
|
||||||
|
|
||||||
tv := vaultik.NewForTesting(store)
|
tv := vaultik.NewForTesting(store)
|
||||||
|
tv.Repositories = newLocalIndex(t, "snapshot-001")
|
||||||
|
|
||||||
opts := &vaultik.RemoveOptions{Force: true, LocalOnly: true}
|
opts := &vaultik.RemoveOptions{Force: true, LocalOnly: true}
|
||||||
result, err := tv.RemoveSnapshot("snapshot-001", opts)
|
result, err := tv.RemoveSnapshot("snapshot-001", opts)
|
||||||
@@ -268,6 +304,7 @@ func TestRemoveSnapshot_DefaultRemovesMetadataNotBlobs(t *testing.T) {
|
|||||||
addBlob(t, store, blobShared)
|
addBlob(t, store, blobShared)
|
||||||
|
|
||||||
tv := vaultik.NewForTesting(store)
|
tv := vaultik.NewForTesting(store)
|
||||||
|
tv.Repositories = newLocalIndex(t, "snapshot-001", "snapshot-002")
|
||||||
|
|
||||||
opts := &vaultik.RemoveOptions{Force: true}
|
opts := &vaultik.RemoveOptions{Force: true}
|
||||||
result, err := tv.RemoveSnapshot("snapshot-001", opts)
|
result, err := tv.RemoveSnapshot("snapshot-001", opts)
|
||||||
@@ -316,6 +353,84 @@ func TestRemoveSnapshot_DryRun(t *testing.T) {
|
|||||||
assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]")
|
assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRemoveSnapshot_UnknownIDIsError checks that an ID naming no
|
||||||
|
// snapshot in the local index or on the destination store is an error
|
||||||
|
// under every option, and that nothing is reported as removed.
|
||||||
|
func TestRemoveSnapshot_UnknownIDIsError(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
for name, opts := range map[string]vaultik.RemoveOptions{
|
||||||
|
"force": {Force: true},
|
||||||
|
"json": {JSON: true},
|
||||||
|
"dry-run": {Force: true, DryRun: true},
|
||||||
|
"local-only": {Force: true, LocalOnly: true},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
store := newTestStorer()
|
||||||
|
addManifest(t, store, "snapshot-001", nil)
|
||||||
|
|
||||||
|
tv := vaultik.NewForTesting(store)
|
||||||
|
tv.Repositories = newLocalIndex(t, "snapshot-001")
|
||||||
|
|
||||||
|
result, err := tv.RemoveSnapshot("snapshot-999", &opts)
|
||||||
|
|
||||||
|
require.ErrorContains(t, err, "snapshot not found")
|
||||||
|
assert.False(t, result.RemoteRemoved)
|
||||||
|
assert.Empty(t, tv.Stdout.String())
|
||||||
|
assert.True(t, store.hasKey(remoteKeyPath("snapshot-001")))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRemoveSnapshot_NoMetadataOnDestination checks that removing a
|
||||||
|
// snapshot whose metadata is not on the destination store does not
|
||||||
|
// report metadata removed from it.
|
||||||
|
func TestRemoveSnapshot_NoMetadataOnDestination(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tv := vaultik.NewForTesting(newTestStorer())
|
||||||
|
tv.Repositories = newLocalIndex(t, "snapshot-001")
|
||||||
|
|
||||||
|
result, err := tv.RemoveSnapshot("snapshot-001",
|
||||||
|
&vaultik.RemoveOptions{Force: true})
|
||||||
|
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.False(t, result.RemoteRemoved)
|
||||||
|
|
||||||
|
out := tv.Stdout.String()
|
||||||
|
assert.Contains(t, out, "Removed snapshot 'snapshot-001' from local database")
|
||||||
|
assert.NotContains(t, out, "Removed snapshot metadata from remote storage")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRemoveSnapshot_NotInLocalIndex checks that removing a snapshot
|
||||||
|
// only the destination store holds removes its metadata there without
|
||||||
|
// reporting a removal from the local database.
|
||||||
|
func TestRemoveSnapshot_NotInLocalIndex(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
store := newTestStorer()
|
||||||
|
addManifest(t, store, "snapshot-001", nil)
|
||||||
|
|
||||||
|
tv := vaultik.NewForTesting(store)
|
||||||
|
tv.Repositories = newLocalIndex(t)
|
||||||
|
|
||||||
|
result, err := tv.RemoveSnapshot("snapshot-001",
|
||||||
|
&vaultik.RemoveOptions{Force: true})
|
||||||
|
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.True(t, result.RemoteRemoved)
|
||||||
|
assert.False(t, store.hasKey(remoteKeyPath("snapshot-001")))
|
||||||
|
|
||||||
|
out := tv.Stdout.String()
|
||||||
|
assert.NotContains(t, out, "from local database")
|
||||||
|
assert.Contains(t, out, "Removed snapshot metadata from remote storage")
|
||||||
|
}
|
||||||
|
|
||||||
func TestRemoveAllSnapshots_RequiresForce(t *testing.T) {
|
func TestRemoveAllSnapshots_RequiresForce(t *testing.T) {
|
||||||
log.Initialize(log.Config{})
|
log.Initialize(log.Config{})
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ var (
|
|||||||
errNoSnapshotsInConfig = errors.New("no snapshots configured")
|
errNoSnapshotsInConfig = errors.New("no snapshots configured")
|
||||||
errSnapshotVerifyFailed = errors.New("verification failed")
|
errSnapshotVerifyFailed = errors.New("verification failed")
|
||||||
errRemoveAllNeedsForce = errors.New("--all requires --force")
|
errRemoveAllNeedsForce = errors.New("--all requires --force")
|
||||||
|
errSnapshotNotFound = errors.New("snapshot not found")
|
||||||
errInvalidTableName = errors.New("invalid table name")
|
errInvalidTableName = errors.New("invalid table name")
|
||||||
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 " +
|
||||||
@@ -643,7 +644,7 @@ func (v *Vaultik) confirmAndExecutePurge(
|
|||||||
"snapshot_id", snapshotID, "error", err)
|
"snapshot_id", snapshotID, "error", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID))
|
_, err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("deleting snapshot %s from remote: %w", snapshotID, err)
|
return fmt.Errorf("deleting snapshot %s from remote: %w", snapshotID, err)
|
||||||
}
|
}
|
||||||
@@ -1153,6 +1154,11 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inLocalIndex, err := v.findSnapshotToRemove(snapshotID, opts)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
|
||||||
if opts.DryRun {
|
if opts.DryRun {
|
||||||
return v.removeSnapshotDryRun(result, snapshotID, opts)
|
return v.removeSnapshotDryRun(result, snapshotID, opts)
|
||||||
}
|
}
|
||||||
@@ -1161,11 +1167,13 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info("Removing snapshot from local database", "snapshot_id", snapshotID)
|
if inLocalIndex {
|
||||||
|
log.Info("Removing snapshot from local database", "snapshot_id", snapshotID)
|
||||||
|
|
||||||
err = v.deleteSnapshotFromLocalDB(snapshotID)
|
err = v.deleteSnapshotFromLocalDB(snapshotID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return result, fmt.Errorf("removing from local database: %w", err)
|
return result, fmt.Errorf("removing from local database: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
@@ -1184,9 +1192,11 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
return result, v.outputRemoveJSON(result)
|
return result, v.outputRemoveJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID)
|
if inLocalIndex {
|
||||||
|
v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID)
|
||||||
|
}
|
||||||
|
|
||||||
if !opts.LocalOnly && result.RemoteRemoved {
|
if result.RemoteRemoved {
|
||||||
v.printlnStdout("Removed snapshot metadata from remote storage")
|
v.printlnStdout("Removed snapshot metadata from remote storage")
|
||||||
v.stdoutf("\nNote: The removed snapshot's blobs remain on the remote. "+
|
v.stdoutf("\nNote: The removed snapshot's blobs remain on the remote. "+
|
||||||
"Run '%s' to delete any blobs no longer referenced by any "+
|
"Run '%s' to delete any blobs no longer referenced by any "+
|
||||||
@@ -1196,6 +1206,45 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// findSnapshotToRemove reports whether the local index has a row for
|
||||||
|
// snapshotID, and returns errSnapshotNotFound when there is nothing to
|
||||||
|
// remove: no row and, unless LocalOnly is set, no metadata on the
|
||||||
|
// destination store either. The destination store is consulted only
|
||||||
|
// when the local index has no row, so a snapshot in the local index can
|
||||||
|
// still be removed from it while the destination store is unreachable.
|
||||||
|
func (v *Vaultik) findSnapshotToRemove(
|
||||||
|
snapshotID string, opts *RemoveOptions,
|
||||||
|
) (bool, error) {
|
||||||
|
if v.Repositories != nil {
|
||||||
|
snap, err := v.Repositories.Snapshots.GetByID(v.ctx, snapshotID)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("looking up snapshot in local index: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if snap != nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.LocalOnly {
|
||||||
|
return false, fmt.Errorf("%w in the local index: %s",
|
||||||
|
errSnapshotNotFound, snapshotID)
|
||||||
|
}
|
||||||
|
|
||||||
|
objects, err := v.remoteSnapshotObjects(snapshot.RemoteSnapshotKey(snapshotID))
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("looking up snapshot on destination store: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(objects) == 0 {
|
||||||
|
return false, fmt.Errorf(
|
||||||
|
"%w in the local index or on the destination store: %s",
|
||||||
|
errSnapshotNotFound, snapshotID)
|
||||||
|
}
|
||||||
|
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
// removeSnapshotDryRun reports what RemoveSnapshot would do without
|
// removeSnapshotDryRun reports what RemoveSnapshot would do without
|
||||||
// making changes.
|
// making changes.
|
||||||
func (v *Vaultik) removeSnapshotDryRun(
|
func (v *Vaultik) removeSnapshotDryRun(
|
||||||
@@ -1255,14 +1304,14 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions)
|
|||||||
// didn't finish and to run `vaultik snapshot remove` for the snapshot
|
// didn't finish and to run `vaultik snapshot remove` for the snapshot
|
||||||
// again once the destination store is reachable (`vaultik prune` never
|
// again once the destination store is reachable (`vaultik prune` never
|
||||||
// removes snapshot metadata). Returns true when the remote removal
|
// removes snapshot metadata). Returns true when the remote removal
|
||||||
// succeeded.
|
// succeeded and deleted something.
|
||||||
func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) bool {
|
func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) bool {
|
||||||
log.Info("Removing snapshot metadata from remote storage",
|
log.Info("Removing snapshot metadata from remote storage",
|
||||||
"snapshot_id", snapshotID)
|
"snapshot_id", snapshotID)
|
||||||
|
|
||||||
remoteKey := snapshot.RemoteSnapshotKey(snapshotID)
|
remoteKey := snapshot.RemoteSnapshotKey(snapshotID)
|
||||||
|
|
||||||
err := v.deleteRemoteSnapshotByKey(remoteKey)
|
deleted, err := v.deleteRemoteSnapshotByKey(remoteKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warn("Could not remove snapshot metadata from remote storage; "+
|
log.Warn("Could not remove snapshot metadata from remote storage; "+
|
||||||
"run '"+snapshotRemoveCommandHint+"' with the snapshot's ID "+
|
"run '"+snapshotRemoveCommandHint+"' with the snapshot's ID "+
|
||||||
@@ -1280,7 +1329,7 @@ func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) b
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return true
|
return deleted > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveAllSnapshots removes every snapshot known to the local
|
// RemoveAllSnapshots removes every snapshot known to the local
|
||||||
@@ -1572,7 +1621,7 @@ func (v *Vaultik) removeAllLocalSnapshots(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
err = v.deleteRemoteSnapshotByKey(
|
_, err = v.deleteRemoteSnapshotByKey(
|
||||||
snapshot.RemoteSnapshotKey(snapshotID))
|
snapshot.RemoteSnapshotKey(snapshotID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warn("Failed to remove snapshot metadata from remote",
|
log.Warn("Failed to remove snapshot metadata from remote",
|
||||||
@@ -1598,7 +1647,7 @@ func (v *Vaultik) removeAllOrphanRemotes(
|
|||||||
for _, key := range orphanRemoteKeys {
|
for _, key := range orphanRemoteKeys {
|
||||||
log.Info("Removing orphan remote snapshot", "remote_key", key)
|
log.Info("Removing orphan remote snapshot", "remote_key", key)
|
||||||
|
|
||||||
err := v.deleteRemoteSnapshotByKey(key)
|
_, err := v.deleteRemoteSnapshotByKey(key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warn("Failed to remove orphan from remote",
|
log.Warn("Failed to remove orphan from remote",
|
||||||
"remote_key", key, "error", err)
|
"remote_key", key, "error", err)
|
||||||
@@ -1645,34 +1694,44 @@ func (v *Vaultik) deleteSnapshotFromLocalDB(snapshotID string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// deleteRemoteSnapshotByKey removes everything under
|
// deleteRemoteSnapshotByKey removes everything under
|
||||||
// metadata/<remoteKey>/ on the destination store. The argument is a
|
// metadata/<remoteKey>/ on the destination store and returns how many
|
||||||
// remote key (double-SHA256 derivation), not a human snapshot ID;
|
// objects it deleted. The argument is a remote key (double-SHA256
|
||||||
// callers that have a human ID must hash via snapshot.RemoteSnapshotKey
|
// derivation), not a human snapshot ID; callers that have a human ID
|
||||||
// first.
|
// must hash via snapshot.RemoteSnapshotKey first.
|
||||||
func (v *Vaultik) deleteRemoteSnapshotByKey(remoteKey string) error {
|
func (v *Vaultik) deleteRemoteSnapshotByKey(remoteKey string) (int, error) {
|
||||||
prefix := fmt.Sprintf("metadata/%s/", remoteKey)
|
objectsToDelete, err := v.remoteSnapshotObjects(remoteKey)
|
||||||
objectCh := v.Storage.ListStream(v.ctx, prefix)
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
var objectsToDelete []string
|
|
||||||
|
|
||||||
for object := range objectCh {
|
|
||||||
if object.Err != nil {
|
|
||||||
return fmt.Errorf("listing objects: %w", object.Err)
|
|
||||||
}
|
|
||||||
|
|
||||||
objectsToDelete = append(objectsToDelete, object.Key)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, key := range objectsToDelete {
|
for i, key := range objectsToDelete {
|
||||||
err := v.Storage.Delete(v.ctx, key)
|
err = v.Storage.Delete(v.ctx, key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("removing %s: %w", key, err)
|
return i, fmt.Errorf("removing %s: %w", key, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug("Deleted remote object", "key", key)
|
log.Debug("Deleted remote object", "key", key)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return len(objectsToDelete), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// remoteSnapshotObjects lists the keys of every object under
|
||||||
|
// metadata/<remoteKey>/ on the destination store.
|
||||||
|
func (v *Vaultik) remoteSnapshotObjects(remoteKey string) ([]string, error) {
|
||||||
|
prefix := fmt.Sprintf("metadata/%s/", remoteKey)
|
||||||
|
|
||||||
|
var keys []string
|
||||||
|
|
||||||
|
for object := range v.Storage.ListStream(v.ctx, prefix) {
|
||||||
|
if object.Err != nil {
|
||||||
|
return nil, fmt.Errorf("listing objects: %w", object.Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
keys = append(keys, object.Key)
|
||||||
|
}
|
||||||
|
|
||||||
|
return keys, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// outputRemoveJSON outputs the removal result as JSON
|
// outputRemoveJSON outputs the removal result as JSON
|
||||||
|
|||||||
Reference in New Issue
Block a user