Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc12400268 |
+17
-4
@@ -279,8 +279,8 @@ Key methods:
|
|||||||
- `Scan(ctx, path, snapshotID)` → Main scan operation
|
- `Scan(ctx, path, snapshotID)` → Main scan operation
|
||||||
|
|
||||||
Scan phases:
|
Scan phases:
|
||||||
1. **Phase 1**: Walk directory, identify files needing processing
|
1. **Phase 0**: Detect deleted files from previous snapshots
|
||||||
2. **Phase 1b**: Count as deleted the files that the previous snapshot of the same name lists and the walk did not find; a file that is excluded, or inside an excluded directory, is not counted
|
2. **Phase 1**: Walk directory, identify files needing processing
|
||||||
3. **Phase 2**: Process files (chunk → pack → upload)
|
3. **Phase 2**: Process files (chunk → pack → upload)
|
||||||
|
|
||||||
#### SnapshotManager
|
#### SnapshotManager
|
||||||
@@ -311,6 +311,8 @@ Repository interfaces:
|
|||||||
|
|
||||||
```
|
```
|
||||||
CreateSnapshot(opts)
|
CreateSnapshot(opts)
|
||||||
|
│
|
||||||
|
├─► markDestination() // Refuse a destination without the marker, then write it
|
||||||
│
|
│
|
||||||
├─► PruneDatabase() // Critical: avoid dedup errors
|
├─► PruneDatabase() // Critical: avoid dedup errors
|
||||||
│
|
│
|
||||||
@@ -320,13 +322,13 @@ CreateSnapshot(opts)
|
|||||||
│ │
|
│ │
|
||||||
│ ├─► scanner.Scan(ctx, path, snapshotID)
|
│ ├─► scanner.Scan(ctx, path, snapshotID)
|
||||||
│ │ │
|
│ │ │
|
||||||
|
│ │ ├─► Phase 0: detectDeletedFiles()
|
||||||
|
│ │ │
|
||||||
│ │ ├─► Phase 1: scanPhase()
|
│ │ ├─► Phase 1: scanPhase()
|
||||||
│ │ │ Walk directory
|
│ │ │ Walk directory
|
||||||
│ │ │ Check file metadata changes
|
│ │ │ Check file metadata changes
|
||||||
│ │ │ Build list of files to process
|
│ │ │ Build list of files to process
|
||||||
│ │ │
|
│ │ │
|
||||||
│ │ ├─► Phase 1b: detectDeletedFiles()
|
|
||||||
│ │ │
|
|
||||||
│ │ └─► Phase 2: processPhase()
|
│ │ └─► Phase 2: processPhase()
|
||||||
│ │ For each file:
|
│ │ For each file:
|
||||||
│ │ chunker.ChunkReaderStreaming()
|
│ │ chunker.ChunkReaderStreaming()
|
||||||
@@ -367,6 +369,8 @@ CreateSnapshot(opts)
|
|||||||
|
|
||||||
```
|
```
|
||||||
bucket/
|
bucket/
|
||||||
|
├── vaultik-destination.txt # Marker written by every backup
|
||||||
|
│
|
||||||
├── blobs/
|
├── blobs/
|
||||||
│ └── {hash[0:2]}/
|
│ └── {hash[0:2]}/
|
||||||
│ └── {hash[2:4]}/
|
│ └── {hash[2:4]}/
|
||||||
@@ -378,6 +382,15 @@ bucket/
|
|||||||
└── manifest.json.zst # Blob list (for pruning/verification)
|
└── manifest.json.zst # Blob list (for pruning/verification)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
While the local index holds snapshots, a destination without
|
||||||
|
`vaultik-destination.txt` is treated as not present
|
||||||
|
(`checkDestinationMarker` in `internal/vaultik/destination_marker.go`):
|
||||||
|
`snapshot create` refuses to write to it, and listing it fails as for a
|
||||||
|
destination that cannot be listed. An unplugged volume's empty mount point
|
||||||
|
is therefore never taken for a destination whose snapshots are all gone.
|
||||||
|
The `file://` backend never creates its destination directory, so a write
|
||||||
|
to a missing one fails.
|
||||||
|
|
||||||
The `{remote-key}` directory name is a one-way double SHA-256 hash of the human
|
The `{remote-key}` directory name is a one-way double SHA-256 hash of the human
|
||||||
snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never
|
snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never
|
||||||
written to the store as a directory name. See
|
written to the store as a directory name. See
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ grep 'public key' vaultik_backup_private_key.txt
|
|||||||
vaultik config set age_recipients.0 age1YOUR_PUBLIC_KEY_HERE
|
vaultik config set age_recipients.0 age1YOUR_PUBLIC_KEY_HERE
|
||||||
vaultik config set storage_url "file:///Volumes/usbstick/mybackup"
|
vaultik config set storage_url "file:///Volumes/usbstick/mybackup"
|
||||||
|
|
||||||
|
# create the destination directory; vaultik never creates it, so a backup
|
||||||
|
# to a volume that is not plugged in fails instead of filling the disk
|
||||||
|
mkdir /Volumes/usbstick/mybackup
|
||||||
|
|
||||||
# macOS only: grant your terminal app Full Disk Access first
|
# macOS only: grant your terminal app Full Disk Access first
|
||||||
# (System Settings → Privacy & Security → Full Disk Access), otherwise
|
# (System Settings → Privacy & Security → Full Disk Access), otherwise
|
||||||
# the backup will abort with a permission error on protected directories
|
# the backup will abort with a permission error on protected directories
|
||||||
@@ -289,6 +293,10 @@ needed.
|
|||||||
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
|
Without `--prune`, or with a value that is not a valid duration, the
|
||||||
command fails before the backup starts.
|
command fails before the backup starts.
|
||||||
|
* Fails before it writes anything when a `file://` destination directory
|
||||||
|
does not exist, or when the local index holds snapshots and the
|
||||||
|
destination has no `vaultik-destination.txt` (see
|
||||||
|
[remote storage layout](#remote-storage-layout))
|
||||||
|
|
||||||
**`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
|
||||||
@@ -317,7 +325,10 @@ invocation that reconciles them.
|
|||||||
|
|
||||||
If the destination store cannot be listed (unmounted volume,
|
If the destination store cannot be listed (unmounted volume,
|
||||||
permission denied, network down), the command warns, falls back to the
|
permission denied, network down), the command warns, falls back to the
|
||||||
local index alone, and still exits zero.
|
local index alone, and still exits zero. It does the same when the
|
||||||
|
local index holds snapshots and the destination has no
|
||||||
|
`vaultik-destination.txt`, as when a volume mounted at the destination
|
||||||
|
is unplugged and leaves its empty mount point behind.
|
||||||
* `--json`: Output in JSON format. Each entry carries `locally_tracked`
|
* `--json`: Output in JSON format. Each entry carries `locally_tracked`
|
||||||
(whether the snapshot is in the local index), `remote_key` (the full
|
(whether the snapshot is in the local index), `remote_key` (the full
|
||||||
64-character storage key), and `remote_present` (whether it was seen
|
64-character storage key), and `remote_present` (whether it was seen
|
||||||
@@ -355,11 +366,13 @@ 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; with
|
the local index or on the destination store is an error; with
|
||||||
`--local-only`, the snapshot must be in the local index. Local row
|
`--local-only`, the snapshot must be in the local index. Local row
|
||||||
cleanup (files, chunks, blobs the snapshot was the last referrer for)
|
cleanup (files, chunks, blobs the snapshot was the last referrer for)
|
||||||
runs automatically. If the destination store is unreachable, the local-DB
|
runs automatically. If the destination store is unreachable, or the
|
||||||
removal still completes and a warning is emitted; run `vaultik snapshot
|
local index holds snapshots and the destination has no
|
||||||
remove <snapshot-id>` again once the store is reachable to remove the
|
`vaultik-destination.txt`, the local-DB removal still completes and a
|
||||||
snapshot's metadata from it (`vaultik prune` does not). To wipe everything
|
warning is emitted; run `vaultik snapshot remove <snapshot-id>` again
|
||||||
on the destination in one go, use `vaultik remote nuke --force`.
|
once the store is reachable to remove the snapshot's metadata from it
|
||||||
|
(`vaultik prune` does not). To wipe everything on the destination in one
|
||||||
|
go, use `vaultik remote nuke --force`.
|
||||||
* `--local-only`: Skip remote cleanup; only touch the local index
|
* `--local-only`: Skip remote cleanup; only touch the local index
|
||||||
* `--dry-run`: Show what would be deleted without deleting
|
* `--dry-run`: Show what would be deleted without deleting
|
||||||
* `--force`: Skip confirmation prompt
|
* `--force`: Skip confirmation prompt
|
||||||
@@ -386,7 +399,10 @@ manifest on the destination store to compute the still-referenced blob
|
|||||||
set and delete any blob not in that set. Step (3) reads all remote
|
set and delete any blob not in that set. Step (3) reads all remote
|
||||||
manifests — network cost scales with the number of snapshots. `snapshot
|
manifests — network cost scales with the number of snapshots. `snapshot
|
||||||
create --prune` runs the same cleanup automatically; this is the
|
create --prune` runs the same cleanup automatically; this is the
|
||||||
manual entry point for the same work.
|
manual entry point for the same work. If the destination store cannot
|
||||||
|
be listed, or the local index holds snapshots and the destination has
|
||||||
|
no `vaultik-destination.txt` (an unplugged volume's empty mount point),
|
||||||
|
prune fails and deletes nothing. `snapshot purge` does the same.
|
||||||
* `--force`: Skip confirmation prompt
|
* `--force`: Skip confirmation prompt
|
||||||
* `--json`: Output stats as JSON. Also skips the confirmation prompt, as
|
* `--json`: Output stats as JSON. Also skips the confirmation prompt, as
|
||||||
`--force` does.
|
`--force` does.
|
||||||
@@ -408,10 +424,10 @@ under `blobs/` whose name is not a blob hash is not counted as a blob,
|
|||||||
since `prune` never deletes it.
|
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, every blob and
|
||||||
backup destination store, leaving the bucket prefix empty. Destructive and
|
`vaultik-destination.txt` from the backup destination store, leaving the
|
||||||
irreversible. This is the single supported way to wipe the entire
|
bucket prefix empty. Destructive and irreversible. This is the single
|
||||||
destination store.
|
supported way to wipe the entire destination store.
|
||||||
* `--force`: Required to confirm destruction.
|
* `--force`: Required to confirm destruction.
|
||||||
|
|
||||||
**`database delete`**: Delete the local SQLite state database file
|
**`database delete`**: Delete the local SQLite state database file
|
||||||
@@ -436,7 +452,12 @@ object store. Credentials are read from `s3.access_key_id` and
|
|||||||
a local or mounted filesystem. Useful for testing or backing up to a NAS. The
|
a local or mounted filesystem. Useful for testing or backing up to a NAS. The
|
||||||
path must be absolute; a relative one is refused when the config loads.
|
path must be absolute; a relative one is refused when the config loads.
|
||||||
Percent-escapes in the path are decoded, so `my%20stick` and `my stick` name
|
Percent-escapes in the path are decoded, so `my%20stick` and `my stick` name
|
||||||
the same directory.
|
the same directory. The directory must exist before the first backup: vaultik
|
||||||
|
never creates it. A directory on a removable volume is gone while the volume is
|
||||||
|
not mounted, so a backup then fails instead of writing to the disk under the
|
||||||
|
mount point. The mount point itself stays behind when the volume is unplugged:
|
||||||
|
there only `vaultik-destination.txt` stops such a backup, and only while the
|
||||||
|
local index holds snapshots.
|
||||||
|
|
||||||
**Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud
|
**Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud
|
||||||
providers. Requires rclone to be configured separately (`rclone config`).
|
providers. Requires rclone to be configured separately (`rclone config`).
|
||||||
@@ -467,6 +488,7 @@ For an implementation-level view of the internals — the data model, the
|
|||||||
|
|
||||||
```
|
```
|
||||||
<bucket>/<prefix>/
|
<bucket>/<prefix>/
|
||||||
|
├── vaultik-destination.txt # Marker written by every backup
|
||||||
├── blobs/
|
├── blobs/
|
||||||
│ └── <aa>/<bb>/<full_blob_hash>
|
│ └── <aa>/<bb>/<full_blob_hash>
|
||||||
└── metadata/
|
└── metadata/
|
||||||
@@ -475,6 +497,15 @@ For an implementation-level view of the internals — the data model, the
|
|||||||
└── manifest.json.zst # Unencrypted blob list (for pruning)
|
└── manifest.json.zst # Unencrypted blob list (for pruning)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
* `vaultik-destination.txt` holds one fixed line of text, with no host
|
||||||
|
name, path or time. While the local index holds snapshots, a
|
||||||
|
destination without it is treated as not present: `snapshot create`
|
||||||
|
refuses to write to it, `prune` and `snapshot purge` fail, and
|
||||||
|
`snapshot list` and `snapshot remove` warn, as for a destination that
|
||||||
|
cannot be listed. This keeps an unplugged volume's empty mount point
|
||||||
|
from being taken for a destination whose snapshots are all gone. Mount
|
||||||
|
the volume if it is removable; if the destination was emptied on
|
||||||
|
purpose, run `vaultik database delete` and back up again.
|
||||||
* Blobs are two-level directory sharded using the first 4 hex chars of the blob hash
|
* Blobs are two-level directory sharded using the first 4 hex chars of the blob hash
|
||||||
* `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted)
|
* `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted)
|
||||||
containing all file metadata, chunk mappings, and relationships for the snapshot
|
containing all file metadata, chunk mappings, and relationships for the snapshot
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ This document describes the structure and organization of data stored in the S3
|
|||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components:
|
Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components, plus a marker file:
|
||||||
1. **Blobs** - The actual backup data (content-addressed, encrypted)
|
1. **Blobs** - The actual backup data (content-addressed, encrypted)
|
||||||
2. **Metadata** - Snapshot information and manifests (partially encrypted)
|
2. **Metadata** - Snapshot information and manifests (partially encrypted)
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ Vaultik stores all backup data in an S3-compatible object store. The repository
|
|||||||
|
|
||||||
```
|
```
|
||||||
<bucket>/<prefix>/
|
<bucket>/<prefix>/
|
||||||
|
├── vaultik-destination.txt
|
||||||
├── blobs/
|
├── blobs/
|
||||||
│ └── <hash[0:2]>/
|
│ └── <hash[0:2]>/
|
||||||
│ └── <hash[2:4]>/
|
│ └── <hash[2:4]>/
|
||||||
@@ -24,6 +25,10 @@ Vaultik stores all backup data in an S3-compatible object store. The repository
|
|||||||
|
|
||||||
The metadata subdirectory is named with the **remote key**, a one-way hash of the snapshot ID, not with the human-readable snapshot ID itself. See [Remote Key Derivation](#remote-key-derivation).
|
The metadata subdirectory is named with the **remote key**, a one-way hash of the snapshot ID, not with the human-readable snapshot ID itself. See [Remote Key Derivation](#remote-key-derivation).
|
||||||
|
|
||||||
|
## Marker File (`vaultik-destination.txt`)
|
||||||
|
|
||||||
|
Every backup writes this file at the root before it uploads anything. It holds one fixed line of plain text and names no host, path or time. While the local index holds snapshots, a destination without it is treated as not present: `snapshot create` refuses to write to it, and `prune`, `snapshot purge`, `snapshot remove` and `snapshot list` behave as for a destination that cannot be listed. An unplugged volume leaves an empty directory at its mount point, and without the marker that directory would read as a destination whose snapshots are all gone. `remote nuke` deletes the marker last.
|
||||||
|
|
||||||
## Blobs Directory (`blobs/`)
|
## Blobs Directory (`blobs/`)
|
||||||
|
|
||||||
### Structure
|
### Structure
|
||||||
|
|||||||
@@ -101,7 +101,8 @@ func TestEntryPruneJSONStdoutIsExactlyOneDocument(t *testing.T) {
|
|||||||
// writeHermeticPruneConfig builds a config over a temp directory with an
|
// writeHermeticPruneConfig builds a config over a temp directory with an
|
||||||
// empty destination directory and, if seedStale is set, creates the
|
// empty destination directory and, if seedStale is set, creates the
|
||||||
// index database up front with one snapshot record that has no
|
// index database up front with one snapshot record that has no
|
||||||
// counterpart on the destination store. Returns the config path.
|
// counterpart on the destination store, and gives the destination the
|
||||||
|
// marker a backup writes. Returns the config path.
|
||||||
func writeHermeticPruneConfig(t *testing.T, seedStale bool) string {
|
func writeHermeticPruneConfig(t *testing.T, seedStale bool) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
@@ -131,6 +132,11 @@ func writeHermeticPruneConfig(t *testing.T, seedStale bool) string {
|
|||||||
|
|
||||||
if seedStale {
|
if seedStale {
|
||||||
seedStaleSnapshotRecord(t, indexPath)
|
seedStaleSnapshotRecord(t, indexPath)
|
||||||
|
|
||||||
|
// While the local index holds a snapshot, prune fails on a
|
||||||
|
// destination without the marker a backup writes.
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(storeDir, "vaultik-destination.txt"), nil, 0o600))
|
||||||
}
|
}
|
||||||
|
|
||||||
return configPath
|
return configPath
|
||||||
|
|||||||
@@ -277,50 +277,6 @@ func (r *FileRepository) ListUnderPath(
|
|||||||
return files, rows.Err()
|
return files, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListUnderPathInSnapshot returns the files that ListUnderPath returns
|
|
||||||
// for path and that the snapshot lists, in no particular order.
|
|
||||||
func (r *FileRepository) ListUnderPathInSnapshot(
|
|
||||||
ctx context.Context, path, snapshotID string,
|
|
||||||
) ([]*File, error) {
|
|
||||||
path = strings.TrimRight(path, "/")
|
|
||||||
dirPrefix := path + "/"
|
|
||||||
|
|
||||||
query := `
|
|
||||||
SELECT f.id, f.path, f.source_path, f.mtime, f.mtime_nsec, f.size,
|
|
||||||
f.mode, f.uid, f.gid, f.link_target
|
|
||||||
FROM files f
|
|
||||||
JOIN snapshot_files sf ON sf.file_id = f.id
|
|
||||||
WHERE sf.snapshot_id = ?
|
|
||||||
AND (f.path = ? OR substr(f.path, 1, length(?)) = ?)
|
|
||||||
`
|
|
||||||
|
|
||||||
rows, err := r.db.conn.QueryContext(ctx, query,
|
|
||||||
snapshotID, path, dirPrefix, dirPrefix)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("querying files: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var files []*File
|
|
||||||
|
|
||||||
for rows.Next() {
|
|
||||||
file, err := r.scanFileRows(rows)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("scanning file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
files = append(files, file)
|
|
||||||
}
|
|
||||||
|
|
||||||
return files, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListIDsWithChunksNotInUploadedBlobs returns the IDs of the files whose
|
// ListIDsWithChunksNotInUploadedBlobs returns the IDs of the files whose
|
||||||
// path starts with prefix and that list at least one chunk held by no
|
// path starts with prefix and that list at least one chunk held by no
|
||||||
// blob whose upload has completed (uploaded_ts set). A new snapshot
|
// blob whose upload has completed (uploaded_ts set). A new snapshot
|
||||||
|
|||||||
@@ -212,65 +212,6 @@ func TestFileRepositoryListUnderPath(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListUnderPathInSnapshot leaves out files outside path and files the
|
|
||||||
// snapshot does not list, though another snapshot lists them.
|
|
||||||
func TestFileRepositoryListUnderPathInSnapshot(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
db, cleanup := setupTestDB(t)
|
|
||||||
defer cleanup()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
files := database.NewFileRepository(db)
|
|
||||||
snapshots := database.NewSnapshotRepository(db)
|
|
||||||
|
|
||||||
listed := map[string][]string{
|
|
||||||
"one": {"/src/a.txt", "/src2/c.txt"},
|
|
||||||
"two": {"/src/b.txt"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for snapshotID, paths := range listed {
|
|
||||||
err := snapshots.Create(ctx, nil, &database.Snapshot{
|
|
||||||
ID: types.SnapshotID(snapshotID),
|
|
||||||
Hostname: "host",
|
|
||||||
StartedAt: time.Now(),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to create snapshot %s: %v", snapshotID, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, path := range paths {
|
|
||||||
err := files.Create(ctx, nil, &database.File{
|
|
||||||
Path: types.FilePath(path),
|
|
||||||
MTime: time.Now().Truncate(time.Second),
|
|
||||||
Mode: 0644,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to create %s: %v", path, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = snapshots.AddFile(ctx, nil, snapshotID, path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to add %s to %s: %v", path, snapshotID, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
found, err := files.ListUnderPathInSnapshot(ctx, "/src", "one")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("failed to list files: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
got := make([]string, 0, len(found))
|
|
||||||
for _, f := range found {
|
|
||||||
got = append(got, f.Path.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
if !slices.Equal(got, []string{"/src/a.txt"}) {
|
|
||||||
t.Errorf("got %q, want only /src/a.txt", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFileRepositorySymlink(t *testing.T) {
|
func TestFileRepositorySymlink(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
+11
-15
@@ -16,9 +16,6 @@ type ScannerParams struct {
|
|||||||
Fs afero.Fs
|
Fs afero.Fs
|
||||||
Exclude []string // Exclude patterns (combined global + snapshot-specific)
|
Exclude []string // Exclude patterns (combined global + snapshot-specific)
|
||||||
SkipErrors bool // Skip file read errors (log loudly but continue)
|
SkipErrors bool // Skip file read errors (log loudly but continue)
|
||||||
// PreviousSnapshotID is the most recent completed snapshot of the
|
|
||||||
// same name, "" for none.
|
|
||||||
PreviousSnapshotID string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Module exports backup functionality as an fx module.
|
// Module exports backup functionality as an fx module.
|
||||||
@@ -47,18 +44,17 @@ func provideScannerFactory(
|
|||||||
}
|
}
|
||||||
|
|
||||||
return NewScanner(ScannerConfig{
|
return NewScanner(ScannerConfig{
|
||||||
FS: params.Fs,
|
FS: params.Fs,
|
||||||
ChunkSize: cfg.ChunkSize.Int64(),
|
ChunkSize: cfg.ChunkSize.Int64(),
|
||||||
Repositories: repos,
|
Repositories: repos,
|
||||||
Storage: storer,
|
Storage: storer,
|
||||||
MaxBlobSize: cfg.BlobSizeLimit.Int64(),
|
MaxBlobSize: cfg.BlobSizeLimit.Int64(),
|
||||||
CompressionLevel: cfg.CompressionLevel,
|
CompressionLevel: cfg.CompressionLevel,
|
||||||
AgeRecipients: cfg.AgeRecipients,
|
AgeRecipients: cfg.AgeRecipients,
|
||||||
EnableProgress: params.EnableProgress,
|
EnableProgress: params.EnableProgress,
|
||||||
UI: params.UI,
|
UI: params.UI,
|
||||||
Exclude: excludes,
|
Exclude: excludes,
|
||||||
SkipErrors: params.SkipErrors,
|
SkipErrors: params.SkipErrors,
|
||||||
PreviousSnapshotID: params.PreviousSnapshotID,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,10 +58,6 @@ type Scanner struct {
|
|||||||
compressionLevel int
|
compressionLevel int
|
||||||
ageRecipient string
|
ageRecipient string
|
||||||
snapshotID string // Current snapshot being processed
|
snapshotID string // Current snapshot being processed
|
||||||
// previousSnapshotID is the most recent completed snapshot of the
|
|
||||||
// same name, "" for none. Only a file it lists can be counted as
|
|
||||||
// deleted.
|
|
||||||
previousSnapshotID string
|
|
||||||
// currentSourcePath is the source directory being scanned, stored with
|
// currentSourcePath is the source directory being scanned, stored with
|
||||||
// each file record.
|
// each file record.
|
||||||
currentSourcePath string
|
currentSourcePath string
|
||||||
@@ -133,9 +129,6 @@ type ScannerConfig struct {
|
|||||||
// SkipErrors skips files that cannot be opened or read (log loudly but
|
// SkipErrors skips files that cannot be opened or read (log loudly but
|
||||||
// continue); packer, database, encryption, and upload errors still abort.
|
// continue); packer, database, encryption, and upload errors still abort.
|
||||||
SkipErrors bool
|
SkipErrors bool
|
||||||
// PreviousSnapshotID is the most recent completed snapshot of the
|
|
||||||
// same name, "" for none.
|
|
||||||
PreviousSnapshotID string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ScanResult contains the results of a scan operation. Files and bytes
|
// ScanResult contains the results of a scan operation. Files and bytes
|
||||||
@@ -214,7 +207,6 @@ func NewScanner(cfg ScannerConfig) *Scanner {
|
|||||||
compiledExclude: compiledExclude,
|
compiledExclude: compiledExclude,
|
||||||
progress: progress,
|
progress: progress,
|
||||||
skipErrors: cfg.SkipErrors,
|
skipErrors: cfg.SkipErrors,
|
||||||
previousSnapshotID: cfg.PreviousSnapshotID,
|
|
||||||
ui: uiw,
|
ui: uiw,
|
||||||
pendingChunkHashes: make(map[string]struct{}),
|
pendingChunkHashes: make(map[string]struct{}),
|
||||||
}
|
}
|
||||||
@@ -266,9 +258,8 @@ func (s *Scanner) Scan(
|
|||||||
|
|
||||||
filesToProcess := scanResult.FilesToProcess
|
filesToProcess := scanResult.FilesToProcess
|
||||||
|
|
||||||
// Phase 1b: Detect deleted files by comparing the previous snapshot
|
// Phase 1b: Detect deleted files by comparing DB against scanned files
|
||||||
// of this name against scanned files
|
err = s.detectDeletedFilesFromMap(ctx, knownFiles, existingFiles, result)
|
||||||
err = s.detectDeletedFiles(ctx, path, existingFiles, result)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("detecting deleted files: %w", err)
|
return nil, fmt.Errorf("detecting deleted files: %w", err)
|
||||||
}
|
}
|
||||||
@@ -448,8 +439,9 @@ func (s *Scanner) summarizeScanPhase(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// loadKnownFiles loads the known files at and beneath path from the
|
// loadKnownFiles loads the known files at and beneath path from the
|
||||||
// database into a map for fast lookup. This avoids per-file database
|
// database into a map for fast lookup. Every loaded file the scan does
|
||||||
// queries during the scan phase.
|
// not find is counted as deleted. This avoids per-file database queries
|
||||||
|
// during the scan phase.
|
||||||
func (s *Scanner) loadKnownFiles(
|
func (s *Scanner) loadKnownFiles(
|
||||||
ctx context.Context, path string,
|
ctx context.Context, path string,
|
||||||
) (map[string]*database.File, error) {
|
) (map[string]*database.File, error) {
|
||||||
@@ -1950,28 +1942,21 @@ func (s *Scanner) queueFileForBatchInsert(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// detectDeletedFiles counts as deleted each file at or beneath path that
|
// detectDeletedFilesFromMap finds files that existed in previous snapshots
|
||||||
// the previous snapshot of this name lists and the walk did not find.
|
// but no longer exist. Uses pre-loaded maps to avoid any filesystem or
|
||||||
// A file that is excluded, or inside an excluded directory, is not
|
// database access.
|
||||||
// counted: the walk skips it whether or not it is still on disk.
|
func (s *Scanner) detectDeletedFilesFromMap(
|
||||||
func (s *Scanner) detectDeletedFiles(
|
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
path string,
|
knownFiles map[string]*database.File,
|
||||||
existingFiles map[string]struct{},
|
existingFiles map[string]struct{},
|
||||||
result *ScanResult,
|
result *ScanResult,
|
||||||
) error {
|
) error {
|
||||||
if s.previousSnapshotID == "" {
|
if len(knownFiles) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
previousFiles, err := s.repos.Files.ListUnderPathInSnapshot(
|
// Check each known file against the enumerated set (no filesystem access needed)
|
||||||
ctx, path, s.previousSnapshotID)
|
for path, file := range knownFiles {
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("listing files of snapshot %s: %w",
|
|
||||||
s.previousSnapshotID, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, file := range previousFiles {
|
|
||||||
// Check context cancellation periodically
|
// Check context cancellation periodically
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
@@ -1979,16 +1964,13 @@ func (s *Scanner) detectDeletedFiles(
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
|
||||||
filePath := file.Path.String()
|
// Check if the file exists in our enumerated set
|
||||||
|
if _, exists := existingFiles[path]; !exists {
|
||||||
_, exists := existingFiles[filePath]
|
// File has been deleted
|
||||||
if exists || s.excludedOrInExcludedDir(filePath, path) {
|
result.FilesDeleted++
|
||||||
continue
|
result.BytesDeleted += file.Size
|
||||||
|
log.Debug("Detected deleted file", "path", path, "size", file.Size)
|
||||||
}
|
}
|
||||||
|
|
||||||
result.FilesDeleted++
|
|
||||||
result.BytesDeleted += file.Size
|
|
||||||
log.Debug("Detected deleted file", "path", filePath, "size", file.Size)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if result.FilesDeleted > 0 {
|
if result.FilesDeleted > 0 {
|
||||||
@@ -1999,20 +1981,6 @@ func (s *Scanner) detectDeletedFiles(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// excludedOrInExcludedDir reports whether filePath, which is at or
|
|
||||||
// beneath rootPath, or any directory between rootPath and it, matches an
|
|
||||||
// exclude pattern. A pattern such as */.local/share/Trash matches the
|
|
||||||
// directory but not the files inside it, which the walk skips too.
|
|
||||||
func (s *Scanner) excludedOrInExcludedDir(filePath, rootPath string) bool {
|
|
||||||
for p := filePath; len(p) > len(rootPath); p = filepath.Dir(p) {
|
|
||||||
if s.shouldExclude(p, rootPath) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// wrapPermissionError augments permission errors with platform-specific
|
// wrapPermissionError augments permission errors with platform-specific
|
||||||
// remediation instructions. On macOS, TCC-protected directories (Calendars,
|
// remediation instructions. On macOS, TCC-protected directories (Calendars,
|
||||||
// Reminders, Photos, etc.) return EPERM unless the running application has
|
// Reminders, Photos, etc.) return EPERM unless the running application has
|
||||||
|
|||||||
@@ -21,9 +21,13 @@ type FileStorer struct {
|
|||||||
// NewFileStorer creates a new filesystem storage backend.
|
// NewFileStorer creates a new filesystem storage backend.
|
||||||
//
|
//
|
||||||
// Construction is intentionally cheap and does not touch the filesystem.
|
// Construction is intentionally cheap and does not touch the filesystem.
|
||||||
// The basePath is recorded; the directory is created lazily on first
|
// The backend never creates basePath: the user does, so that when
|
||||||
// write. Write operations (Put/PutWithProgress) call MkdirAll for the
|
// basePath is a directory on an unplugged volume, a write fails instead
|
||||||
// per-blob parent directory, which also covers basePath on first use.
|
// of landing on the disk under the mount point. This does not hold when
|
||||||
|
// basePath is the mount point itself, which stays behind when its volume
|
||||||
|
// is unplugged.
|
||||||
|
// Put and PutWithProgress fail on a missing basePath and create the
|
||||||
|
// directories below it as needed.
|
||||||
// Get and Stat report a key under a missing basePath as ErrNotFound.
|
// Get and Stat report a key under a missing basePath as ErrNotFound.
|
||||||
// List and ListStream fail on a missing basePath, because listing it as
|
// List and ListStream fail on a missing basePath, because listing it as
|
||||||
// an empty store would make `prune` drop every local snapshot record.
|
// an empty store would make `prune` drop every local snapshot record.
|
||||||
@@ -297,7 +301,19 @@ func (f *FileStorer) writeAtomic(
|
|||||||
path := f.fullPath(key)
|
path := f.fullPath(key)
|
||||||
dir := filepath.Dir(path)
|
dir := filepath.Dir(path)
|
||||||
|
|
||||||
err := f.fs.MkdirAll(dir, storageDirPerm)
|
// Checked on every write, so a destination that disappears part-way
|
||||||
|
// through a backup fails it rather than being recreated by MkdirAll.
|
||||||
|
_, err := f.fs.Stat(f.basePath)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return fmt.Errorf("destination directory does not exist; "+
|
||||||
|
"create it, or mount the volume it is on: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("checking destination directory: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = f.fs.MkdirAll(dir, storageDirPerm)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("creating directories: %w", err)
|
return fmt.Errorf("creating directories: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"sneak.berlin/go/vaultik/internal/storage"
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
@@ -60,3 +62,43 @@ func TestFileStorerListMissingDestination(t *testing.T) {
|
|||||||
t.Errorf("ListStream error = %v, want a not-exist error", streamErr)
|
t.Errorf("ListStream error = %v, want a not-exist error", streamErr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestFileStorerPutMissingDestination checks that a write fails when the
|
||||||
|
// destination directory has gone, even after earlier writes to it
|
||||||
|
// succeeded, and that it does not create the directory again.
|
||||||
|
func TestFileStorerPutMissingDestination(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
base := filepath.Join(t.TempDir(), "usbstick")
|
||||||
|
|
||||||
|
err := os.Mkdir(base, 0o750)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Mkdir: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
s, err := storage.NewFileStorer(base)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewFileStorer: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = s.Put(ctx, "blobs/aa/bb/first", strings.NewReader("first"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first Put: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = os.Rename(base, base+"-unplugged")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Rename: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = s.Put(ctx, "blobs/aa/bb/second", strings.NewReader("second"))
|
||||||
|
if !errors.Is(err, fs.ErrNotExist) {
|
||||||
|
t.Errorf("Put = %v, want a not-exist error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = os.Stat(base)
|
||||||
|
if !errors.Is(err, fs.ErrNotExist) {
|
||||||
|
t.Errorf("Put created the destination directory again (Stat = %v)", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -41,7 +41,8 @@ type Info struct {
|
|||||||
// directory for filesystem).
|
// directory for filesystem).
|
||||||
type Storer interface {
|
type Storer interface {
|
||||||
// Put stores data at the specified key.
|
// Put stores data at the specified key.
|
||||||
// Parent directories are created automatically for filesystem backends.
|
// The filesystem backend fails when its destination directory does
|
||||||
|
// not exist, and creates the directories below it as needed.
|
||||||
Put(ctx context.Context, key string, data io.Reader) error
|
Put(ctx context.Context, key string, data io.Reader) error
|
||||||
|
|
||||||
// PutWithProgress stores data with progress reporting.
|
// PutWithProgress stores data with progress reporting.
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ func TestBackupAfterRemovingNewestSnapshotRestoresChangedFile(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
changedPath := filepath.Join(dataDir, "appended.bin")
|
changedPath := filepath.Join(dataDir, "appended.bin")
|
||||||
@@ -184,7 +184,7 @@ func TestBackupAfterInterruptedRunRestoresChangedFile(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
changedPath := filepath.Join(dataDir, "appended.bin")
|
changedPath := filepath.Join(dataDir, "appended.bin")
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestDeepVerifyAcceptsHealthyAndRejectsCorruptBlob(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(64 * 1024)
|
chunkSize := int64(64 * 1024)
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package vaultik
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// destinationMarkerKey is the object every backup writes at the root of
|
||||||
|
// the backup destination store. While the local index holds a snapshot,
|
||||||
|
// a destination without it is treated as not present: an unplugged
|
||||||
|
// volume leaves an empty directory at its mount point, which would
|
||||||
|
// otherwise read as a store whose snapshots are all gone.
|
||||||
|
const destinationMarkerKey = "vaultik-destination.txt"
|
||||||
|
|
||||||
|
// destinationMarkerText is the whole content of the marker. It names no
|
||||||
|
// host, path or time.
|
||||||
|
const destinationMarkerText = "This is a vaultik backup destination store.\n"
|
||||||
|
|
||||||
|
// errDestinationNotPresent is returned when the local index holds a
|
||||||
|
// snapshot and the backup destination store has no marker.
|
||||||
|
var errDestinationNotPresent = errors.New("backup destination store is not present")
|
||||||
|
|
||||||
|
// checkDestinationMarker returns errDestinationNotPresent when the local
|
||||||
|
// index holds a snapshot and the backup destination store has no marker.
|
||||||
|
// With no snapshot in the local index, as on a first backup or on
|
||||||
|
// another machine, there is nothing to check.
|
||||||
|
func (v *Vaultik) checkDestinationMarker() error {
|
||||||
|
ids, err := v.localSnapshotIDs()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listing local snapshots: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = v.Storage.Stat(v.ctx, destinationMarkerKey)
|
||||||
|
if errors.Is(err, storage.ErrNotFound) {
|
||||||
|
return fmt.Errorf("%w: %s has no %s, but the local index holds "+
|
||||||
|
"snapshots stored there; mount the volume if it is removable, "+
|
||||||
|
"or if the destination was emptied on purpose, run "+
|
||||||
|
"'vaultik database delete' and back up again",
|
||||||
|
errDestinationNotPresent, v.Storage.Info().Location,
|
||||||
|
destinationMarkerKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("checking for %s: %w", destinationMarkerKey, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// markDestination checks the backup destination store with
|
||||||
|
// checkDestinationMarker and then writes the marker, so a first backup
|
||||||
|
// marks its destination and a later one writes the same text again.
|
||||||
|
func (v *Vaultik) markDestination() error {
|
||||||
|
err := v.checkDestinationMarker()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = v.Storage.Put(v.ctx, destinationMarkerKey,
|
||||||
|
strings.NewReader(destinationMarkerText))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("writing %s to the backup destination store: %w",
|
||||||
|
destinationMarkerKey, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
package vaultik_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
|
)
|
||||||
|
|
||||||
|
// These tests cover https://git.eeqj.de/sneak/vaultik/issues/239: a
|
||||||
|
// file:// destination at a volume's mount point leaves an empty directory
|
||||||
|
// behind when the volume is unplugged. While the local index holds
|
||||||
|
// snapshots, a destination without vaultik-destination.txt is not present,
|
||||||
|
// so no command may write to it or conclude from it that the local
|
||||||
|
// snapshots are gone.
|
||||||
|
|
||||||
|
// markerFile is the name of the file a backup writes at the root of the
|
||||||
|
// destination.
|
||||||
|
const markerFile = "vaultik-destination.txt"
|
||||||
|
|
||||||
|
// backUpThenUnplugMountPoint backs up to a file:// destination, then
|
||||||
|
// moves the destination directory away and leaves an empty directory in
|
||||||
|
// its place, as unplugging a volume mounted there would. It returns the
|
||||||
|
// path of that empty directory.
|
||||||
|
func backUpThenUnplugMountPoint(
|
||||||
|
ctx context.Context, t *testing.T,
|
||||||
|
) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer, string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
storeDir := filepath.Join(t.TempDir(), "mnt")
|
||||||
|
v, repos, out := backUpToFileDestination(ctx, t, storeDir)
|
||||||
|
|
||||||
|
require.NoError(t, os.Rename(storeDir, storeDir+"-unplugged"))
|
||||||
|
require.NoError(t, os.Mkdir(storeDir, 0o750))
|
||||||
|
|
||||||
|
return v, repos, out, storeDir
|
||||||
|
}
|
||||||
|
|
||||||
|
// assertUntouched checks that the local index still holds its one
|
||||||
|
// snapshot and that nothing was written to the empty mount point.
|
||||||
|
func assertUntouched(
|
||||||
|
ctx context.Context, t *testing.T,
|
||||||
|
repos *database.Repositories, storeDir string,
|
||||||
|
) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Len(t, snapshots, 1, "no local snapshot record may be deleted")
|
||||||
|
|
||||||
|
entries, err := os.ReadDir(storeDir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, entries, "nothing may be written to the empty mount point")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFirstBackupWritesMarker checks that a backup writes the marker
|
||||||
|
// file at the root of the destination.
|
||||||
|
func TestFirstBackupWritesMarker(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
storeDir := t.TempDir()
|
||||||
|
backUpToFileDestination(context.Background(), t, storeDir)
|
||||||
|
|
||||||
|
assert.FileExists(t, filepath.Join(storeDir, markerFile))
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBackupRefusesDestinationWithoutMarker checks that snapshot create
|
||||||
|
// --prune writes nothing and drops no local snapshot record when the
|
||||||
|
// destination has no marker.
|
||||||
|
func TestBackupRefusesDestinationWithoutMarker(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t)
|
||||||
|
|
||||||
|
err := v.CreateSnapshot(&vaultik.SnapshotCreateOptions{
|
||||||
|
Cron: true,
|
||||||
|
Prune: true,
|
||||||
|
})
|
||||||
|
require.ErrorContains(t, err, markerFile)
|
||||||
|
|
||||||
|
assertUntouched(ctx, t, repos, storeDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPruneRefusesDestinationWithoutMarker checks that prune fails and
|
||||||
|
// deletes no local snapshot record when the destination has no marker.
|
||||||
|
func TestPruneRefusesDestinationWithoutMarker(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t)
|
||||||
|
|
||||||
|
err := v.Prune(&vaultik.PruneOptions{Force: true})
|
||||||
|
require.ErrorContains(t, err, markerFile)
|
||||||
|
|
||||||
|
assertUntouched(ctx, t, repos, storeDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPurgeRefusesDestinationWithoutMarker checks that snapshot purge
|
||||||
|
// fails and deletes no local snapshot record when the destination has no
|
||||||
|
// marker.
|
||||||
|
func TestPurgeRefusesDestinationWithoutMarker(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t)
|
||||||
|
|
||||||
|
err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{
|
||||||
|
KeepLatest: true,
|
||||||
|
Force: true,
|
||||||
|
})
|
||||||
|
require.ErrorContains(t, err, markerFile)
|
||||||
|
|
||||||
|
assertUntouched(ctx, t, repos, storeDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRemoveSnapshotWarnsWhenDestinationHasNoMarker checks that snapshot
|
||||||
|
// remove warns that the metadata could not be removed from a destination
|
||||||
|
// without a marker, instead of reporting that it was.
|
||||||
|
func TestRemoveSnapshotWarnsWhenDestinationHasNoMarker(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
v, repos, out, _ := backUpThenUnplugMountPoint(ctx, t)
|
||||||
|
|
||||||
|
result, err := v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "first"),
|
||||||
|
&vaultik.RemoveOptions{Force: true})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
assert.False(t, result.RemoteRemoved)
|
||||||
|
assert.Contains(t, out.String(),
|
||||||
|
"Could not remove snapshot metadata from remote")
|
||||||
|
assert.Contains(t, out.String(), markerFile)
|
||||||
|
assert.NotContains(t, out.String(),
|
||||||
|
"Removed snapshot metadata from remote storage")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestListSnapshotsWarnsWhenDestinationHasNoMarker checks that snapshot
|
||||||
|
// list warns and shows the local index alone when the destination has no
|
||||||
|
// marker, without reporting the local snapshot as missing from it.
|
||||||
|
func TestListSnapshotsWarnsWhenDestinationHasNoMarker(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
v, repos, out, _ := backUpThenUnplugMountPoint(ctx, t)
|
||||||
|
id := localSnapshotID(ctx, t, repos, "first")
|
||||||
|
|
||||||
|
require.NoError(t, v.ListSnapshots(false))
|
||||||
|
|
||||||
|
assert.Contains(t, out.String(), "Could not list backup destination store")
|
||||||
|
assert.Contains(t, out.String(), markerFile)
|
||||||
|
assert.Contains(t, out.String(), id)
|
||||||
|
assert.NotContains(t, out.String(), "not found in backup destination store")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBackupAfterNukeRemoteSucceeds checks that remote nuke leaves the
|
||||||
|
// destination ready for a new first backup, which writes the marker
|
||||||
|
// again.
|
||||||
|
func TestBackupAfterNukeRemoteSucceeds(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
storeDir := t.TempDir()
|
||||||
|
v, _, _ := backUpToFileDestination(context.Background(), t, storeDir)
|
||||||
|
|
||||||
|
require.NoError(t, v.NukeRemote(true))
|
||||||
|
assert.NoFileExists(t, filepath.Join(storeDir, markerFile))
|
||||||
|
|
||||||
|
require.NoError(t, backUp(v, "second"))
|
||||||
|
assert.FileExists(t, filepath.Join(storeDir, markerFile))
|
||||||
|
}
|
||||||
@@ -192,7 +192,7 @@ func assertRestoreRejectsDamagedBlob(
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -238,7 +238,7 @@ func TestDeepVerifyCatchesLyingBackend(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -290,7 +290,7 @@ func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -298,10 +298,6 @@ func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) {
|
|||||||
|
|
||||||
writeFaultSourceTree(t, fs, dataDir)
|
writeFaultSourceTree(t, fs, dataDir)
|
||||||
|
|
||||||
// No upload succeeds, so nothing creates the destination directory.
|
|
||||||
// It must exist for the listing below to show that no blob survived.
|
|
||||||
require.NoError(t, os.Mkdir(storeDir, 0o750))
|
|
||||||
|
|
||||||
inner, err := storage.NewFileStorer(storeDir)
|
inner, err := storage.NewFileStorer(storeDir)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
@@ -365,7 +361,7 @@ func TestBackupRetryAfterInterruptedUploadIsRestorable(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -429,7 +425,7 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -511,7 +507,7 @@ func TestBackupCompletesOnlyAfterMetadataExport(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -661,18 +657,17 @@ func faultScannerFactory(
|
|||||||
) snapshot.ScannerFactory {
|
) snapshot.ScannerFactory {
|
||||||
return func(params snapshot.ScannerParams) *snapshot.Scanner {
|
return func(params snapshot.ScannerParams) *snapshot.Scanner {
|
||||||
return snapshot.NewScanner(snapshot.ScannerConfig{
|
return snapshot.NewScanner(snapshot.ScannerConfig{
|
||||||
FS: params.Fs,
|
FS: params.Fs,
|
||||||
Storage: storer,
|
Storage: storer,
|
||||||
ChunkSize: faultChunkSize,
|
ChunkSize: faultChunkSize,
|
||||||
MaxBlobSize: faultMaxBlobSize,
|
MaxBlobSize: faultMaxBlobSize,
|
||||||
CompressionLevel: cfg.CompressionLevel,
|
CompressionLevel: cfg.CompressionLevel,
|
||||||
AgeRecipients: cfg.AgeRecipients,
|
AgeRecipients: cfg.AgeRecipients,
|
||||||
Repositories: repos,
|
Repositories: repos,
|
||||||
EnableProgress: params.EnableProgress,
|
EnableProgress: params.EnableProgress,
|
||||||
UI: params.UI,
|
UI: params.UI,
|
||||||
Exclude: params.Exclude,
|
Exclude: params.Exclude,
|
||||||
SkipErrors: params.SkipErrors,
|
SkipErrors: params.SkipErrors,
|
||||||
PreviousSnapshotID: params.PreviousSnapshotID,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -687,7 +682,7 @@ func TestRestoreReportsDiskFull(t *testing.T) {
|
|||||||
osFS := afero.NewOsFs()
|
osFS := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -771,7 +771,7 @@ func TestEndToEndFileStorage(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -964,7 +964,7 @@ func TestDedupOnlySnapshotRestores(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -24,13 +24,11 @@ import (
|
|||||||
// that is not plugged in, cannot be listed. It is not an empty store, so
|
// that is not plugged in, cannot be listed. It is not an empty store, so
|
||||||
// no command may conclude from it that the local snapshots are gone.
|
// no command may conclude from it that the local snapshots are gone.
|
||||||
|
|
||||||
// backUpToFileDestination backs up the snapshot named "first" to a
|
// newFileDestinationVaultik returns a Vaultik that backs up the
|
||||||
// file:// destination at storeDir, which need not exist yet. Everything
|
// snapshot named "first" to a file:// destination at storeDir.
|
||||||
// the returned Vaultik prints after the backup goes to the returned
|
func newFileDestinationVaultik(
|
||||||
// buffer.
|
|
||||||
func backUpToFileDestination(
|
|
||||||
ctx context.Context, t *testing.T, storeDir string,
|
ctx context.Context, t *testing.T, storeDir string,
|
||||||
) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) {
|
) (*vaultik.Vaultik, *database.Repositories) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
osFs := afero.NewOsFs()
|
osFs := afero.NewOsFs()
|
||||||
@@ -49,8 +47,22 @@ func backUpToFileDestination(
|
|||||||
|
|
||||||
repos := database.NewRepositories(db)
|
repos := database.NewRepositories(db)
|
||||||
cfg := changedFileConfig(dataDir, dbPath)
|
cfg := changedFileConfig(dataDir, dbPath)
|
||||||
v := newBackupVaultik(ctx, cfg, store, repos, db, osFs)
|
|
||||||
|
|
||||||
|
return newBackupVaultik(ctx, cfg, store, repos, db, osFs), repos
|
||||||
|
}
|
||||||
|
|
||||||
|
// backUpToFileDestination creates the directory storeDir, as a user must
|
||||||
|
// before the first backup, and backs up the snapshot named "first" to a
|
||||||
|
// file:// destination there. Everything the returned Vaultik prints
|
||||||
|
// after the backup goes to the returned buffer.
|
||||||
|
func backUpToFileDestination(
|
||||||
|
ctx context.Context, t *testing.T, storeDir string,
|
||||||
|
) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
require.NoError(t, os.MkdirAll(storeDir, 0o750))
|
||||||
|
|
||||||
|
v, repos := newFileDestinationVaultik(ctx, t, storeDir)
|
||||||
require.NoError(t, backUp(v, "first"))
|
require.NoError(t, backUp(v, "first"))
|
||||||
|
|
||||||
out := &bytes.Buffer{}
|
out := &bytes.Buffer{}
|
||||||
@@ -75,21 +87,28 @@ func backUpThenUnplug(
|
|||||||
return v, repos, out
|
return v, repos, out
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestFirstBackupCreatesDestinationDirectory checks that a first backup
|
// TestBackupFailsWhenDestinationDirectoryMissing checks that a backup to
|
||||||
// to a destination directory that does not exist yet creates it, and
|
// a file:// destination whose directory does not exist fails before it
|
||||||
// that the destination can be listed afterwards.
|
// records a snapshot, and does not create the directory.
|
||||||
func TestFirstBackupCreatesDestinationDirectory(t *testing.T) {
|
func TestBackupFailsWhenDestinationDirectoryMissing(t *testing.T) {
|
||||||
log.Initialize(log.Config{})
|
log.Initialize(log.Config{})
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
storeDir := filepath.Join(t.TempDir(), "volume", "backup")
|
volume := filepath.Join(t.TempDir(), "volume")
|
||||||
v, _, out := backUpToFileDestination(ctx, t, storeDir)
|
v, repos := newFileDestinationVaultik(ctx, t, filepath.Join(volume, "backup"))
|
||||||
|
|
||||||
require.NoError(t, v.ListSnapshots(false))
|
err := backUp(v, "first")
|
||||||
|
require.ErrorIs(t, err, fs.ErrNotExist)
|
||||||
|
require.ErrorContains(t, err, "create it, or mount the volume it is on")
|
||||||
|
|
||||||
assert.NotContains(t, out.String(), "Could not list backup destination store")
|
_, err = os.Stat(volume)
|
||||||
assert.NotContains(t, out.String(), "not found in backup destination store")
|
require.ErrorIs(t, err, fs.ErrNotExist,
|
||||||
|
"the backup must not create the destination directory")
|
||||||
|
|
||||||
|
snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, snapshots)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestListSnapshotsWarnsWhenDestinationMissing checks that snapshot list
|
// TestListSnapshotsWarnsWhenDestinationMissing checks that snapshot list
|
||||||
|
|||||||
@@ -29,8 +29,9 @@ 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, and the destination marker. After this
|
||||||
// prefix is empty and the next backup starts from scratch.
|
// returns successfully the bucket prefix is empty and the next backup
|
||||||
|
// starts from scratch.
|
||||||
//
|
//
|
||||||
// Refuses to run unless force is true. The caller is responsible for
|
// Refuses to run unless force is true. The caller is responsible for
|
||||||
// confirming with the user.
|
// confirming with the user.
|
||||||
@@ -62,6 +63,13 @@ func (v *Vaultik) NukeRemote(force bool) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Last, once the local snapshot records are gone: the next backup
|
||||||
|
// then has none and writes the marker again.
|
||||||
|
err = v.Storage.Delete(v.ctx, destinationMarkerKey)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("deleting %s: %w", destinationMarkerKey, err)
|
||||||
|
}
|
||||||
|
|
||||||
v.UI.Completef("Backup destination store is now empty.")
|
v.UI.Completef("Backup destination store is now empty.")
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -34,6 +34,9 @@ func setupConsistencyTest(
|
|||||||
repos := database.NewRepositories(db)
|
repos := database.NewRepositories(db)
|
||||||
mockStorage := NewMockStorer()
|
mockStorage := NewMockStorer()
|
||||||
|
|
||||||
|
// A backup wrote to this destination, so it carries the marker.
|
||||||
|
require.NoError(t, mockStorage.Put(ctx, markerFile, strings.NewReader("")))
|
||||||
|
|
||||||
for _, id := range snapshotIDs {
|
for _, id := range snapshotIDs {
|
||||||
parts := strings.Split(id, "_")
|
parts := strings.Split(id, "_")
|
||||||
startedAt, err := time.Parse(time.RFC3339, parts[len(parts)-1])
|
startedAt, err := time.Parse(time.RFC3339, parts[len(parts)-1])
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ func setupPurgeTest(
|
|||||||
repos := database.NewRepositories(db)
|
repos := database.NewRepositories(db)
|
||||||
mockStorage := NewMockStorer()
|
mockStorage := NewMockStorer()
|
||||||
|
|
||||||
|
// A backup wrote to this destination, so it carries the marker.
|
||||||
|
require.NoError(t, mockStorage.Put(ctx, markerFile, strings.NewReader("")))
|
||||||
|
|
||||||
// Insert each snapshot into the DB and create remote metadata stubs.
|
// Insert each snapshot into the DB and create remote metadata stubs.
|
||||||
// Use timestamps parsed from snapshot IDs for realistic ordering.
|
// Use timestamps parsed from snapshot IDs for realistic ordering.
|
||||||
for _, id := range snapshotIDs {
|
for _, id := range snapshotIDs {
|
||||||
|
|||||||
@@ -303,6 +303,10 @@ func TestRemoveSnapshot_DefaultRemovesMetadataNotBlobs(t *testing.T) {
|
|||||||
addBlob(t, store, blobUnique)
|
addBlob(t, store, blobUnique)
|
||||||
addBlob(t, store, blobShared)
|
addBlob(t, store, blobShared)
|
||||||
|
|
||||||
|
// A backup wrote to this destination, so it carries the marker.
|
||||||
|
require.NoError(t, store.Put(context.Background(), markerFile,
|
||||||
|
bytes.NewReader(nil)))
|
||||||
|
|
||||||
tv := vaultik.NewForTesting(store)
|
tv := vaultik.NewForTesting(store)
|
||||||
tv.Repositories = newLocalIndex(t, "snapshot-001", "snapshot-002")
|
tv.Repositories = newLocalIndex(t, "snapshot-001", "snapshot-002")
|
||||||
|
|
||||||
@@ -392,7 +396,12 @@ func TestRemoveSnapshot_NoMetadataOnDestination(t *testing.T) {
|
|||||||
log.Initialize(log.Config{})
|
log.Initialize(log.Config{})
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
tv := vaultik.NewForTesting(newTestStorer())
|
// A backup wrote to this destination, so it carries the marker.
|
||||||
|
store := newTestStorer()
|
||||||
|
require.NoError(t, store.Put(context.Background(), markerFile,
|
||||||
|
bytes.NewReader(nil)))
|
||||||
|
|
||||||
|
tv := vaultik.NewForTesting(store)
|
||||||
tv.Repositories = newLocalIndex(t, "snapshot-001")
|
tv.Repositories = newLocalIndex(t, "snapshot-001")
|
||||||
|
|
||||||
result, err := tv.RemoveSnapshot("snapshot-001",
|
result, err := tv.RemoveSnapshot("snapshot-001",
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ func TestRestoreOnAnotherMachine(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) {
|
|||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(root, "source")
|
dataDir := filepath.Join(root, "source")
|
||||||
storeDir := filepath.Join(root, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(root, "restored")
|
restoreDir := filepath.Join(root, "restored")
|
||||||
dbPath := filepath.Join(root, "index.sqlite")
|
dbPath := filepath.Join(root, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -197,7 +197,7 @@ func TestRestoreLocalityAndReadAt(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ func backupOneFile(
|
|||||||
require.NoError(t, afero.WriteFile(fs, srcPath, content, mode))
|
require.NoError(t, afero.WriteFile(fs, srcPath, content, mode))
|
||||||
require.NoError(t, fs.Chmod(srcPath, mode))
|
require.NoError(t, fs.Chmod(srcPath, mode))
|
||||||
|
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
storer, err := storage.NewFileStorer(storeDir)
|
storer, err := storage.NewFileStorer(storeDir)
|
||||||
|
|||||||
@@ -219,7 +219,7 @@ func backupSingleChunkFiles(
|
|||||||
require.NoError(t, afero.WriteFile(fs, path, files[path], 0o644))
|
require.NoError(t, afero.WriteFile(fs, path, files[path], 0o644))
|
||||||
}
|
}
|
||||||
|
|
||||||
storer, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
storer, err := storage.NewFileStorer(t.TempDir())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
db, err := database.New(ctx, dbPath)
|
db, err := database.New(ctx, dbPath)
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ func TestRestoreAndDeepVerifyRejectSwappedDatabase(t *testing.T) {
|
|||||||
|
|
||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
|
|
||||||
chunkSize := int64(64 * 1024)
|
chunkSize := int64(64 * 1024)
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ func TestDeepVerifyRejectsSwappedDatabaseWithEmptyManifest(t *testing.T) {
|
|||||||
|
|
||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
|
|
||||||
chunkSize := int64(64 * 1024)
|
chunkSize := int64(64 * 1024)
|
||||||
|
|
||||||
|
|||||||
@@ -186,7 +186,7 @@ func TestRestoreSweeperEvictsBlobs(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ func TestRestoreRejectsTruncatedMetadataDB(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ func TestBackupOfSameSecondRewriteRestoresNewContent(t *testing.T) {
|
|||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
rewrittenPath := filepath.Join(dataDir, "small.txt")
|
rewrittenPath := filepath.Join(dataDir, "small.txt")
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(32 * 1024)
|
chunkSize := int64(32 * 1024)
|
||||||
@@ -105,7 +105,7 @@ func TestShallowVerifyDetectsMissingDatabase(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(32 * 1024)
|
chunkSize := int64(32 * 1024)
|
||||||
|
|||||||
@@ -92,6 +92,13 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Before PruneDatabase: it drops incomplete snapshots, which could
|
||||||
|
// leave the local index without one and so skip the marker check.
|
||||||
|
err = v.markDestination()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// Clean up incomplete snapshots FIRST, before any scanning.
|
// Clean up incomplete snapshots FIRST, before any scanning.
|
||||||
// This is critical for data safety; PruneDatabase below does it.
|
// This is critical for data safety; PruneDatabase below does it.
|
||||||
hostname := v.Config.Hostname
|
hostname := v.Config.Hostname
|
||||||
@@ -114,21 +121,9 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error {
|
|||||||
return fmt.Errorf("prune database: %w", err)
|
return fmt.Errorf("prune database: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine which snapshots to process
|
snapshotNames, err := v.snapshotNamesToCreate(opts.Snapshots)
|
||||||
snapshotNames := opts.Snapshots
|
if err != nil {
|
||||||
if len(snapshotNames) == 0 {
|
return err
|
||||||
snapshotNames = v.Config.SnapshotNames()
|
|
||||||
} else {
|
|
||||||
// Validate requested snapshot names exist
|
|
||||||
for _, name := range snapshotNames {
|
|
||||||
if _, ok := v.Config.Snapshots[name]; !ok {
|
|
||||||
return fmt.Errorf("%w: %q", errSnapshotNotInConfig, name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(snapshotNames) == 0 {
|
|
||||||
return errNoSnapshotsInConfig
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process each named snapshot
|
// Process each named snapshot
|
||||||
@@ -168,6 +163,28 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// snapshotNamesToCreate returns the requested snapshot names, each checked
|
||||||
|
// against the config, or every configured name when none was requested.
|
||||||
|
func (v *Vaultik) snapshotNamesToCreate(requested []string) ([]string, error) {
|
||||||
|
snapshotNames := requested
|
||||||
|
if len(snapshotNames) == 0 {
|
||||||
|
snapshotNames = v.Config.SnapshotNames()
|
||||||
|
} else {
|
||||||
|
// Validate requested snapshot names exist
|
||||||
|
for _, name := range snapshotNames {
|
||||||
|
if _, ok := v.Config.Snapshots[name]; !ok {
|
||||||
|
return nil, fmt.Errorf("%w: %q", errSnapshotNotInConfig, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(snapshotNames) == 0 {
|
||||||
|
return nil, errNoSnapshotsInConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
return snapshotNames, nil
|
||||||
|
}
|
||||||
|
|
||||||
// runPostBackupPrune drops older snapshots of the given names and removes
|
// runPostBackupPrune drops older snapshots of the given names and removes
|
||||||
// orphan blobs from remote storage. If keepNewerThan is set (e.g. "4w"),
|
// orphan blobs from remote storage. If keepNewerThan is set (e.g. "4w"),
|
||||||
// snapshots newer than that duration are kept. Otherwise only the latest
|
// snapshots newer than that duration are kept. Otherwise only the latest
|
||||||
@@ -241,18 +258,12 @@ func (v *Vaultik) createNamedSnapshot(
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
previousSnapshotID, err := v.previousSnapshotID(snapName)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
scanner := v.ScannerFactory(snapshot.ScannerParams{
|
scanner := v.ScannerFactory(snapshot.ScannerParams{
|
||||||
EnableProgress: !opts.Cron,
|
EnableProgress: !opts.Cron,
|
||||||
UI: v.UI,
|
UI: v.UI,
|
||||||
Fs: v.Fs,
|
Fs: v.Fs,
|
||||||
Exclude: v.Config.GetExcludes(snapName),
|
Exclude: v.Config.GetExcludes(snapName),
|
||||||
SkipErrors: opts.SkipErrors,
|
SkipErrors: opts.SkipErrors,
|
||||||
PreviousSnapshotID: previousSnapshotID,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
snapshotID, err := v.SnapshotManager.CreateSnapshotWithName(
|
snapshotID, err := v.SnapshotManager.CreateSnapshotWithName(
|
||||||
@@ -287,24 +298,6 @@ func (v *Vaultik) createNamedSnapshot(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// previousSnapshotID returns the ID of the most recent completed snapshot
|
|
||||||
// named snapName in the local index, or "" when there is none.
|
|
||||||
func (v *Vaultik) previousSnapshotID(snapName string) (string, error) {
|
|
||||||
snapshots, err := v.Repositories.Snapshots.ListRecent(v.ctx, listRecentLimit)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("listing snapshots: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, s := range snapshots {
|
|
||||||
if s.CompletedAt != nil &&
|
|
||||||
parseSnapshotName(s.ID.String(), s.Hostname.String()) == snapName {
|
|
||||||
return s.ID.String(), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// resolveSnapshotPaths resolves source directories to absolute paths
|
// resolveSnapshotPaths resolves source directories to absolute paths
|
||||||
// with symlink resolution.
|
// with symlink resolution.
|
||||||
func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) {
|
func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) {
|
||||||
@@ -1216,10 +1209,18 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
return v.removeSnapshotDryRun(result, snapshotID, opts)
|
return v.removeSnapshotDryRun(result, snapshotID, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !opts.Force && !opts.JSON && !v.confirmRemoveSnapshot(snapshotID, opts) {
|
if !v.confirmRemoveSnapshot(snapshotID, opts) {
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Checked before the local record is deleted: it may be the last
|
||||||
|
// snapshot in the local index, and the check applies only while the
|
||||||
|
// local index holds one.
|
||||||
|
var markerErr error
|
||||||
|
if !opts.LocalOnly {
|
||||||
|
markerErr = v.checkDestinationMarker()
|
||||||
|
}
|
||||||
|
|
||||||
if inLocalIndex {
|
if inLocalIndex {
|
||||||
log.Info("Removing snapshot from local database", "snapshot_id", snapshotID)
|
log.Info("Removing snapshot from local database", "snapshot_id", snapshotID)
|
||||||
|
|
||||||
@@ -1230,7 +1231,7 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
result.RemoteRemoved = v.removeSnapshotRemote(snapshotID, opts)
|
result.RemoteRemoved = v.removeSnapshotRemote(snapshotID, markerErr, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.SnapshotManager != nil {
|
if v.SnapshotManager != nil {
|
||||||
@@ -1322,9 +1323,13 @@ func (v *Vaultik) removeSnapshotDryRun(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// confirmRemoveSnapshot prompts for confirmation before removing a
|
// confirmRemoveSnapshot prompts for confirmation before removing a
|
||||||
// snapshot. Returns false (treating EOF/read errors as "no") unless the
|
// snapshot, unless --force or --json is set. Returns false (treating
|
||||||
// user answers "y".
|
// EOF/read errors as "no") unless the user answers "y".
|
||||||
func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) bool {
|
func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) bool {
|
||||||
|
if opts.Force || opts.JSON {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
if opts.LocalOnly {
|
if opts.LocalOnly {
|
||||||
v.stdoutf("Remove snapshot '%s' from local database "+
|
v.stdoutf("Remove snapshot '%s' from local database "+
|
||||||
"(remote untouched)? [y/N] ", snapshotID)
|
"(remote untouched)? [y/N] ", snapshotID)
|
||||||
@@ -1356,15 +1361,24 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions)
|
|||||||
// removal has already happened, so the user is told the remote half
|
// removal has already happened, so the user is told the remote half
|
||||||
// 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). markerErr is the result of
|
||||||
// succeeded and deleted something.
|
// checkDestinationMarker; when it is set, nothing is deleted and it is
|
||||||
func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) bool {
|
// the failure reported. Returns true when the remote removal succeeded
|
||||||
|
// and deleted something.
|
||||||
|
func (v *Vaultik) removeSnapshotRemote(
|
||||||
|
snapshotID string, markerErr error, 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)
|
var deleted int
|
||||||
|
|
||||||
|
err := markerErr
|
||||||
|
if err == nil {
|
||||||
|
deleted, err = v.deleteRemoteSnapshotByKey(
|
||||||
|
snapshot.RemoteSnapshotKey(snapshotID))
|
||||||
|
}
|
||||||
|
|
||||||
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 "+
|
||||||
@@ -1468,8 +1482,8 @@ func (v *Vaultik) localSnapshotIDs() ([]string, error) {
|
|||||||
// listAllRemoteSnapshotKeys collects the hashed remote keys
|
// listAllRemoteSnapshotKeys collects the hashed remote keys
|
||||||
// (subdirectories under metadata/) currently present in the
|
// (subdirectories under metadata/) currently present in the
|
||||||
// destination store. Returns (nil, err) when the store cannot be
|
// destination store. Returns (nil, err) when the store cannot be
|
||||||
// listed; callers must treat that as "no remote info available," not
|
// listed, or is not present by checkDestinationMarker; callers must
|
||||||
// fatal.
|
// treat that as "no remote info available," not fatal.
|
||||||
func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) {
|
func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) {
|
||||||
log.Info("Listing all remote snapshots")
|
log.Info("Listing all remote snapshots")
|
||||||
|
|
||||||
@@ -1518,6 +1532,11 @@ func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err := v.checkDestinationMarker()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return keys, nil
|
return keys, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,196 +0,0 @@
|
|||||||
package vaultik_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"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/304: a
|
|
||||||
// backup counts a file as deleted only when the previous snapshot of
|
|
||||||
// the same name had it and it is gone, and never counts an excluded
|
|
||||||
// file.
|
|
||||||
|
|
||||||
// deletedCountEnv is a backup setup over the source directory src whose
|
|
||||||
// user-facing output is kept in out. Each test configures its snapshots
|
|
||||||
// with setSnapshot.
|
|
||||||
type deletedCountEnv struct {
|
|
||||||
v *vaultik.Vaultik
|
|
||||||
out *bytes.Buffer
|
|
||||||
src string
|
|
||||||
}
|
|
||||||
|
|
||||||
// newDeletedCountEnv writes files, keyed by path relative to src.
|
|
||||||
func newDeletedCountEnv(t *testing.T, files map[string][]byte) *deletedCountEnv {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
fs := afero.NewOsFs()
|
|
||||||
tempDir := t.TempDir()
|
|
||||||
srcDir := filepath.Join(tempDir, "src")
|
|
||||||
|
|
||||||
for rel, content := range files {
|
|
||||||
path := filepath.Join(srcDir, rel)
|
|
||||||
require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755))
|
|
||||||
require.NoError(t, afero.WriteFile(fs, path, content, 0o644))
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := faultTestConfig()
|
|
||||||
cfg.IndexPath = filepath.Join(tempDir, "index.sqlite")
|
|
||||||
cfg.Snapshots = map[string]config.SnapshotConfig{}
|
|
||||||
|
|
||||||
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
db, err := database.New(ctx, cfg.IndexPath)
|
|
||||||
require.NoError(t, err)
|
|
||||||
t.Cleanup(func() { _ = db.Close() })
|
|
||||||
|
|
||||||
repos := database.NewRepositories(db)
|
|
||||||
out := &bytes.Buffer{}
|
|
||||||
v := newBackupVaultik(ctx, cfg, store, repos, db, fs)
|
|
||||||
v.UI = ui.NewWithColor(out, false)
|
|
||||||
|
|
||||||
return &deletedCountEnv{v: v, out: out, src: srcDir}
|
|
||||||
}
|
|
||||||
|
|
||||||
// setSnapshot configures the snapshot name to back up the path rel
|
|
||||||
// beneath src, with the given excludes.
|
|
||||||
func (e *deletedCountEnv) setSnapshot(name, rel string, exclude ...string) {
|
|
||||||
e.v.Config.Snapshots[name] = config.SnapshotConfig{
|
|
||||||
Paths: []string{filepath.Join(e.src, rel)},
|
|
||||||
Exclude: exclude,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// backUp runs a backup of the named snapshot and returns its output.
|
|
||||||
func (e *deletedCountEnv) backUp(t *testing.T, name string) string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
e.out.Reset()
|
|
||||||
require.NoError(t, e.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{
|
|
||||||
Snapshots: []string{name},
|
|
||||||
}))
|
|
||||||
|
|
||||||
return e.out.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// A file this snapshot excludes is not counted as deleted: neither one
|
|
||||||
// that another snapshot backs up, nor one that the previous snapshot of
|
|
||||||
// this name had before the exclude was added.
|
|
||||||
func TestBackupDoesNotCountExcludedFileAsDeleted(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newDeletedCountEnv(t, map[string][]byte{
|
|
||||||
"top.txt": []byte("top"),
|
|
||||||
"cache/tmp.bin": []byte("cache"),
|
|
||||||
"photos/a.jpg": []byte("photo a"),
|
|
||||||
"photos/b.jpg": []byte("photo b"),
|
|
||||||
"photos/c.jpg": []byte("photo c"),
|
|
||||||
})
|
|
||||||
env.setSnapshot("photos", "photos")
|
|
||||||
env.setSnapshot("home", "", "/photos")
|
|
||||||
|
|
||||||
env.backUp(t, "photos")
|
|
||||||
assert.Contains(t, env.backUp(t, "home"), filesLine(2, 2, 0))
|
|
||||||
|
|
||||||
env.setSnapshot("home", "", "/photos", "/cache")
|
|
||||||
assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1))
|
|
||||||
}
|
|
||||||
|
|
||||||
// A file inside a directory that an exclude added after a backup
|
|
||||||
// matches is not counted as deleted, though the pattern matches only the
|
|
||||||
// directory.
|
|
||||||
func TestBackupDoesNotCountFileInExcludedDirectoryAsDeleted(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newDeletedCountEnv(t, map[string][]byte{
|
|
||||||
"top.txt": []byte("top"),
|
|
||||||
"user/.local/share/Trash/old.txt": []byte("old"),
|
|
||||||
})
|
|
||||||
env.setSnapshot("home", "")
|
|
||||||
|
|
||||||
assert.Contains(t, env.backUp(t, "home"), filesLine(2, 2, 0))
|
|
||||||
|
|
||||||
env.setSnapshot("home", "", "*/.local/share/Trash")
|
|
||||||
assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1))
|
|
||||||
}
|
|
||||||
|
|
||||||
// A backup counts only files that the previous snapshot of its own name
|
|
||||||
// had, not one that a later snapshot of another name over the same path
|
|
||||||
// had and that is since removed.
|
|
||||||
func TestBackupIgnoresSnapshotOfAnotherName(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
env := newDeletedCountEnv(t, map[string][]byte{
|
|
||||||
"kept.txt": []byte("kept"),
|
|
||||||
})
|
|
||||||
env.setSnapshot("home", "")
|
|
||||||
env.setSnapshot("other", "")
|
|
||||||
|
|
||||||
env.backUp(t, "home")
|
|
||||||
|
|
||||||
// Snapshot start times are kept in whole seconds: wait so that other's
|
|
||||||
// snapshot is strictly the most recent.
|
|
||||||
time.Sleep(time.Second)
|
|
||||||
|
|
||||||
extra := filepath.Join(env.src, "extra.txt")
|
|
||||||
require.NoError(t, os.WriteFile(extra, []byte("extra"), 0o600))
|
|
||||||
env.backUp(t, "other")
|
|
||||||
require.NoError(t, os.Remove(extra))
|
|
||||||
|
|
||||||
assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1))
|
|
||||||
}
|
|
||||||
|
|
||||||
// A file removed from disk is counted as deleted by the next backup of
|
|
||||||
// the snapshot that had it, and not by any later backup of that
|
|
||||||
// snapshot, nor by the first backup of another name over the same path.
|
|
||||||
func TestBackupCountsDeletedFileOnce(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
aContent := bytes.Repeat([]byte("a"), 1000)
|
|
||||||
bContent := bytes.Repeat([]byte("b"), 2000)
|
|
||||||
keptContent := bytes.Repeat([]byte("k"), 500)
|
|
||||||
|
|
||||||
env := newDeletedCountEnv(t, map[string][]byte{
|
|
||||||
"a.txt": aContent,
|
|
||||||
"b.txt": bContent,
|
|
||||||
"kept.txt": keptContent,
|
|
||||||
})
|
|
||||||
env.setSnapshot("home", "")
|
|
||||||
env.setSnapshot("other", "")
|
|
||||||
|
|
||||||
assert.Contains(t, env.backUp(t, "home"), filesLine(3, 3, 0))
|
|
||||||
|
|
||||||
require.NoError(t, os.Remove(filepath.Join(env.src, "a.txt")))
|
|
||||||
require.NoError(t, os.Remove(filepath.Join(env.src, "b.txt")))
|
|
||||||
|
|
||||||
summary := env.backUp(t, "home")
|
|
||||||
assert.Contains(t, summary,
|
|
||||||
"Files: 1 examined, 0 backed up, 1 unchanged, 2 deleted.")
|
|
||||||
assert.Contains(t, summary,
|
|
||||||
fmt.Sprintf("Data: %s total (%s backed up), %s deleted.",
|
|
||||||
env.v.UI.Size(int64(len(keptContent))), env.v.UI.Size(0),
|
|
||||||
env.v.UI.Size(int64(len(aContent)+len(bContent)))))
|
|
||||||
|
|
||||||
assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1))
|
|
||||||
assert.Contains(t, env.backUp(t, "other"), filesLine(1, 0, 1))
|
|
||||||
}
|
|
||||||
@@ -87,7 +87,7 @@ func TestSnapshotSummaryCountsFileNotStoredAsFailed(t *testing.T) {
|
|||||||
"src": {Paths: []string{srcDir}},
|
"src": {Paths: []string{srcDir}},
|
||||||
}
|
}
|
||||||
|
|
||||||
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
store, err := storage.NewFileStorer(t.TempDir())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
db, err := database.New(ctx, cfg.IndexPath)
|
db, err := database.New(ctx, cfg.IndexPath)
|
||||||
|
|||||||
@@ -122,6 +122,9 @@ func newListEnv(t *testing.T) *listEnv {
|
|||||||
store := newObservingStorer()
|
store := newObservingStorer()
|
||||||
stdout := &bytes.Buffer{}
|
stdout := &bytes.Buffer{}
|
||||||
|
|
||||||
|
// A backup wrote to this destination, so it carries the marker.
|
||||||
|
require.NoError(t, store.Put(ctx, markerFile, strings.NewReader("")))
|
||||||
|
|
||||||
v := &vaultik.Vaultik{
|
v := &vaultik.Vaultik{
|
||||||
Config: &config.Config{
|
Config: &config.Config{
|
||||||
AgeSecretKey: "",
|
AgeSecretKey: "",
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ func TestSkipErrorsBackupStopsOnIndexErrorRecordingDirectory(t *testing.T) {
|
|||||||
"tree": {Paths: []string{srcDir}},
|
"tree": {Paths: []string{srcDir}},
|
||||||
}
|
}
|
||||||
|
|
||||||
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
store, err := storage.NewFileStorer(t.TempDir())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
db, err := database.New(ctx, cfg.IndexPath)
|
db, err := database.New(ctx, cfg.IndexPath)
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ func newSummaryEnv(t *testing.T) *summaryEnv {
|
|||||||
"split": {Paths: []string{dirOne, dirTwo}},
|
"split": {Paths: []string{dirOne, dirTwo}},
|
||||||
}
|
}
|
||||||
|
|
||||||
inner, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
inner, err := storage.NewFileStorer(t.TempDir())
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
store := faultstore.New(inner)
|
store := faultstore.New(inner)
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ func TestBackupWithoutCronOfTwoPathSnapshotRestoresBothPaths(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
firstDir := filepath.Join(tempDir, "first")
|
firstDir := filepath.Join(tempDir, "first")
|
||||||
secondDir := filepath.Join(tempDir, "second")
|
secondDir := filepath.Join(tempDir, "second")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ func TestVerify_QuietSuppressesReport(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := filepath.Join(tempDir, "remote")
|
storeDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(32 * 1024)
|
chunkSize := int64(32 * 1024)
|
||||||
|
|||||||
Reference in New Issue
Block a user