Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c6af49bb6 |
@@ -293,8 +293,8 @@ needed.
|
||||
**`snapshot list`**: Show every snapshot known to this host — the union
|
||||
of the local index and the backup destination store — with timestamps
|
||||
and three sizes per snapshot (compressed remote size; total
|
||||
uncompressed chunk size; size of the chunks that snapshot stored that
|
||||
were not stored before, recorded when its backup ran).
|
||||
uncompressed chunk size; size of chunks newly referenced by that
|
||||
snapshot).
|
||||
|
||||
Listing the destination store does **not** require the age secret key,
|
||||
so it works in vaultik's intended configuration, where the backed-up
|
||||
@@ -307,8 +307,8 @@ only the hash, so hostname and snapshot name exist solely in the local
|
||||
index and in the encrypted per-snapshot database. Snapshots found only
|
||||
on the destination store are therefore listed as
|
||||
`<remote only:<abbreviated remote key>>` and show `<remote only>` in
|
||||
the uncompressed and "new chunk" columns, which come only from the
|
||||
local index. Their timestamp and compressed size are real,
|
||||
the uncompressed and "new chunk" columns, which can only be computed
|
||||
from the local index. Their timestamp and compressed size are real,
|
||||
read from the manifest.
|
||||
|
||||
Snapshots in the local index with no counterpart on the destination
|
||||
|
||||
@@ -119,7 +119,6 @@ Tracks backup snapshots.
|
||||
- `completed_at` (INTEGER) - Completion timestamp (NULL if in progress)
|
||||
- `file_count` (INTEGER) - Number of files in snapshot
|
||||
- `chunk_count` (INTEGER) - Number of chunks this snapshot stored that were not stored before
|
||||
- `new_chunk_size` (INTEGER) - Total size of those chunks before compression; `snapshot list` shows it as NEW CHUNK SIZE
|
||||
- `blob_count` (INTEGER) - Number of blobs this snapshot created
|
||||
- `total_size` (INTEGER) - Total size of all files
|
||||
- `blob_size` (INTEGER) - Total compressed size of all referenced blobs
|
||||
|
||||
@@ -58,12 +58,7 @@ func (r *BlobChunkRepository) GetByBlobID(
|
||||
return nil, fmt.Errorf("querying blob chunks: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var blobChunks []*BlobChunk
|
||||
|
||||
|
||||
@@ -83,12 +83,7 @@ func (r *BlobRepository) GetAll(ctx context.Context) (map[string]*Blob, error) {
|
||||
return nil, fmt.Errorf("querying blobs: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
out := make(map[string]*Blob)
|
||||
|
||||
|
||||
@@ -61,12 +61,7 @@ func (r *ChunkFileRepository) GetByChunkHash(
|
||||
return nil, fmt.Errorf("querying chunk files: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return r.scanChunkFiles(rows)
|
||||
}
|
||||
@@ -87,12 +82,7 @@ func (r *ChunkFileRepository) GetByFilePath(
|
||||
return nil, fmt.Errorf("querying chunk files: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return r.scanChunkFiles(rows)
|
||||
}
|
||||
@@ -112,12 +102,7 @@ func (r *ChunkFileRepository) GetByFileID(
|
||||
return nil, fmt.Errorf("querying chunk files: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return r.scanChunkFiles(rows)
|
||||
}
|
||||
|
||||
@@ -107,12 +107,7 @@ func (r *ChunkRepository) GetByHashes(
|
||||
return nil, fmt.Errorf("querying chunks: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var chunks []*Chunk
|
||||
|
||||
@@ -152,12 +147,7 @@ func (r *ChunkRepository) ListUnpacked(
|
||||
return nil, fmt.Errorf("querying unpacked chunks: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var chunks []*Chunk
|
||||
|
||||
|
||||
@@ -38,12 +38,7 @@ func (r *ChunkRepository) list(ctx context.Context, query string) ([]*Chunk, err
|
||||
return nil, fmt.Errorf("querying chunks: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var chunks []*Chunk
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Fatalf prints an error message to stderr and exits with status 1
|
||||
func Fatalf(format string, args ...any) {
|
||||
fmt.Fprintf(os.Stderr, "FATAL: "+format+"\n", args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -62,12 +62,7 @@ func (r *FileChunkRepository) GetByPath(
|
||||
return nil, fmt.Errorf("querying file chunks: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return r.scanFileChunks(rows)
|
||||
}
|
||||
@@ -88,12 +83,7 @@ func (r *FileChunkRepository) GetByFileID(
|
||||
return nil, fmt.Errorf("querying file chunks: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return r.scanFileChunks(rows)
|
||||
}
|
||||
@@ -117,12 +107,7 @@ func (r *FileChunkRepository) GetByPathTx(
|
||||
return nil, fmt.Errorf("querying file chunks: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
fileChunks, err := r.scanFileChunks(rows)
|
||||
LogSQL("GetByPathTx", "Complete", path, "count", len(fileChunks))
|
||||
|
||||
@@ -175,12 +175,7 @@ func (r *FileRepository) ListModifiedSince(
|
||||
return nil, fmt.Errorf("querying files: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var files []*File
|
||||
|
||||
@@ -256,12 +251,7 @@ func (r *FileRepository) ListUnderPath(
|
||||
return nil, fmt.Errorf("querying files: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var files []*File
|
||||
|
||||
@@ -304,12 +294,7 @@ func (r *FileRepository) ListIDsWithChunksNotInUploadedBlobs(
|
||||
return nil, fmt.Errorf("querying files: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var ids []types.FileID
|
||||
|
||||
@@ -340,12 +325,7 @@ func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) {
|
||||
return nil, fmt.Errorf("querying files: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var files []*File
|
||||
|
||||
|
||||
@@ -106,22 +106,24 @@ func (r *Repositories) WithReadTx(ctx context.Context, fn TxFunc) error {
|
||||
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
rollbackErr := tx.Rollback()
|
||||
if rollbackErr != nil {
|
||||
Fatalf("failed to rollback transaction: %v", rollbackErr)
|
||||
}
|
||||
// The panic is the failure to report, so a rollback error
|
||||
// is dropped.
|
||||
_ = tx.Rollback()
|
||||
|
||||
panic(p)
|
||||
} else if err != nil {
|
||||
rollbackErr := tx.Rollback()
|
||||
if rollbackErr != nil {
|
||||
Fatalf("failed to rollback transaction: %v", rollbackErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
err = fn(ctx, tx)
|
||||
if err != nil {
|
||||
// Once ctx is cancelled, database/sql rolls the transaction
|
||||
// back itself and Rollback returns sql.ErrTxDone.
|
||||
rollbackErr := tx.Rollback()
|
||||
if rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) {
|
||||
return fmt.Errorf("%w; rolling back transaction: %w",
|
||||
err, rollbackErr)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -411,3 +411,41 @@ func TestRepositoriesReadTransaction(t *testing.T) {
|
||||
t.Error("expected to retrieve file in read transaction")
|
||||
}
|
||||
}
|
||||
|
||||
// When the context is cancelled during a read transaction's body,
|
||||
// database/sql rolls the transaction back itself, so WithReadTx's own
|
||||
// rollback finds it already done. WithReadTx must return the body's error
|
||||
// alone, without that rollback.
|
||||
func TestRepositoriesReadTransactionContextCancelled(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
db, cleanup := setupTestDB(t)
|
||||
defer cleanup()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
repos := database.NewRepositories(db)
|
||||
|
||||
err := repos.WithReadTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||
cancel()
|
||||
|
||||
// database/sql rolls back from a goroutine of its own; wait
|
||||
// until it has, so the test does not depend on that race.
|
||||
for {
|
||||
_, err := tx.ExecContext(context.WithoutCancel(ctx), "SELECT 1")
|
||||
if errors.Is(err, sql.ErrTxDone) {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("expected context.Canceled, got: %v", err)
|
||||
}
|
||||
|
||||
if errors.Is(err, sql.ErrTxDone) {
|
||||
t.Fatalf("the already-done rollback was reported: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,6 @@ CREATE TABLE IF NOT EXISTS snapshots (
|
||||
completed_at INTEGER,
|
||||
file_count INTEGER NOT NULL DEFAULT 0,
|
||||
chunk_count INTEGER NOT NULL DEFAULT 0,
|
||||
new_chunk_size INTEGER NOT NULL DEFAULT 0,
|
||||
blob_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_size INTEGER NOT NULL DEFAULT 0,
|
||||
blob_size INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
@@ -129,7 +129,6 @@ func (r *SnapshotRepository) UpdateExtendedStats(
|
||||
compressionLevel int,
|
||||
uploadBytes int64,
|
||||
uploadDurationMs int64,
|
||||
newChunkSize int64,
|
||||
) error {
|
||||
compressionRatio, err := r.extendedCompressionRatio(
|
||||
ctx, tx, snapshotID, blobUncompressedSize,
|
||||
@@ -144,19 +143,18 @@ func (r *SnapshotRepository) UpdateExtendedStats(
|
||||
compression_ratio = ?,
|
||||
compression_level = ?,
|
||||
upload_bytes = ?,
|
||||
upload_duration_ms = ?,
|
||||
new_chunk_size = ?
|
||||
upload_duration_ms = ?
|
||||
WHERE id = ?
|
||||
`
|
||||
|
||||
if tx != nil {
|
||||
_, err = tx.ExecContext(ctx, query,
|
||||
blobUncompressedSize, compressionRatio, compressionLevel,
|
||||
uploadBytes, uploadDurationMs, newChunkSize, snapshotID)
|
||||
uploadBytes, uploadDurationMs, snapshotID)
|
||||
} else {
|
||||
_, err = r.db.ExecWithLog(ctx, query,
|
||||
blobUncompressedSize, compressionRatio, compressionLevel,
|
||||
uploadBytes, uploadDurationMs, newChunkSize, snapshotID)
|
||||
uploadBytes, uploadDurationMs, snapshotID)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -241,12 +239,7 @@ func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, er
|
||||
return nil, fmt.Errorf("querying snapshots: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
snapshots, err := r.scanSnapshotRows(rows)
|
||||
if err != nil {
|
||||
@@ -281,12 +274,7 @@ func (r *SnapshotRepository) ListRecent(
|
||||
return nil, fmt.Errorf("querying snapshots: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return r.scanSnapshotRows(rows)
|
||||
}
|
||||
@@ -501,12 +489,7 @@ func (r *SnapshotRepository) GetBlobHashes(
|
||||
return nil, fmt.Errorf("querying blob hashes: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var blobs []string
|
||||
|
||||
@@ -596,24 +579,45 @@ func (r *SnapshotRepository) GetSnapshotUncompressedChunkSize(
|
||||
return totalSize, nil
|
||||
}
|
||||
|
||||
// GetSnapshotNewChunkSize returns the total plaintext size of the chunks the
|
||||
// snapshot's backup stored that were not stored before, as the backup
|
||||
// recorded it. It is not derived from the snapshot's files: a file's row is
|
||||
// shared by every snapshot that lists it and is rewritten when the file
|
||||
// changes, so it shows only the file's latest chunks.
|
||||
// GetSnapshotNewChunkSize returns the sum of plaintext sizes of chunks that are
|
||||
// referenced by this snapshot but not by any earlier completed snapshot known to
|
||||
// the local database. The result is the marginal uncompressed data this snapshot
|
||||
// added to the dedup pool — i.e., the delta from prior snapshots.
|
||||
func (r *SnapshotRepository) GetSnapshotNewChunkSize(
|
||||
ctx context.Context, snapshotID string,
|
||||
) (int64, error) {
|
||||
query := `SELECT new_chunk_size FROM snapshots WHERE id = ?`
|
||||
query := `
|
||||
WITH this_snap_chunks AS (
|
||||
SELECT DISTINCT fc.chunk_hash
|
||||
FROM snapshot_files sf
|
||||
JOIN file_chunks fc ON sf.file_id = fc.file_id
|
||||
WHERE sf.snapshot_id = ?
|
||||
),
|
||||
prior_chunks AS (
|
||||
SELECT DISTINCT fc.chunk_hash
|
||||
FROM snapshots s
|
||||
JOIN snapshot_files sf ON sf.snapshot_id = s.id
|
||||
JOIN file_chunks fc ON fc.file_id = sf.file_id
|
||||
WHERE s.completed_at IS NOT NULL
|
||||
AND s.id != ?
|
||||
AND s.started_at < (SELECT started_at FROM snapshots WHERE id = ?)
|
||||
)
|
||||
SELECT COALESCE(SUM(c.size), 0)
|
||||
FROM chunks c
|
||||
JOIN this_snap_chunks t ON c.chunk_hash = t.chunk_hash
|
||||
WHERE c.chunk_hash NOT IN (SELECT chunk_hash FROM prior_chunks)
|
||||
`
|
||||
|
||||
var newChunkSize int64
|
||||
var totalSize int64
|
||||
|
||||
err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&newChunkSize)
|
||||
err := r.db.conn.QueryRowContext(
|
||||
ctx, query, snapshotID, snapshotID, snapshotID,
|
||||
).Scan(&totalSize)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("querying new chunk size: %w", err)
|
||||
}
|
||||
|
||||
return newChunkSize, nil
|
||||
return totalSize, nil
|
||||
}
|
||||
|
||||
// GetIncompleteSnapshots returns all snapshots that haven't been completed
|
||||
@@ -634,12 +638,7 @@ func (r *SnapshotRepository) GetIncompleteSnapshots(
|
||||
return nil, fmt.Errorf("querying incomplete snapshots: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
return r.scanSnapshotRows(rows)
|
||||
}
|
||||
@@ -662,12 +661,7 @@ func (r *SnapshotRepository) GetIncompleteByHostname(
|
||||
return nil, fmt.Errorf("querying incomplete snapshots: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := rows.Close()
|
||||
if err != nil {
|
||||
Fatalf("failed to close rows: %v", err)
|
||||
}
|
||||
}()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
// Same column set as every other multi-row snapshot query, so the
|
||||
// shared scanner applies — including its timestamp normalization.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//nolint:testpackage // exercises the unexported cleanupBlobTempFile
|
||||
package snapshot
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"sneak.berlin/go/vaultik/internal/blob"
|
||||
)
|
||||
|
||||
// A blob temp file that cannot be closed or removed must make the cleanup
|
||||
// return an error, not end the process.
|
||||
func TestCleanupBlobTempFileReturnsErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewOsFs()
|
||||
s := &Scanner{fs: fs}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// prepare runs before the cleanup and makes its close or remove
|
||||
// fail.
|
||||
prepare func(tempFile afero.File) error
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "close fails",
|
||||
prepare: func(tempFile afero.File) error { return tempFile.Close() },
|
||||
want: os.ErrClosed,
|
||||
},
|
||||
{
|
||||
name: "remove fails",
|
||||
prepare: func(tempFile afero.File) error {
|
||||
return fs.Remove(tempFile.Name())
|
||||
},
|
||||
want: os.ErrNotExist,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tempFile, err := afero.TempFile(fs, t.TempDir(), "blob-*.tmp")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = tt.prepare(tempFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = s.cleanupBlobTempFile(&blob.WithReader{TempFile: tempFile})
|
||||
if !errors.Is(err, tt.want) {
|
||||
t.Fatalf("expected an error wrapping %v, got: %v", tt.want, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -135,9 +135,7 @@ type ScannerConfig struct {
|
||||
// are counted per file: BytesScanned is the size of the new and changed
|
||||
// files, BytesSkipped that of the unchanged ones. FilesFailed counts the
|
||||
// new and changed files that phase 2 could not store; FilesScanned
|
||||
// includes them and BytesScanned does not. ChunksCreated counts the
|
||||
// chunks that were not already stored, and NewChunkSize is their total
|
||||
// size.
|
||||
// includes them and BytesScanned does not.
|
||||
type ScanResult struct {
|
||||
FilesScanned int
|
||||
FilesSkipped int
|
||||
@@ -147,7 +145,6 @@ type ScanResult struct {
|
||||
BytesSkipped int64
|
||||
BytesDeleted int64
|
||||
ChunksCreated int
|
||||
NewChunkSize int64
|
||||
BlobsCreated int
|
||||
BlobsUploaded int
|
||||
BytesUploaded int64
|
||||
@@ -1556,19 +1553,23 @@ func (s *Scanner) handleBlobReady(
|
||||
blobExists, err := s.uploadBlobIfNeeded(
|
||||
ctx, blobPath, blobWithReader, startTime, result)
|
||||
if err != nil {
|
||||
s.cleanupBlobTempFile(blobWithReader)
|
||||
cleanupErr := s.cleanupBlobTempFile(blobWithReader)
|
||||
|
||||
return fmt.Errorf("uploading blob %s: %w", finishedBlob.Hash, err)
|
||||
return errors.Join(
|
||||
fmt.Errorf("uploading blob %s: %w", finishedBlob.Hash, err), cleanupErr)
|
||||
}
|
||||
|
||||
err = s.recordBlobMetadata(ctx, finishedBlob, blobExists, startTime)
|
||||
if err != nil {
|
||||
s.cleanupBlobTempFile(blobWithReader)
|
||||
cleanupErr := s.cleanupBlobTempFile(blobWithReader)
|
||||
|
||||
return err
|
||||
return errors.Join(err, cleanupErr)
|
||||
}
|
||||
|
||||
s.cleanupBlobTempFile(blobWithReader)
|
||||
err = s.cleanupBlobTempFile(blobWithReader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Chunks from this blob are now committed to DB - remove from pending set
|
||||
s.removePendingChunkHashes(blobWithReader.InsertedChunkHashes)
|
||||
@@ -1762,20 +1763,22 @@ func (s *Scanner) recordBlobMetadata(
|
||||
}
|
||||
|
||||
// cleanupBlobTempFile closes and removes the blob's temporary file
|
||||
func (s *Scanner) cleanupBlobTempFile(blobWithReader *blob.WithReader) {
|
||||
func (s *Scanner) cleanupBlobTempFile(blobWithReader *blob.WithReader) error {
|
||||
if blobWithReader.TempFile != nil {
|
||||
tempName := blobWithReader.TempFile.Name()
|
||||
|
||||
err := blobWithReader.TempFile.Close()
|
||||
if err != nil {
|
||||
log.Fatal("Failed to close temp file", "file", tempName, "error", err)
|
||||
return fmt.Errorf("closing blob temp file: %w", err)
|
||||
}
|
||||
|
||||
err = s.fs.Remove(tempName)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to remove temp file", "file", tempName, "error", err)
|
||||
return fmt.Errorf("removing blob temp file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// streamingChunkInfo tracks chunk metadata collected during streaming
|
||||
@@ -1869,12 +1872,11 @@ func (s *Scanner) processFileStreaming(
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateChunkStats counts a chunk that was not already stored, and its
|
||||
// size. The scan result's file counts, BytesScanned and BytesSkipped are
|
||||
// not touched here: the scan phase counts each file once.
|
||||
// updateChunkStats counts a chunk that was not already stored. The scan
|
||||
// result's file counts, BytesScanned and BytesSkipped are not touched
|
||||
// here: the scan phase counts each file once.
|
||||
func (s *Scanner) updateChunkStats(chunkSize int64, result *ScanResult) {
|
||||
result.ChunksCreated++
|
||||
result.NewChunkSize += chunkSize
|
||||
|
||||
if s.progress != nil {
|
||||
s.progress.GetStats().ChunksCreated.Add(1)
|
||||
|
||||
@@ -199,7 +199,6 @@ func (sm *SnapshotManager) UpdateSnapshotStatsExtended(
|
||||
stats.CompressionLevel,
|
||||
stats.BytesUploaded,
|
||||
stats.UploadDurationMs,
|
||||
stats.NewChunkSize,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -907,7 +906,6 @@ type ExtendedBackupStats struct {
|
||||
BlobUncompressedSize int64 // Total uncompressed size of all referenced blobs
|
||||
CompressionLevel int // Compression level used for this snapshot
|
||||
UploadDurationMs int64 // Total milliseconds spent uploading to S3
|
||||
NewChunkSize int64 // Total size of the chunks counted in ChunksCreated
|
||||
}
|
||||
|
||||
// deleteOtherSnapshots deletes all snapshots except the current one
|
||||
|
||||
@@ -1,20 +1,15 @@
|
||||
package vaultik_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/require"
|
||||
"sneak.berlin/go/vaultik/internal/config"
|
||||
"sneak.berlin/go/vaultik/internal/log"
|
||||
"sneak.berlin/go/vaultik/internal/storage"
|
||||
"sneak.berlin/go/vaultik/internal/ui"
|
||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||
)
|
||||
@@ -82,161 +77,6 @@ func TestDeepVerifyAcceptsHealthyAndRejectsCorruptBlob(t *testing.T) {
|
||||
"deep verify should fail on a corrupted blob")
|
||||
}
|
||||
|
||||
// TestDeepVerifyJSONCountsBlobs checks the counts that deep verify
|
||||
// reports under --json: on a healthy snapshot, with a blob that cannot
|
||||
// be checked, with a damaged blob, with missing blobs, and with a blob
|
||||
// of the wrong size. Deep verify stops at the first damaged blob, so the
|
||||
// blobs read before it are the ones verified; when blobs are missing or
|
||||
// the wrong size it reads no blob contents, but counts every such blob.
|
||||
func TestDeepVerifyJSONCountsBlobs(t *testing.T) {
|
||||
log.Initialize(log.Config{})
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewOsFs()
|
||||
tempDir := t.TempDir()
|
||||
|
||||
dataDir := filepath.Join(tempDir, "source")
|
||||
storeDir := filepath.Join(tempDir, "remote")
|
||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||
|
||||
chunkSize := int64(32 * 1024)
|
||||
maxBlobSize := int64(128 * 1024)
|
||||
|
||||
// Random data does not compress or deduplicate, so it fills several
|
||||
// blobs.
|
||||
data := make([]byte, maxBlobSize*4)
|
||||
_, err := rand.Read(data)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, fs.MkdirAll(dataDir, 0o755))
|
||||
require.NoError(t, afero.WriteFile(fs,
|
||||
filepath.Join(dataDir, "data.bin"), data, 0o644))
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
cfg, storer, snapshotID := runFileStorageBackup(
|
||||
ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize)
|
||||
|
||||
healthy, err := deepVerifyJSON(ctx, t, cfg, storer, snapshotID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "ok", healthy.Status)
|
||||
require.GreaterOrEqual(t, healthy.BlobCount, 3)
|
||||
require.Equal(t, healthy.BlobCount, healthy.Verified)
|
||||
require.Zero(t, healthy.Missing)
|
||||
|
||||
// Deep verify reads blobs in hash order, which is the sorted order of
|
||||
// their storage keys.
|
||||
keys, err := storer.List(ctx, "blobs/")
|
||||
require.NoError(t, err)
|
||||
slices.Sort(keys)
|
||||
require.Len(t, keys, healthy.BlobCount)
|
||||
|
||||
// A blob that is present but cannot be checked is not missing: the
|
||||
// check stops with the storage error.
|
||||
denied := &statDeniedStorer{Storer: storer, deniedKey: keys[0]}
|
||||
|
||||
got, err := deepVerifyJSON(ctx, t, cfg, denied, snapshotID)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "failed", got.Status)
|
||||
require.Zero(t, got.Missing)
|
||||
require.Contains(t, got.ErrorMessage, os.ErrPermission.Error())
|
||||
|
||||
// Damage the last blob read, keeping its length, so every blob before
|
||||
// it is read and passes first.
|
||||
lastPath := filepath.Join(storeDir, keys[len(keys)-1])
|
||||
blob, err := afero.ReadFile(fs, lastPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
blob[len(blob)/2] ^= 0xff
|
||||
require.NoError(t, afero.WriteFile(fs, lastPath, blob, 0o600))
|
||||
|
||||
got, err = deepVerifyJSON(ctx, t, cfg, storer, snapshotID)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "failed", got.Status)
|
||||
require.Equal(t, healthy.BlobCount-1, got.Verified)
|
||||
require.Zero(t, got.Missing)
|
||||
|
||||
// Delete the first blob and the damaged last one: both must be
|
||||
// counted as missing, not only the first one found.
|
||||
var deletedSize int64
|
||||
|
||||
for _, key := range []string{keys[0], keys[len(keys)-1]} {
|
||||
info, statErr := storer.Stat(ctx, key)
|
||||
require.NoError(t, statErr)
|
||||
|
||||
deletedSize += info.Size
|
||||
|
||||
require.NoError(t, storer.Delete(ctx, key))
|
||||
}
|
||||
|
||||
got, err = deepVerifyJSON(ctx, t, cfg, storer, snapshotID)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "failed", got.Status)
|
||||
require.Equal(t, 2, got.Missing)
|
||||
require.Equal(t, deletedSize, got.MissingSize)
|
||||
require.Zero(t, got.Verified)
|
||||
|
||||
// Make a blob between the two deleted ones longer: it is counted as
|
||||
// the wrong size, and both missing blobs are still counted.
|
||||
grownPath := filepath.Join(storeDir, keys[1])
|
||||
blob, err = afero.ReadFile(fs, grownPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
blob = append(blob, []byte("extra")...)
|
||||
require.NoError(t, afero.WriteFile(fs, grownPath, blob, 0o600))
|
||||
|
||||
got, err = deepVerifyJSON(ctx, t, cfg, storer, snapshotID)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "failed", got.Status)
|
||||
require.Equal(t, 1, got.Mismatched)
|
||||
require.Equal(t, 2, got.Missing)
|
||||
require.Zero(t, got.Verified)
|
||||
}
|
||||
|
||||
// statDeniedStorer passes every call through to the wrapped Storer,
|
||||
// except that Stat of deniedKey fails with a permission error, as it
|
||||
// does for a blob that is present but cannot be read.
|
||||
type statDeniedStorer struct {
|
||||
storage.Storer
|
||||
|
||||
deniedKey string
|
||||
}
|
||||
|
||||
func (s *statDeniedStorer) Stat(
|
||||
ctx context.Context, key string,
|
||||
) (*storage.ObjectInfo, error) {
|
||||
if key == s.deniedKey {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
|
||||
return s.Storer.Stat(ctx, key)
|
||||
}
|
||||
|
||||
// deepVerifyJSON runs deep verify with --json on snapshotID and returns
|
||||
// the decoded result and the error RunDeepVerify returned.
|
||||
func deepVerifyJSON(
|
||||
ctx context.Context, t *testing.T,
|
||||
cfg *config.Config, storer storage.Storer, snapshotID string,
|
||||
) (vaultik.VerifyResult, error) {
|
||||
t.Helper()
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
v := &vaultik.Vaultik{
|
||||
Config: cfg,
|
||||
Storage: storer,
|
||||
Fs: afero.NewOsFs(),
|
||||
Stdout: &out,
|
||||
Stderr: io.Discard,
|
||||
UI: ui.NewWithColor(io.Discard, false),
|
||||
}
|
||||
v.SetContext(ctx)
|
||||
|
||||
err := v.RunDeepVerify(snapshotID,
|
||||
&vaultik.VerifyOptions{Deep: true, JSON: true})
|
||||
|
||||
return decodeVerifyResult(t, out.Bytes()), err
|
||||
}
|
||||
|
||||
// corruptOneBlob flips a middle byte of the first blob file found under
|
||||
// blobsDir, leaving the file length unchanged.
|
||||
func corruptOneBlob(t *testing.T, fs afero.Fs, blobsDir string) {
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
package vaultik_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"maps"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"sneak.berlin/go/vaultik/internal/chunker"
|
||||
"sneak.berlin/go/vaultik/internal/database"
|
||||
"sneak.berlin/go/vaultik/internal/log"
|
||||
"sneak.berlin/go/vaultik/internal/storage"
|
||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||
)
|
||||
|
||||
// TestNewChunkSizeOfChangedFileStaysFixed covers
|
||||
// https://git.eeqj.de/sneak/vaultik/issues/311. A backup whose only change
|
||||
// is a modified file lists the size of the chunks that change added as its
|
||||
// NEW CHUNK SIZE, and a later backup that changes the file again leaves
|
||||
// every earlier snapshot's figure as it was. The file's row in the local
|
||||
// index is shared by all three snapshots and rewritten by each backup.
|
||||
func TestNewChunkSizeOfChangedFileStaysFixed(t *testing.T) {
|
||||
log.Initialize(log.Config{})
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewOsFs()
|
||||
tempDir := t.TempDir()
|
||||
dataDir := filepath.Join(tempDir, "src")
|
||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||
changedPath := filepath.Join(dataDir, "changed.bin")
|
||||
|
||||
ctx := context.Background()
|
||||
files := writeFaultSourceTree(t, fs, dataDir)
|
||||
cfg := changedFileConfig(dataDir, dbPath)
|
||||
|
||||
appendRandomBytes(t, fs, files, changedPath, appendedFileSize)
|
||||
|
||||
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
||||
require.NoError(t, err)
|
||||
|
||||
db, err := database.New(ctx, dbPath)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
|
||||
repos := database.NewRepositories(db)
|
||||
v := newBackupVaultik(ctx, cfg, store, repos, db, fs)
|
||||
|
||||
require.NoError(t, backUp(v, "first"))
|
||||
|
||||
firstFiles := maps.Clone(files)
|
||||
firstID := localSnapshotID(ctx, t, repos, "first")
|
||||
|
||||
appendRandomBytes(t, fs, files, changedPath, faultChunkSize)
|
||||
require.NoError(t, backUp(v, "second"))
|
||||
|
||||
secondID := localSnapshotID(ctx, t, repos, "second")
|
||||
secondAdded := sizeOfNewChunks(t, files, firstFiles)
|
||||
require.Positive(t, secondAdded)
|
||||
assert.Equal(t, secondAdded, listedNewChunkSizes(t, v)[secondID],
|
||||
"the second snapshot must count the chunks the change added")
|
||||
|
||||
appendRandomBytes(t, fs, files, changedPath, faultChunkSize)
|
||||
require.NoError(t, backUp(v, "third"))
|
||||
|
||||
sizes := listedNewChunkSizes(t, v)
|
||||
assert.Equal(t, sizeOfNewChunks(t, firstFiles, nil), sizes[firstID],
|
||||
"a later backup must not change the first snapshot's figure")
|
||||
assert.Equal(t, secondAdded, sizes[secondID],
|
||||
"a later backup must not change the second snapshot's figure")
|
||||
}
|
||||
|
||||
// sizeOfNewChunks returns the total size of the distinct chunks of the
|
||||
// files in after that no file in before has, cut the way the backup cuts
|
||||
// them.
|
||||
func sizeOfNewChunks(t *testing.T, after, before map[string][]byte) int64 {
|
||||
t.Helper()
|
||||
|
||||
known := make(map[string]bool)
|
||||
for _, chunk := range chunksOf(t, before) {
|
||||
known[chunk.Hash] = true
|
||||
}
|
||||
|
||||
var total int64
|
||||
|
||||
for _, chunk := range chunksOf(t, after) {
|
||||
if !known[chunk.Hash] {
|
||||
known[chunk.Hash] = true
|
||||
total += chunk.Size
|
||||
}
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
// chunksOf returns the chunks of every file in files.
|
||||
func chunksOf(t *testing.T, files map[string][]byte) []chunker.Chunk {
|
||||
t.Helper()
|
||||
|
||||
c := chunker.NewChunker(faultChunkSize)
|
||||
|
||||
var all []chunker.Chunk
|
||||
|
||||
for _, content := range files {
|
||||
chunks, err := c.ChunkReader(bytes.NewReader(content))
|
||||
require.NoError(t, err)
|
||||
|
||||
all = append(all, chunks...)
|
||||
}
|
||||
|
||||
return all
|
||||
}
|
||||
|
||||
// listedNewChunkSizes runs `snapshot list --json` and returns each listed
|
||||
// snapshot's new_chunk_size by snapshot ID.
|
||||
func listedNewChunkSizes(t *testing.T, v *vaultik.Vaultik) map[string]int64 {
|
||||
t.Helper()
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
v.Stdout = &out
|
||||
require.NoError(t, v.ListSnapshots(true))
|
||||
|
||||
sizes := make(map[string]int64)
|
||||
for _, row := range decodeListJSON(t, out.String()) {
|
||||
sizes[row.ID] = row.NewChunkSize
|
||||
}
|
||||
|
||||
return sizes
|
||||
}
|
||||
@@ -309,22 +309,11 @@ func (v *Vaultik) restoreAllFiles(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
plan, unplanned, err := newRestorePlan(
|
||||
v.ctx, repos, files, chunkToBlobMap, blobIDToHash)
|
||||
plan, err := newRestorePlan(v.ctx, repos, files, chunkToBlobMap, blobIDToHash)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("building restore plan: %w", err)
|
||||
}
|
||||
|
||||
// Ranging over files rather than the map reports them in a stable order.
|
||||
for _, file := range files {
|
||||
if planErr, ok := unplanned[file.ID]; ok {
|
||||
err = v.handleRestoreFileError(plan, opts, result, file, file.ID, planErr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filesByID, totalBytesExpected := indexRestoreFiles(files)
|
||||
|
||||
v.UI.Beginf("Restoring %s files (%s) to %s.",
|
||||
|
||||
@@ -61,8 +61,8 @@ func craftedFile(
|
||||
}
|
||||
|
||||
// TestRestoreShortChunkHashInNoBlob proves a file whose short chunk hash
|
||||
// has no blob_chunks row is left out of the restore plan with an error,
|
||||
// and fails the chunk write with an error.
|
||||
// has no blob_chunks row fails restore planning and the chunk write with
|
||||
// an error.
|
||||
func TestRestoreShortChunkHashInNoBlob(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -77,11 +77,9 @@ func TestRestoreShortChunkHashInNoBlob(t *testing.T) {
|
||||
chunkToBlobMap, err := v.buildChunkToBlobMap(ctx, repos)
|
||||
require.NoError(t, err)
|
||||
|
||||
plan, unplanned, err := newRestorePlan(ctx, repos, []*database.File{file},
|
||||
_, err = newRestorePlan(ctx, repos, []*database.File{file},
|
||||
chunkToBlobMap, map[string]string{})
|
||||
require.NoError(t, err)
|
||||
require.ErrorIs(t, unplanned[file.ID], errPlanChunkMissing)
|
||||
require.False(t, plan.hasPending())
|
||||
require.ErrorIs(t, err, errPlanChunkMissing)
|
||||
|
||||
fileChunks, err := repos.FileChunks.GetByFileID(ctx, file.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -41,25 +41,20 @@ type restorePlan struct {
|
||||
|
||||
// newRestorePlan builds the file→blob index for the given files. Files
|
||||
// whose chunks reference no blobs (symlinks, directories) start in the
|
||||
// ready queue immediately. A file with a chunk that no blob holds cannot
|
||||
// be restored: it is left out of the plan and returned, by ID, with the
|
||||
// reason.
|
||||
// ready queue immediately.
|
||||
func newRestorePlan(
|
||||
ctx context.Context,
|
||||
repos *database.Repositories,
|
||||
files []*database.File,
|
||||
chunkToBlobMap map[string]*database.BlobChunk,
|
||||
blobIDToHash map[string]string,
|
||||
) (*restorePlan, map[types.FileID]error, error) {
|
||||
) (*restorePlan, error) {
|
||||
p := &restorePlan{
|
||||
fileBlobs: make(map[types.FileID]map[string]struct{}, len(files)),
|
||||
blobFiles: make(map[string]map[types.FileID]struct{}),
|
||||
ready: make([]types.FileID, 0, len(files)),
|
||||
cached: make(map[string]struct{}),
|
||||
}
|
||||
unplanned := make(map[types.FileID]error)
|
||||
|
||||
nextFile:
|
||||
for _, f := range files {
|
||||
if f.IsSymlink() || f.Mode&uint32(os.ModeDir) != 0 {
|
||||
// No chunks to fetch — restore can run immediately.
|
||||
@@ -71,7 +66,7 @@ nextFile:
|
||||
|
||||
fileChunks, err := repos.FileChunks.GetByFileID(ctx, f.ID)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("planning %s: %w", f.Path, err)
|
||||
return nil, fmt.Errorf("planning %s: %w", f.Path, err)
|
||||
}
|
||||
|
||||
blobs := make(map[string]struct{})
|
||||
@@ -79,18 +74,14 @@ nextFile:
|
||||
for _, fc := range fileChunks {
|
||||
bc, ok := chunkToBlobMap[fc.ChunkHash.String()]
|
||||
if !ok {
|
||||
unplanned[f.ID] = fmt.Errorf("%w: %s",
|
||||
errPlanChunkMissing, shortHash(fc.ChunkHash.String()))
|
||||
|
||||
continue nextFile
|
||||
return nil, fmt.Errorf("planning %s: %w: %s",
|
||||
f.Path, errPlanChunkMissing, shortHash(fc.ChunkHash.String()))
|
||||
}
|
||||
|
||||
hash, ok := blobIDToHash[bc.BlobID.String()]
|
||||
if !ok {
|
||||
unplanned[f.ID] = fmt.Errorf("%w: %s",
|
||||
errPlanBlobIDMissing, bc.BlobID)
|
||||
|
||||
continue nextFile
|
||||
return nil, fmt.Errorf("planning %s: %w: %s",
|
||||
f.Path, errPlanBlobIDMissing, bc.BlobID)
|
||||
}
|
||||
|
||||
blobs[hash] = struct{}{}
|
||||
@@ -112,7 +103,7 @@ nextFile:
|
||||
}
|
||||
}
|
||||
|
||||
return p, unplanned, nil
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// markBlobCached records that the named blob is now resident in the
|
||||
|
||||
@@ -28,8 +28,7 @@ const (
|
||||
)
|
||||
|
||||
// missingBlobBackup is a snapshot of single-chunk files spread over two
|
||||
// blobs, with one of those blobs lost: deleted from the store, or missing
|
||||
// from the snapshot metadata.
|
||||
// blobs, with one of those blobs deleted from the store.
|
||||
type missingBlobBackup struct {
|
||||
fs afero.Fs
|
||||
cfg *config.Config
|
||||
@@ -38,39 +37,20 @@ type missingBlobBackup struct {
|
||||
restoreDir string
|
||||
// files holds the original content by source path.
|
||||
files map[string][]byte
|
||||
// lost holds the source paths whose chunk is in the lost blob.
|
||||
// lost holds the source paths whose chunk is in the deleted blob.
|
||||
lost map[string]bool
|
||||
}
|
||||
|
||||
// TestRestoreSkipErrorsSkipsFilesOfMissingBlob restores with SkipErrors
|
||||
// after one blob of a two-blob snapshot was deleted from the store.
|
||||
// after one blob of a two-blob snapshot was deleted. Every file stored in
|
||||
// that blob must be reported as failed and left absent, every other file
|
||||
// must be restored intact, and Restore must still return an error.
|
||||
func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) {
|
||||
log.Initialize(log.Config{})
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
assertRestoreSkipsLostFiles(ctx, t, backupThenDeleteOneBlob(ctx, t))
|
||||
}
|
||||
|
||||
// TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob restores with
|
||||
// SkipErrors a snapshot whose metadata lists chunks that no blob holds, as
|
||||
// earlier backup defects left behind.
|
||||
func TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob(t *testing.T) {
|
||||
log.Initialize(log.Config{})
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
assertRestoreSkipsLostFiles(ctx, t, backupThenDropOneBlobFromMetadata(ctx, t))
|
||||
}
|
||||
|
||||
// assertRestoreSkipsLostFiles restores backup with SkipErrors. Every file
|
||||
// stored in the lost blob must be reported as failed and left absent,
|
||||
// every other file must be restored intact, and Restore must still return
|
||||
// an error.
|
||||
func assertRestoreSkipsLostFiles(
|
||||
ctx context.Context, t *testing.T, backup *missingBlobBackup,
|
||||
) {
|
||||
t.Helper()
|
||||
backup := backupThenDeleteOneBlob(ctx, t)
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
@@ -92,14 +72,14 @@ func assertRestoreSkipsLostFiles(
|
||||
|
||||
if backup.lost[path] {
|
||||
assert.Containsf(t, out.String(), path,
|
||||
"%s needs the lost blob and must be reported", path)
|
||||
"%s needs the deleted blob and must be reported", path)
|
||||
assert.NoFileExists(t, restored)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
got, err := afero.ReadFile(backup.fs, restored)
|
||||
require.NoErrorf(t, err, "%s does not need the lost blob", path)
|
||||
require.NoErrorf(t, err, "%s does not need the deleted blob", path)
|
||||
assert.Equalf(t, content, got, "%s restored with wrong content", path)
|
||||
}
|
||||
}
|
||||
@@ -123,30 +103,6 @@ func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) {
|
||||
require.ErrorIs(t, err, storage.ErrNotFound)
|
||||
}
|
||||
|
||||
// TestRestoreChunkInNoBlobAbortsWithoutSkipErrors checks that a chunk held
|
||||
// by no blob still ends the restore, before any file is written, when
|
||||
// SkipErrors is not set.
|
||||
func TestRestoreChunkInNoBlobAbortsWithoutSkipErrors(t *testing.T) {
|
||||
log.Initialize(log.Config{})
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
backup := backupThenDropOneBlobFromMetadata(ctx, t)
|
||||
|
||||
v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs)
|
||||
|
||||
err := v.Restore(&vaultik.RestoreOptions{
|
||||
SnapshotID: backup.snapshotID,
|
||||
TargetDir: backup.restoreDir,
|
||||
})
|
||||
|
||||
require.ErrorContains(t, err, "chunk missing from blob map")
|
||||
|
||||
for path := range backup.files {
|
||||
assert.NoFileExists(t, filepath.Join(backup.restoreDir, path))
|
||||
}
|
||||
}
|
||||
|
||||
// backupThenDeleteOneBlob backs up missingBlobFileCount single-chunk
|
||||
// files, then deletes from the store the blob holding the first of them.
|
||||
func backupThenDeleteOneBlob(
|
||||
@@ -154,54 +110,6 @@ func backupThenDeleteOneBlob(
|
||||
) *missingBlobBackup {
|
||||
t.Helper()
|
||||
|
||||
backup, db, lostBlob := backupSingleChunkFiles(ctx, t)
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
require.NoError(t, backup.storer.Delete(ctx, fmt.Sprintf(
|
||||
"blobs/%s/%s/%s", lostBlob[:2], lostBlob[2:4], lostBlob)))
|
||||
|
||||
return backup
|
||||
}
|
||||
|
||||
// backupThenDropOneBlobFromMetadata backs up missingBlobFileCount
|
||||
// single-chunk files, then removes the blob holding the first of them from
|
||||
// the snapshot and exports the snapshot metadata again. The exported
|
||||
// metadata then lists chunks that no blob holds.
|
||||
func backupThenDropOneBlobFromMetadata(
|
||||
ctx context.Context, t *testing.T,
|
||||
) *missingBlobBackup {
|
||||
t.Helper()
|
||||
|
||||
backup, db, lostBlob := backupSingleChunkFiles(ctx, t)
|
||||
|
||||
// The uploads row refers to the blob row, so it would keep the export
|
||||
// from deleting it.
|
||||
for _, query := range []string{
|
||||
"DELETE FROM snapshot_blobs WHERE blob_hash = ?",
|
||||
"DELETE FROM uploads WHERE blob_hash = ?",
|
||||
} {
|
||||
_, err := db.Conn().ExecContext(ctx, query, lostBlob)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
sm := newFaultSnapshotManager(
|
||||
backup.fs, backup.storer, backup.cfg, database.NewRepositories(db))
|
||||
require.NoError(t,
|
||||
sm.ExportSnapshotMetadata(ctx, db.Path(), backup.snapshotID))
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
return backup
|
||||
}
|
||||
|
||||
// backupSingleChunkFiles backs up missingBlobFileCount single-chunk files.
|
||||
// It returns the backup, with lost naming the files stored in the same
|
||||
// blob as the first of them, the still open local index, and the hash of
|
||||
// that blob.
|
||||
func backupSingleChunkFiles(
|
||||
ctx context.Context, t *testing.T,
|
||||
) (*missingBlobBackup, *database.DB, string) {
|
||||
t.Helper()
|
||||
|
||||
fs := afero.NewOsFs()
|
||||
tempDir := t.TempDir()
|
||||
dataDir := filepath.Join(tempDir, "src")
|
||||
@@ -235,11 +143,16 @@ func backupSingleChunkFiles(
|
||||
blobOfFile[path] = blobHashOfSingleChunkFile(ctx, t, repos, path)
|
||||
}
|
||||
|
||||
lostBlob := blobOfFile[filepath.Join(dataDir, "file-00.bin")]
|
||||
require.NoError(t, db.Close())
|
||||
|
||||
deleted := blobOfFile[filepath.Join(dataDir, "file-00.bin")]
|
||||
require.NoError(t, storer.Delete(ctx, fmt.Sprintf(
|
||||
"blobs/%s/%s/%s", deleted[:2], deleted[2:4], deleted)))
|
||||
|
||||
lost := make(map[string]bool)
|
||||
|
||||
for path, hash := range blobOfFile {
|
||||
if hash == lostBlob {
|
||||
if hash == deleted {
|
||||
lost[path] = true
|
||||
}
|
||||
}
|
||||
@@ -255,7 +168,7 @@ func backupSingleChunkFiles(
|
||||
restoreDir: filepath.Join(tempDir, "restored"),
|
||||
files: files,
|
||||
lost: lost,
|
||||
}, db, lostBlob
|
||||
}
|
||||
}
|
||||
|
||||
// blobHashOfSingleChunkFile returns the hash of the blob holding the one
|
||||
|
||||
@@ -209,7 +209,6 @@ type snapshotStats struct {
|
||||
totalFiles int
|
||||
totalBytes int64
|
||||
totalChunks int
|
||||
newChunkSize int64
|
||||
totalBlobs int
|
||||
totalBytesSkipped int64
|
||||
totalFilesSkipped int
|
||||
@@ -342,7 +341,6 @@ func (v *Vaultik) scanAllDirectories(
|
||||
stats.totalFiles += result.FilesScanned
|
||||
stats.totalBytes += result.BytesScanned
|
||||
stats.totalChunks += result.ChunksCreated
|
||||
stats.newChunkSize += result.NewChunkSize
|
||||
stats.totalBlobs += result.BlobsCreated
|
||||
stats.totalFilesSkipped += result.FilesSkipped
|
||||
stats.totalFilesFailed += result.FilesFailed
|
||||
@@ -405,7 +403,6 @@ func (v *Vaultik) finalizeSnapshotMetadata(
|
||||
BlobUncompressedSize: stats.blobUncompressedSize,
|
||||
CompressionLevel: v.Config.CompressionLevel,
|
||||
UploadDurationMs: stats.uploadDuration.Milliseconds(),
|
||||
NewChunkSize: stats.newChunkSize,
|
||||
}
|
||||
|
||||
err = v.SnapshotManager.UpdateSnapshotStatsExtended(v.ctx, snapshotID, extStats)
|
||||
|
||||
@@ -487,7 +487,6 @@ type listJSONRow struct {
|
||||
RemoteKey string `json:"remote_key"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
CompressedSize int64 `json:"compressed_size"`
|
||||
NewChunkSize int64 `json:"new_chunk_size"`
|
||||
LocallyTracked bool `json:"locally_tracked"`
|
||||
RemotePresent *bool `json:"remote_present"`
|
||||
}
|
||||
|
||||
+17
-39
@@ -17,7 +17,6 @@ import (
|
||||
"sneak.berlin/go/vaultik/internal/database"
|
||||
"sneak.berlin/go/vaultik/internal/log"
|
||||
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||
"sneak.berlin/go/vaultik/internal/storage"
|
||||
)
|
||||
|
||||
// Sentinel errors for snapshot verification failures.
|
||||
@@ -33,9 +32,7 @@ var (
|
||||
errManifestExtraBlob = errors.New("manifest contains blob not in database")
|
||||
errManifestMissingBlob = errors.New(
|
||||
"manifest omits blob present in database")
|
||||
errBlobSizeMismatch = errors.New("blob size mismatch")
|
||||
errBlobsNotInStorage = errors.New(
|
||||
"blobs missing from storage or stored with the wrong size")
|
||||
errBlobSizeMismatch = errors.New("blob size mismatch")
|
||||
)
|
||||
|
||||
// verifyStatusFailed is the JSON status value for a failed verification.
|
||||
@@ -138,6 +135,7 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error {
|
||||
}
|
||||
|
||||
result.Status = "ok"
|
||||
result.Verified = len(dbBlobs)
|
||||
|
||||
if opts.JSON {
|
||||
return v.outputVerifyJSON(result)
|
||||
@@ -292,7 +290,7 @@ func (v *Vaultik) runVerificationSteps(
|
||||
v.stdoutf("Checking blob existence in remote storage...\n")
|
||||
}
|
||||
|
||||
err = v.verifyBlobExistenceFromDB(dbBlobs, result)
|
||||
err = v.verifyBlobExistenceFromDB(dbBlobs)
|
||||
if err != nil {
|
||||
return v.deepVerifyFailure(result, opts, err.Error(), err)
|
||||
}
|
||||
@@ -303,8 +301,7 @@ func (v *Vaultik) runVerificationSteps(
|
||||
len(dbBlobs), ubytes(totalSize))
|
||||
}
|
||||
|
||||
err = v.performDeepVerificationFromDB(
|
||||
dbBlobs, tdb.db.Conn(), opts, result, identities)
|
||||
err = v.performDeepVerificationFromDB(dbBlobs, tdb.db.Conn(), opts, identities)
|
||||
if err != nil {
|
||||
return v.deepVerifyFailure(result, opts, err.Error(), err)
|
||||
}
|
||||
@@ -656,14 +653,8 @@ func (v *Vaultik) verifyManifestAgainstDatabase(
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyBlobExistenceFromDB checks that every blob from the database is
|
||||
// in storage with the size the database records. It checks them all,
|
||||
// counting the missing and wrong-size blobs in result, and fails if it
|
||||
// found any. Any storage error other than not found stops the check and
|
||||
// fails with that error.
|
||||
func (v *Vaultik) verifyBlobExistenceFromDB(
|
||||
blobs []snapshot.BlobInfo, result *VerifyResult,
|
||||
) error {
|
||||
// verifyBlobExistenceFromDB checks that all blobs from database exist in S3
|
||||
func (v *Vaultik) verifyBlobExistenceFromDB(blobs []snapshot.BlobInfo) error {
|
||||
log.Info("Verifying blob existence in S3", "blob_count", len(blobs))
|
||||
|
||||
for i, blob := range blobs {
|
||||
@@ -676,23 +667,17 @@ func (v *Vaultik) verifyBlobExistenceFromDB(
|
||||
// Construct blob path
|
||||
blobPath := fmt.Sprintf("blobs/%s/%s/%s", blob.Hash[:2], blob.Hash[2:4], blob.Hash)
|
||||
|
||||
// Check blob exists
|
||||
stat, err := v.Storage.Stat(v.ctx, blobPath)
|
||||
switch {
|
||||
case errors.Is(err, storage.ErrNotFound):
|
||||
log.Warn("Blob missing from storage", "hash", blob.Hash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("blob %s missing from storage: %w", blob.Hash, err)
|
||||
}
|
||||
|
||||
result.Missing++
|
||||
result.MissingSize += blob.CompressedSize
|
||||
case err != nil:
|
||||
return fmt.Errorf("checking blob %s in storage: %w",
|
||||
blob.Hash, err)
|
||||
case stat.Size != blob.CompressedSize:
|
||||
log.Warn("Blob has the wrong size in storage",
|
||||
"hash", blob.Hash,
|
||||
"storage_size", stat.Size,
|
||||
"database_size", blob.CompressedSize)
|
||||
|
||||
result.Mismatched++
|
||||
// Verify size matches
|
||||
if stat.Size != blob.CompressedSize {
|
||||
return fmt.Errorf(
|
||||
"%w: blob %s: S3 has %d bytes, database has %d bytes",
|
||||
errBlobSizeMismatch, blob.Hash, stat.Size, blob.CompressedSize)
|
||||
}
|
||||
|
||||
// Progress update every 100 blobs
|
||||
@@ -706,22 +691,16 @@ func (v *Vaultik) verifyBlobExistenceFromDB(
|
||||
}
|
||||
}
|
||||
|
||||
if result.Missing > 0 || result.Mismatched > 0 {
|
||||
return fmt.Errorf("%w: %d missing, %d with the wrong size",
|
||||
errBlobsNotInStorage, result.Missing, result.Mismatched)
|
||||
}
|
||||
|
||||
log.Info("✓ All blobs exist in storage")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// performDeepVerificationFromDB downloads and verifies the content of
|
||||
// each blob using the database as source, stopping at the first blob that
|
||||
// fails. Each blob that passes is counted in result.Verified.
|
||||
// each blob using the database as source.
|
||||
func (v *Vaultik) performDeepVerificationFromDB(
|
||||
blobs []snapshot.BlobInfo, db *sql.DB, opts *VerifyOptions,
|
||||
result *VerifyResult, identities []age.Identity,
|
||||
identities []age.Identity,
|
||||
) error {
|
||||
// Calculate total bytes for ETA
|
||||
var totalBytesExpected int64
|
||||
@@ -744,7 +723,6 @@ func (v *Vaultik) performDeepVerificationFromDB(
|
||||
return fmt.Errorf("blob %s verification failed: %w", blobInfo.Hash, err)
|
||||
}
|
||||
|
||||
result.Verified++
|
||||
bytesProcessed += blobInfo.CompressedSize
|
||||
elapsed := time.Since(startTime)
|
||||
remaining := len(blobs) - (i + 1)
|
||||
|
||||
Reference in New Issue
Block a user