Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6476fa831a |
@@ -311,8 +311,6 @@ 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
|
||||||
│
|
│
|
||||||
@@ -369,8 +367,6 @@ 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]}/
|
||||||
@@ -382,15 +378,6 @@ 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,10 +24,6 @@ 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
|
||||||
@@ -302,10 +298,6 @@ value where a list belongs or a word where a number belongs), is refused.
|
|||||||
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
|
||||||
@@ -335,10 +327,7 @@ 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. It does the same when the
|
local index alone, and still exits zero.
|
||||||
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
|
||||||
@@ -376,13 +365,11 @@ 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, or the
|
runs automatically. If the destination store is unreachable, the local-DB
|
||||||
local index holds snapshots and the destination has no
|
removal still completes and a warning is emitted; run `vaultik snapshot
|
||||||
`vaultik-destination.txt`, the local-DB removal still completes and a
|
remove <snapshot-id>` again once the store is reachable to remove the
|
||||||
warning is emitted; run `vaultik snapshot remove <snapshot-id>` again
|
snapshot's metadata from it (`vaultik prune` does not). To wipe everything
|
||||||
once the store is reachable to remove the snapshot's metadata from it
|
on the destination in one go, use `vaultik remote nuke --force`.
|
||||||
(`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
|
||||||
@@ -413,12 +400,8 @@ 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. If the destination store cannot
|
manual entry point for the same work. If a blob cannot be deleted, the
|
||||||
be listed, or the local index holds snapshots and the destination has
|
command (and `snapshot create --prune`) exits non-zero.
|
||||||
no `vaultik-destination.txt` (an unplugged volume's empty mount point),
|
|
||||||
prune fails and deletes nothing. `snapshot purge` does the same. If a
|
|
||||||
blob cannot be deleted, the command (and `snapshot create --prune`)
|
|
||||||
exits non-zero.
|
|
||||||
* `--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. A blob that cannot be deleted is counted in
|
`--force` does. A blob that cannot be deleted is counted in
|
||||||
@@ -442,12 +425,11 @@ since `prune` never deletes it.
|
|||||||
* `--json`: Output as JSON
|
* `--json`: Output as JSON
|
||||||
|
|
||||||
**`remote nuke`**: Delete every object under `metadata/` and `blobs/` on
|
**`remote nuke`**: Delete every object under `metadata/` and `blobs/` on
|
||||||
the backup destination store, whatever its name, and then
|
the backup destination store, whatever its name, leaving the bucket prefix
|
||||||
`vaultik-destination.txt`, leaving the bucket prefix empty. Destructive
|
empty. Destructive and irreversible. This is the single supported way to
|
||||||
and irreversible. This is the single supported way to wipe the entire
|
wipe the entire destination store. If a listing afterwards still finds
|
||||||
destination store. If a listing afterwards still finds anything under
|
anything there, the command names each object left and exits non-zero;
|
||||||
`metadata/` or `blobs/`, the command names each object left and exits
|
running it again deletes what is left.
|
||||||
non-zero; running it again deletes what is left.
|
|
||||||
* `--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
|
||||||
@@ -472,12 +454,7 @@ 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 directory must exist before the first backup: vaultik
|
the same directory.
|
||||||
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`).
|
||||||
@@ -508,7 +485,6 @@ 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/
|
||||||
@@ -517,15 +493,6 @@ 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
|
||||||
@@ -745,8 +712,10 @@ the `NO_COLOR` environment variable is unset (https://no-color.org/).
|
|||||||
reports and tables (`version`, `info`, `remote info`, `snapshot
|
reports and tables (`version`, `info`, `remote info`, `snapshot
|
||||||
verify`, `snapshot list`) but never the machine-consumed `config get`
|
verify`, `snapshot list`) but never the machine-consumed `config get`
|
||||||
value or the `--json` documents, which a script depends on. The
|
value or the `--json` documents, which a script depends on. The
|
||||||
`database delete` confirmation prompt is also written this way and
|
confirmation prompts of `database delete`, `prune`, `snapshot purge`
|
||||||
always shown: it is an interactive exchange the operator must see.
|
and `snapshot remove`, each with what it asks to delete, are also
|
||||||
|
written this way and always shown: they are an interactive exchange
|
||||||
|
the operator must see.
|
||||||
|
|
||||||
`internal/ui` writes to stdout; it is the output the user asked for. The
|
`internal/ui` writes to stdout; it is the output the user asked for. The
|
||||||
exceptions are the startup banner and the error a failed command ends
|
exceptions are the startup banner and the error a failed command ends
|
||||||
|
|||||||
@@ -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, plus a marker file:
|
Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components:
|
||||||
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,7 +12,6 @@ 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]>/
|
||||||
@@ -25,10 +24,6 @@ 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,8 +101,7 @@ 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, and gives the destination the
|
// counterpart on the destination store. Returns the config path.
|
||||||
// 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()
|
||||||
|
|
||||||
@@ -132,11 +131,6 @@ 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
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// flagCron is used to build the argument vectors below.
|
||||||
|
const flagCron = "--cron"
|
||||||
|
|
||||||
|
// plantUnreferencedBlob writes a blob that no snapshot references to the
|
||||||
|
// destination store at storeDir, so that a prune deletes it. Returns its
|
||||||
|
// path.
|
||||||
|
func plantUnreferencedBlob(t *testing.T, storeDir string) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
hash := strings.Repeat("b", 64)
|
||||||
|
path := filepath.Join(storeDir, "blobs", hash[:2], hash[2:4], hash)
|
||||||
|
|
||||||
|
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(path, []byte("unreferenced"), 0o600))
|
||||||
|
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreatePruneIsSilent checks that a successful
|
||||||
|
// `snapshot create --prune` under --cron or --quiet prints nothing on
|
||||||
|
// stdout or stderr, whether or not the prune finds a blob to delete.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreatePruneIsSilent(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
plantBlob bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "cron, no blob to delete",
|
||||||
|
args: []string{cmdSnapshot, cmdCreate, flagCron, flagPrune},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cron, blob to delete",
|
||||||
|
args: []string{cmdSnapshot, cmdCreate, flagCron, flagPrune},
|
||||||
|
plantBlob: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cron with keep-newer-than",
|
||||||
|
args: []string{
|
||||||
|
cmdSnapshot, cmdCreate, flagCron, flagPrune,
|
||||||
|
flagKeepNewerThan, "4w",
|
||||||
|
},
|
||||||
|
plantBlob: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "quiet",
|
||||||
|
args: []string{flagQuiet, cmdSnapshot, cmdCreate, flagPrune},
|
||||||
|
plantBlob: true,
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
var blob string
|
||||||
|
if testCase.plantBlob {
|
||||||
|
blob = plantUnreferencedBlob(t, storeDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, stdout, stderr := runEntry(t,
|
||||||
|
append([]string{flagConfig, configPath}, testCase.args...)...)
|
||||||
|
|
||||||
|
assert.Equal(t, 0, code)
|
||||||
|
assert.Empty(t, stdout)
|
||||||
|
assert.Empty(t, stderr)
|
||||||
|
|
||||||
|
if testCase.plantBlob {
|
||||||
|
assert.NoFileExists(t, blob, "the prune must delete the blob")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntryPruneQuietIsSilent checks that a successful `prune --force`
|
||||||
|
// under --quiet prints nothing on stdout or stderr, both when there is
|
||||||
|
// nothing to remove and when it removes a stale local snapshot record
|
||||||
|
// and an unreferenced blob.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntryPruneQuietIsSilent(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
staleRecordAndBlob bool
|
||||||
|
}{
|
||||||
|
{name: "nothing to remove"},
|
||||||
|
{name: "stale record and blob to remove", staleRecordAndBlob: true},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
configPath := writeHermeticPruneConfig(t, testCase.staleRecordAndBlob)
|
||||||
|
|
||||||
|
var blob string
|
||||||
|
if testCase.staleRecordAndBlob {
|
||||||
|
// writeHermeticPruneConfig puts the store beside the config.
|
||||||
|
blob = plantUnreferencedBlob(t,
|
||||||
|
filepath.Join(filepath.Dir(configPath), "store"))
|
||||||
|
}
|
||||||
|
|
||||||
|
code, stdout, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, flagQuiet, cmdPrune, flagForce)
|
||||||
|
|
||||||
|
assert.Equal(t, 0, code)
|
||||||
|
assert.Empty(t, stdout)
|
||||||
|
assert.Empty(t, stderr)
|
||||||
|
|
||||||
|
if testCase.staleRecordAndBlob {
|
||||||
|
assert.NoFileExists(t, blob, "the prune must delete the blob")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,11 +41,6 @@ func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T)
|
|||||||
// too, so the purge selects it rather than dropping it as stale.
|
// too, so the purge selects it rather than dropping it as stale.
|
||||||
seedStaleSnapshotRecord(t, indexPath)
|
seedStaleSnapshotRecord(t, indexPath)
|
||||||
|
|
||||||
// While the local index holds a snapshot, purge fails on a
|
|
||||||
// destination without the marker a backup writes.
|
|
||||||
require.NoError(t, os.WriteFile(
|
|
||||||
filepath.Join(dir, "store", "vaultik-destination.txt"), nil, 0o600))
|
|
||||||
|
|
||||||
manifestDir := filepath.Join(dir, "store", "metadata",
|
manifestDir := filepath.Join(dir, "store", "metadata",
|
||||||
snapshot.RemoteSnapshotKey(stalePruneSnapshotID))
|
snapshot.RemoteSnapshotKey(stalePruneSnapshotID))
|
||||||
require.NoError(t, os.MkdirAll(manifestDir, 0o750))
|
require.NoError(t, os.MkdirAll(manifestDir, 0o750))
|
||||||
@@ -64,12 +59,10 @@ func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T)
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, db.Close())
|
require.NoError(t, db.Close())
|
||||||
|
|
||||||
code, _, stderr := runEntry(t, flagConfig, configPath,
|
code, _, _ := runEntry(t, flagConfig, configPath,
|
||||||
cmdSnapshot, cmdPurge, flagOlderThan, "30d", flagForce)
|
cmdSnapshot, cmdPurge, flagOlderThan, "30d", flagForce)
|
||||||
|
|
||||||
assert.Equal(t, 1, code)
|
assert.Equal(t, 1, code)
|
||||||
assert.Contains(t, stderr, "simulated index error",
|
|
||||||
"the purge must fail at the local-index delete")
|
|
||||||
assert.FileExists(t, manifestPath,
|
assert.FileExists(t, manifestPath,
|
||||||
"the snapshot is still in the local index, so its metadata must stay")
|
"the snapshot is still in the local index, so its metadata must stay")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -578,54 +578,3 @@ func TestExcludePatterns_DoubleStarFileAtEveryDepth(t *testing.T) {
|
|||||||
require.Equal(t, 1, result.FilesScanned,
|
require.Equal(t, 1, result.FilesScanned,
|
||||||
"**/ file pattern should match at the top level and nested")
|
"**/ file pattern should match at the top level and nested")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExcludePatterns_AnchoredDoubleStarAtEveryDepth(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// As in gitignore, /**/ also matches directly under the source dir
|
|
||||||
fs := setupAnchoredTestFS(t)
|
|
||||||
|
|
||||||
scanner, repos, cleanup := createTestScanner(t, fs, []string{"/**/projectname"})
|
|
||||||
defer cleanup()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
createSnapshotRecord(ctx, t, repos, "test-snapshot")
|
|
||||||
|
|
||||||
result, err := scanner.Scan(ctx, "/backup", "test-snapshot")
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// /**/projectname should exclude BOTH:
|
|
||||||
// - /backup/projectname/file.txt
|
|
||||||
// - /backup/otherproject/projectname/file.txt
|
|
||||||
// Total files: 4, excluded: 2
|
|
||||||
require.Equal(t, 2, result.FilesScanned,
|
|
||||||
"/**/ pattern should match at the top level and nested")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExcludePatterns_DoubleStarInMiddleMatchesZeroDirectories(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
// As in gitignore, a/**/b matches a/b as well as a/c/b. The last part
|
|
||||||
// is a glob: with a plain name the glob library already matched a/b.
|
|
||||||
fs := &afero.MemMapFs{}
|
|
||||||
files := []string{"/backup/a/x.log", "/backup/a/c/y.log", "/backup/a/c/kept.txt"}
|
|
||||||
|
|
||||||
for _, path := range files {
|
|
||||||
require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0755))
|
|
||||||
require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0644))
|
|
||||||
}
|
|
||||||
|
|
||||||
scanner, repos, cleanup := createTestScanner(t, fs, []string{"a/**/*.log"})
|
|
||||||
defer cleanup()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
createSnapshotRecord(ctx, t, repos, "test-snapshot")
|
|
||||||
|
|
||||||
result, err := scanner.Scan(ctx, "/backup", "test-snapshot")
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// a/**/*.log should exclude /backup/a/x.log and /backup/a/c/y.log
|
|
||||||
// Total files: 3, excluded: 2
|
|
||||||
require.Equal(t, 1, result.FilesScanned,
|
|
||||||
"a/**/*.log should match a/x.log as well as a/c/y.log")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2035,60 +2035,33 @@ func compileExcludePatterns(patterns []string) []compiledPattern {
|
|||||||
pattern = strings.TrimSuffix(pattern, "/")
|
pattern = strings.TrimSuffix(pattern, "/")
|
||||||
|
|
||||||
// A leading "**/" demands a "/" before the name and so misses an
|
// A leading "**/" demands a "/" before the name and so misses an
|
||||||
// entry directly under the source path. It means "at every depth",
|
// entry directly under the source path. An unanchored pattern
|
||||||
// which is what an unanchored pattern already does, so drop the
|
// already matches at every depth, so drop the prefix: as in
|
||||||
// prefix and match unanchored: as in gitignore, "**/x" and
|
// gitignore, "**/x" then also matches a top-level "x".
|
||||||
// "/**/x" then also match a top-level "x".
|
if !anchored {
|
||||||
if rest, found := strings.CutPrefix(pattern, "**/"); found {
|
pattern = strings.TrimPrefix(pattern, "**/")
|
||||||
pattern = rest
|
|
||||||
anchored = false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Likewise "/**/" inside a pattern demands two slashes, so
|
// Compile the glob pattern
|
||||||
// "a/**/*.log" misses "a/x.log". As in gitignore it stands for
|
// For patterns without path separators, we need to match them as components
|
||||||
// zero or more directories, so also compile the pattern with it
|
// e.g., ".git" should match ".git" anywhere in the path
|
||||||
// made a single "/". The glob library's {a,b} is no help: with a
|
g, err := glob.Compile(pattern, '/')
|
||||||
// "**" inside it in mid-pattern, it misses paths it should match.
|
if err != nil {
|
||||||
for _, variant := range doubleStarVariants(pattern) {
|
log.Warn("Invalid exclude pattern, skipping", "pattern", p, "error", err)
|
||||||
// For patterns without path separators, we need to match them as components
|
|
||||||
// e.g., ".git" should match ".git" anywhere in the path
|
|
||||||
g, err := glob.Compile(variant, '/')
|
|
||||||
if err != nil {
|
|
||||||
log.Warn("Invalid exclude pattern, skipping", "pattern", p, "error", err)
|
|
||||||
|
|
||||||
break
|
continue
|
||||||
}
|
|
||||||
|
|
||||||
compiled = append(compiled, compiledPattern{
|
|
||||||
pattern: g,
|
|
||||||
anchored: anchored,
|
|
||||||
original: p,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
compiled = append(compiled, compiledPattern{
|
||||||
|
pattern: g,
|
||||||
|
anchored: anchored,
|
||||||
|
original: p,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return compiled
|
return compiled
|
||||||
}
|
}
|
||||||
|
|
||||||
// doubleStarVariants returns pattern once for every way of keeping each
|
|
||||||
// "/**/" in it or making it a single "/".
|
|
||||||
func doubleStarVariants(pattern string) []string {
|
|
||||||
const doubleStar = "/**/"
|
|
||||||
|
|
||||||
before, after, found := strings.Cut(pattern, doubleStar)
|
|
||||||
if !found {
|
|
||||||
return []string{pattern}
|
|
||||||
}
|
|
||||||
|
|
||||||
var variants []string
|
|
||||||
|
|
||||||
for _, rest := range doubleStarVariants(after) {
|
|
||||||
variants = append(variants, before+doubleStar+rest, before+"/"+rest)
|
|
||||||
}
|
|
||||||
|
|
||||||
return variants
|
|
||||||
}
|
|
||||||
|
|
||||||
// shouldExclude checks if a path should be excluded based on exclude patterns
|
// shouldExclude checks if a path should be excluded based on exclude patterns
|
||||||
// filePath is the full path to the file
|
// filePath is the full path to the file
|
||||||
// rootPath is the root of the backup source directory
|
// rootPath is the root of the backup source directory
|
||||||
|
|||||||
@@ -21,13 +21,9 @@ 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 backend never creates basePath: the user does, so that when
|
// The basePath is recorded; the directory is created lazily on first
|
||||||
// basePath is a directory on an unplugged volume, a write fails instead
|
// write. Write operations (Put/PutWithProgress) call MkdirAll for the
|
||||||
// of landing on the disk under the mount point. This does not hold when
|
// per-blob parent directory, which also covers basePath on first use.
|
||||||
// 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.
|
||||||
@@ -303,19 +299,7 @@ func (f *FileStorer) writeAtomic(
|
|||||||
path := f.fullPath(key)
|
path := f.fullPath(key)
|
||||||
dir := filepath.Dir(path)
|
dir := filepath.Dir(path)
|
||||||
|
|
||||||
// Checked on every write, so a destination that disappears part-way
|
err := f.fs.MkdirAll(dir, storageDirPerm)
|
||||||
// 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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -292,43 +292,3 @@ func TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -7,12 +7,10 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/config"
|
|
||||||
"github.com/rclone/rclone/fs/config/configfile"
|
"github.com/rclone/rclone/fs/config/configfile"
|
||||||
"github.com/rclone/rclone/fs/operations"
|
"github.com/rclone/rclone/fs/operations"
|
||||||
|
|
||||||
@@ -35,15 +33,6 @@ type RcloneStorer struct {
|
|||||||
// The remote parameter is the rclone remote name (as configured via `rclone config`).
|
// The remote parameter is the rclone remote name (as configured via `rclone config`).
|
||||||
// The path parameter is the path within the remote.
|
// The path parameter is the path within the remote.
|
||||||
func NewRcloneStorer(ctx context.Context, remote, path string) (*RcloneStorer, error) {
|
func NewRcloneStorer(ctx context.Context, remote, path string) (*RcloneStorer, error) {
|
||||||
// rclone reads RCLONE_CONFIG only as the value of its --config flag,
|
|
||||||
// which vaultik does not have, so it is applied here as that flag would.
|
|
||||||
if configPath, ok := os.LookupEnv("RCLONE_CONFIG"); ok {
|
|
||||||
err := config.SetConfigPath(configPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("using RCLONE_CONFIG %q: %w", configPath, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Install the default config file handler
|
// Install the default config file handler
|
||||||
configfile.Install()
|
configfile.Install()
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/rclone/rclone/fs"
|
"github.com/rclone/rclone/fs"
|
||||||
"github.com/rclone/rclone/fs/config"
|
|
||||||
"github.com/rclone/rclone/fs/config/configmap"
|
"github.com/rclone/rclone/fs/config/configmap"
|
||||||
"sneak.berlin/go/vaultik/internal/storage"
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
)
|
)
|
||||||
@@ -391,41 +390,3 @@ func TestNewRcloneStorerUnknownRemote(t *testing.T) {
|
|||||||
t.Errorf("NewRcloneStorer error = %v, want ErrRemoteNotFound", err)
|
t.Errorf("NewRcloneStorer error = %v, want ErrRemoteNotFound", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestNewRcloneStorerReadsRcloneConfigEnv checks that a remote defined only
|
|
||||||
// in the file RCLONE_CONFIG names is found and written to, as rclone itself
|
|
||||||
// would.
|
|
||||||
func TestNewRcloneStorerReadsRcloneConfigEnv(t *testing.T) {
|
|
||||||
// rclone keeps the config file path in a process-global variable, which
|
|
||||||
// NewRcloneStorer leaves pointing at this test's file.
|
|
||||||
previous := config.GetConfigPath()
|
|
||||||
|
|
||||||
t.Cleanup(func() { _ = config.SetConfigPath(previous) })
|
|
||||||
|
|
||||||
confFile := filepath.Join(t.TempDir(), "rclone.conf")
|
|
||||||
|
|
||||||
err := os.WriteFile(confFile, []byte("[loc]\ntype = local\n"), 0o600)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("writing rclone config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Setenv("RCLONE_CONFIG", confFile)
|
|
||||||
|
|
||||||
dir := t.TempDir()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
s, err := storage.NewRcloneStorer(ctx, "loc", dir)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewRcloneStorer: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = s.Put(ctx, testBlobKey, strings.NewReader("blob-bytes"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Put: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = os.Stat(filepath.Join(dir, testBlobKey))
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("object is not in the remote's directory: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -41,8 +41,7 @@ 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.
|
||||||
// The filesystem backend fails when its destination directory does
|
// Parent directories are created automatically for filesystem backends.
|
||||||
// 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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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")
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ func TestDeepVerifyAcceptsHealthyAndRejectsCorruptBlob(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(64 * 1024)
|
chunkSize := int64(64 * 1024)
|
||||||
@@ -93,7 +93,7 @@ func TestDeepVerifyJSONCountsBlobs(t *testing.T) {
|
|||||||
|
|
||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(t.TempDir(), "remote")
|
||||||
|
|
||||||
cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir)
|
cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir)
|
||||||
|
|
||||||
@@ -149,7 +149,7 @@ func TestDeepVerifyJSONCountsWrongSizeBlob(t *testing.T) {
|
|||||||
|
|
||||||
fs := afero.NewOsFs()
|
fs := afero.NewOsFs()
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(t.TempDir(), "remote")
|
||||||
|
|
||||||
cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir)
|
cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir)
|
||||||
|
|
||||||
@@ -178,7 +178,7 @@ func TestDeepVerifyStopsOnBlobThatCannotBeChecked(t *testing.T) {
|
|||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(t.TempDir(), "remote")
|
||||||
|
|
||||||
cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir)
|
cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir)
|
||||||
failing := statFailingStorer{Storer: storer, failKeys: []string{keys[0]}}
|
failing := statFailingStorer{Storer: storer, failKeys: []string{keys[0]}}
|
||||||
|
|||||||
@@ -1,74 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -298,6 +298,10 @@ 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)
|
||||||
|
|
||||||
@@ -361,7 +365,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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -425,7 +429,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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -441,10 +445,6 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) {
|
|||||||
|
|
||||||
repos := database.NewRepositories(db)
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
// snapshot create writes the marker; this backup runs its steps one
|
|
||||||
// by one, so the marker is written here.
|
|
||||||
require.NoError(t, inner.Put(ctx, markerFile, strings.NewReader("")))
|
|
||||||
|
|
||||||
// Back up and complete with a working backend.
|
// Back up and complete with a working backend.
|
||||||
sm := newFaultSnapshotManager(fs, inner, cfg, repos)
|
sm := newFaultSnapshotManager(fs, inner, cfg, repos)
|
||||||
scanner := newFaultScanner(fs, inner, cfg, repos)
|
scanner := newFaultScanner(fs, inner, cfg, repos)
|
||||||
@@ -493,14 +493,8 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) {
|
|||||||
"shallow verify must report the missing manifest")
|
"shallow verify must report the missing manifest")
|
||||||
|
|
||||||
// snapshot list must not crash on the partial snapshot.
|
// snapshot list must not crash on the partial snapshot.
|
||||||
var listOut strings.Builder
|
|
||||||
|
|
||||||
reader.UI = ui.NewWithColor(&listOut, false)
|
|
||||||
require.NoError(t, reader.ListSnapshots(false),
|
require.NoError(t, reader.ListSnapshots(false),
|
||||||
"snapshot list must tolerate a partially-exported snapshot")
|
"snapshot list must tolerate a partially-exported snapshot")
|
||||||
assert.NotContains(t, listOut.String(),
|
|
||||||
"Could not list backup destination store",
|
|
||||||
"snapshot list must read the partial snapshot from the destination")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scenario 2, repair: the process dies during the metadata export of a
|
// Scenario 2, repair: the process dies during the metadata export of a
|
||||||
@@ -517,7 +511,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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -692,7 +686,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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -24,11 +24,13 @@ 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.
|
||||||
|
|
||||||
// newFileDestinationVaultik returns a Vaultik that backs up the
|
// backUpToFileDestination backs up the snapshot named "first" to a
|
||||||
// snapshot named "first" to a file:// destination at storeDir.
|
// file:// destination at storeDir, which need not exist yet. Everything
|
||||||
func newFileDestinationVaultik(
|
// the returned Vaultik prints after the backup goes to the returned
|
||||||
|
// buffer.
|
||||||
|
func backUpToFileDestination(
|
||||||
ctx context.Context, t *testing.T, storeDir string,
|
ctx context.Context, t *testing.T, storeDir string,
|
||||||
) (*vaultik.Vaultik, *database.Repositories) {
|
) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
osFs := afero.NewOsFs()
|
osFs := afero.NewOsFs()
|
||||||
@@ -47,22 +49,8 @@ func newFileDestinationVaultik(
|
|||||||
|
|
||||||
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{}
|
||||||
@@ -87,28 +75,21 @@ func backUpThenUnplug(
|
|||||||
return v, repos, out
|
return v, repos, out
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestBackupFailsWhenDestinationDirectoryMissing checks that a backup to
|
// TestFirstBackupCreatesDestinationDirectory checks that a first backup
|
||||||
// a file:// destination whose directory does not exist fails before it
|
// to a destination directory that does not exist yet creates it, and
|
||||||
// records a snapshot, and does not create the directory.
|
// that the destination can be listed afterwards.
|
||||||
func TestBackupFailsWhenDestinationDirectoryMissing(t *testing.T) {
|
func TestFirstBackupCreatesDestinationDirectory(t *testing.T) {
|
||||||
log.Initialize(log.Config{})
|
log.Initialize(log.Config{})
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
volume := filepath.Join(t.TempDir(), "volume")
|
storeDir := filepath.Join(t.TempDir(), "volume", "backup")
|
||||||
v, repos := newFileDestinationVaultik(ctx, t, filepath.Join(volume, "backup"))
|
v, _, out := backUpToFileDestination(ctx, t, storeDir)
|
||||||
|
|
||||||
err := backUp(v, "first")
|
require.NoError(t, v.ListSnapshots(false))
|
||||||
require.ErrorIs(t, err, fs.ErrNotExist)
|
|
||||||
require.ErrorContains(t, err, "create it, or mount the volume it is on")
|
|
||||||
|
|
||||||
_, err = os.Stat(volume)
|
assert.NotContains(t, out.String(), "Could not list backup destination store")
|
||||||
require.ErrorIs(t, err, fs.ErrNotExist,
|
assert.NotContains(t, out.String(), "not found in backup destination store")
|
||||||
"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
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ func TestNewChunkSizeOfChangedFileStaysFixed(t *testing.T) {
|
|||||||
|
|
||||||
appendRandomBytes(t, fs, files, changedPath, appendedFileSize)
|
appendRandomBytes(t, fs, files, changedPath, appendedFileSize)
|
||||||
|
|
||||||
store, err := storage.NewFileStorer(t.TempDir())
|
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
db, err := database.New(ctx, dbPath)
|
db, err := database.New(ctx, dbPath)
|
||||||
|
|||||||
+12
-15
@@ -42,10 +42,9 @@ const blobKeyParts = 4
|
|||||||
|
|
||||||
// NukeRemote deletes every object under metadata/ and blobs/ in remote
|
// NukeRemote deletes every object under metadata/ and blobs/ in remote
|
||||||
// storage, whatever its name, along with any object an upload cut off
|
// storage, whatever its name, along with any object an upload cut off
|
||||||
// part-way left under a temporary `.partial` name, and last the
|
// part-way left under a temporary `.partial` name. It returns
|
||||||
// destination marker. It returns successfully only when a listing
|
// successfully only when a listing afterwards finds nothing left there,
|
||||||
// afterwards finds nothing left under metadata/ and blobs/, and the next
|
// and the next backup then starts from scratch.
|
||||||
// backup then 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.
|
||||||
@@ -106,13 +105,6 @@ func (v *Vaultik) emptyDestinationStore() error {
|
|||||||
return fmt.Errorf("%d %w", len(left), errObjectsLeft)
|
return fmt.Errorf("%d %w", len(left), errObjectsLeft)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,7 +204,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error {
|
|||||||
return v.outputPruneBlobsJSON(result)
|
return v.outputPruneBlobsJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.printlnStdout("No unreferenced blobs to remove.")
|
v.UI.Infof("No unreferenced blobs to remove.")
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -220,12 +212,17 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error {
|
|||||||
log.Info("Found unreferenced blobs",
|
log.Info("Found unreferenced blobs",
|
||||||
"count", len(unreferencedBlobs), "total_size", ubytes(totalSize))
|
"count", len(unreferencedBlobs), "total_size", ubytes(totalSize))
|
||||||
|
|
||||||
if !opts.JSON {
|
if opts.Force && !opts.JSON {
|
||||||
v.stdoutf("Found %d unreferenced blob(s) totaling %s\n",
|
v.UI.Infof("Found %d unreferenced blob(s) totaling %s.",
|
||||||
len(unreferencedBlobs), ubytes(totalSize))
|
len(unreferencedBlobs), ubytes(totalSize))
|
||||||
}
|
}
|
||||||
|
|
||||||
if !opts.Force && !opts.JSON {
|
if !opts.Force && !opts.JSON {
|
||||||
|
// The count, the prompt and its answer bypass the UI: they are an
|
||||||
|
// interactive exchange the operator must see, so --quiet does not
|
||||||
|
// silence them.
|
||||||
|
v.stdoutf("Found %d unreferenced blob(s) totaling %s.\n",
|
||||||
|
len(unreferencedBlobs), ubytes(totalSize))
|
||||||
v.stdoutf("\nDelete %d unreferenced blob(s)? [y/N] ", len(unreferencedBlobs))
|
v.stdoutf("\nDelete %d unreferenced blob(s)? [y/N] ", len(unreferencedBlobs))
|
||||||
|
|
||||||
var confirm string
|
var confirm string
|
||||||
@@ -252,7 +249,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
v.stdoutf("\nDeleted %d blob(s) totaling %s\n",
|
v.UI.Infof("Deleted %d blob(s) totaling %s.",
|
||||||
result.BlobsDeleted, ubytes(result.BytesFreed))
|
result.BlobsDeleted, ubytes(result.BytesFreed))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"sneak.berlin/go/vaultik/internal/log"
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
"sneak.berlin/go/vaultik/internal/snapshot"
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
"sneak.berlin/go/vaultik/internal/types"
|
"sneak.berlin/go/vaultik/internal/types"
|
||||||
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -34,9 +35,6 @@ 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])
|
||||||
@@ -61,13 +59,16 @@ func setupConsistencyTest(
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
stdout := &bytes.Buffer{}
|
||||||
|
|
||||||
v := &vaultik.Vaultik{
|
v := &vaultik.Vaultik{
|
||||||
Storage: mockStorage,
|
Storage: mockStorage,
|
||||||
Repositories: repos,
|
Repositories: repos,
|
||||||
DB: db,
|
DB: db,
|
||||||
Stdout: &bytes.Buffer{},
|
Stdout: stdout,
|
||||||
Stderr: &bytes.Buffer{},
|
Stderr: &bytes.Buffer{},
|
||||||
Stdin: &bytes.Buffer{},
|
Stdin: &bytes.Buffer{},
|
||||||
|
UI: ui.NewWithColor(stdout, false),
|
||||||
}
|
}
|
||||||
v.SetContext(ctx)
|
v.SetContext(ctx)
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"sneak.berlin/go/vaultik/internal/log"
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
"sneak.berlin/go/vaultik/internal/snapshot"
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
"sneak.berlin/go/vaultik/internal/types"
|
"sneak.berlin/go/vaultik/internal/types"
|
||||||
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -44,9 +45,6 @@ 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 {
|
||||||
@@ -89,6 +87,7 @@ func setupPurgeTest(
|
|||||||
Stdout: stdout,
|
Stdout: stdout,
|
||||||
Stderr: stderr,
|
Stderr: stderr,
|
||||||
Stdin: stdin,
|
Stdin: stdin,
|
||||||
|
UI: ui.NewWithColor(stdout, false),
|
||||||
}
|
}
|
||||||
v.SetContext(ctx)
|
v.SetContext(ctx)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package vaultik_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestPurgeSnapshots_QuietSuppressesReport checks that `snapshot purge
|
||||||
|
// --keep-latest --force` under --quiet deletes the older snapshot and
|
||||||
|
// prints nothing.
|
||||||
|
func TestPurgeSnapshots_QuietSuppressesReport(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
v := setupPurgeTest(t, snapHostname, []string{snapHomeT0, snapHomeT1})
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
|
||||||
|
v.Stdout = &out
|
||||||
|
v.UI = ui.NewWithColor(&out, false)
|
||||||
|
v.UI.SetQuiet(true)
|
||||||
|
|
||||||
|
require.NoError(t, v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{
|
||||||
|
KeepLatest: true,
|
||||||
|
Force: true,
|
||||||
|
}))
|
||||||
|
|
||||||
|
assert.Equal(t, []string{snapHomeT1}, listRemainingSnapshots(t, v))
|
||||||
|
assert.Empty(t, out.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPurgeSnapshots_QuietPromptListsSnapshots checks that `snapshot
|
||||||
|
// purge --keep-latest` without --force still lists the snapshots its
|
||||||
|
// prompt asks to delete under --quiet.
|
||||||
|
func TestPurgeSnapshots_QuietPromptListsSnapshots(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
v := setupPurgeTest(t, snapHostname, []string{snapHomeT0, snapHomeT1})
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
|
||||||
|
v.Stdout = &out
|
||||||
|
v.UI = ui.NewWithColor(&out, false)
|
||||||
|
v.UI.SetQuiet(true)
|
||||||
|
|
||||||
|
// Stdin is empty, so the prompt reads no answer and cancels.
|
||||||
|
require.NoError(t, v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{
|
||||||
|
KeepLatest: true,
|
||||||
|
}))
|
||||||
|
|
||||||
|
assert.Contains(t, out.String(), snapHomeT0)
|
||||||
|
assert.Contains(t, out.String(), "Delete 1 snapshot(s)? [y/N]")
|
||||||
|
assert.Len(t, listRemainingSnapshots(t, v), 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPruneBlobs_QuietPromptShowsBlobTotal checks that `prune` without
|
||||||
|
// --force still states the count and total size of the blobs its prompt
|
||||||
|
// asks to delete under --quiet.
|
||||||
|
func TestPruneBlobs_QuietPromptShowsBlobTotal(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
env := newListEnv(t)
|
||||||
|
env.v.UI.SetQuiet(true)
|
||||||
|
|
||||||
|
// The store holds no manifest, so nothing references this blob.
|
||||||
|
addBlob(t, env.store.testStorer, testBlobHashA)
|
||||||
|
|
||||||
|
// Stdin is empty, so the prompt reads no answer and cancels.
|
||||||
|
require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{}))
|
||||||
|
|
||||||
|
assert.Contains(t, env.stdout.String(),
|
||||||
|
"Found 1 unreferenced blob(s) totaling")
|
||||||
|
assert.Contains(t, env.stdout.String(),
|
||||||
|
"Delete 1 unreferenced blob(s)? [y/N]")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRemoveSnapshot_QuietSuppressesReport checks that `snapshot remove`
|
||||||
|
// under --quiet prints nothing with --dry-run or with --force, and that
|
||||||
|
// the --json document still prints.
|
||||||
|
func TestRemoveSnapshot_QuietSuppressesReport(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
newQuietRemover := func() (*vaultik.TestVaultik, *testStorer) {
|
||||||
|
store := newTestStorer()
|
||||||
|
addManifest(t, store, "snapshot-001", nil)
|
||||||
|
|
||||||
|
tv := vaultik.NewForTesting(store)
|
||||||
|
tv.Repositories = newLocalIndex(t, "snapshot-001")
|
||||||
|
tv.UI.SetQuiet(true)
|
||||||
|
|
||||||
|
return tv, store
|
||||||
|
}
|
||||||
|
|
||||||
|
tv, store := newQuietRemover()
|
||||||
|
|
||||||
|
_, err := tv.RemoveSnapshot("snapshot-001",
|
||||||
|
&vaultik.RemoveOptions{DryRun: true})
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, tv.Stdout.String(),
|
||||||
|
"--dry-run must print nothing under --quiet")
|
||||||
|
|
||||||
|
_, err = tv.RemoveSnapshot("snapshot-001",
|
||||||
|
&vaultik.RemoveOptions{Force: true})
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.False(t, store.hasKey(remoteKeyPath("snapshot-001")))
|
||||||
|
assert.Empty(t, tv.Stdout.String(),
|
||||||
|
"--force must print nothing under --quiet")
|
||||||
|
|
||||||
|
tv, _ = newQuietRemover()
|
||||||
|
|
||||||
|
_, err = tv.RemoveSnapshot("snapshot-001",
|
||||||
|
&vaultik.RemoveOptions{JSON: true})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
var result vaultik.RemoveResult
|
||||||
|
|
||||||
|
require.NoError(t, json.Unmarshal(tv.Stdout.Bytes(), &result),
|
||||||
|
"the --json document must still print under --quiet")
|
||||||
|
assert.True(t, result.RemoteRemoved)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNukeRemote_QuietSuppressesReport checks that `remote nuke --force`
|
||||||
|
// under --quiet prints nothing while it removes a snapshot's metadata
|
||||||
|
// and its blobs.
|
||||||
|
func TestNukeRemote_QuietSuppressesReport(t *testing.T) {
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
storeDir := filepath.Join(t.TempDir(), "store")
|
||||||
|
v, _, out := backUpToFileDestination(ctx, t, storeDir)
|
||||||
|
v.UI.SetQuiet(true)
|
||||||
|
|
||||||
|
require.NoError(t, v.NukeRemote(true))
|
||||||
|
assert.Empty(t, out.String())
|
||||||
|
}
|
||||||
@@ -303,10 +303,6 @@ 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")
|
||||||
|
|
||||||
@@ -354,7 +350,7 @@ func TestRemoveSnapshot_DryRun(t *testing.T) {
|
|||||||
assert.True(t, store.hasKey("blobs/aa/aa/"+blobA))
|
assert.True(t, store.hasKey("blobs/aa/aa/"+blobA))
|
||||||
assert.True(t, store.hasKey(remoteKeyPath("snapshot-001")))
|
assert.True(t, store.hasKey(remoteKeyPath("snapshot-001")))
|
||||||
|
|
||||||
assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]")
|
assert.Contains(t, tv.Stdout.String(), "Dry run: no changes made.")
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestRemoveSnapshot_UnknownIDIsError checks that an ID naming no
|
// TestRemoveSnapshot_UnknownIDIsError checks that an ID naming no
|
||||||
@@ -396,12 +392,7 @@ func TestRemoveSnapshot_NoMetadataOnDestination(t *testing.T) {
|
|||||||
log.Initialize(log.Config{})
|
log.Initialize(log.Config{})
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
// A backup wrote to this destination, so it carries the marker.
|
tv := vaultik.NewForTesting(newTestStorer())
|
||||||
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",
|
||||||
@@ -513,7 +504,7 @@ func TestRemoveAllSnapshots_DryRun(t *testing.T) {
|
|||||||
|
|
||||||
assert.Equal(t, initialCount, store.keyCount())
|
assert.Equal(t, initialCount, store.keyCount())
|
||||||
|
|
||||||
assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]")
|
assert.Contains(t, tv.Stdout.String(), "Dry run: no changes made.")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRemoveAllSnapshots_NoSnapshots(t *testing.T) {
|
func TestRemoveAllSnapshots_NoSnapshots(t *testing.T) {
|
||||||
|
|||||||
@@ -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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(root, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
storer, err := storage.NewFileStorer(storeDir)
|
storer, err := storage.NewFileStorer(storeDir)
|
||||||
|
|||||||
@@ -345,7 +345,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(t.TempDir())
|
storer, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
|
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
|
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func TestRestoreNamesUnmatchedPathAndRestoresTheMatchingOne(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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -89,7 +89,7 @@ func TestRestoreNamesEveryPathWhenNothingMatches(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
dataDir := filepath.Join(tempDir, "src")
|
dataDir := filepath.Join(tempDir, "src")
|
||||||
linkDir := filepath.Join(tempDir, "srclink")
|
linkDir := filepath.Join(tempDir, "srclink")
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
@@ -152,7 +152,7 @@ func TestRestoreNamesUnmatchedPathWhenADamagedBlobStopsIt(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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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 TestVerifyPassesWhenBackupReusesStoredBlob(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
secondDBPath := filepath.Join(tempDir, "second.sqlite")
|
secondDBPath := filepath.Join(tempDir, "second.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(64 * 1024)
|
chunkSize := int64(64 * 1024)
|
||||||
|
|||||||
@@ -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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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")
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(32 * 1024)
|
chunkSize := int64(32 * 1024)
|
||||||
@@ -110,7 +110,7 @@ func TestShallowVerifyDetectsMissingDatabase(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(32 * 1024)
|
chunkSize := int64(32 * 1024)
|
||||||
@@ -193,7 +193,7 @@ func TestShallowVerifyReportsStatErrorsApartFromMissing(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(32 * 1024)
|
chunkSize := int64(32 * 1024)
|
||||||
@@ -282,7 +282,7 @@ func TestShallowVerifyQuietFailsOnStatErrorAlone(t *testing.T) {
|
|||||||
tempDir := t.TempDir()
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
dataDir := filepath.Join(tempDir, "source")
|
dataDir := filepath.Join(tempDir, "source")
|
||||||
storeDir := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
chunkSize := int64(32 * 1024)
|
chunkSize := int64(32 * 1024)
|
||||||
|
|||||||
+69
-100
@@ -94,13 +94,6 @@ 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
|
||||||
@@ -123,9 +116,21 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error {
|
|||||||
return fmt.Errorf("prune database: %w", err)
|
return fmt.Errorf("prune database: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
snapshotNames, err := v.snapshotNamesToCreate(opts.Snapshots)
|
// Determine which snapshots to process
|
||||||
if err != nil {
|
snapshotNames := opts.Snapshots
|
||||||
return err
|
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 fmt.Errorf("%w: %q", errSnapshotNotInConfig, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(snapshotNames) == 0 {
|
||||||
|
return errNoSnapshotsInConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process each named snapshot
|
// Process each named snapshot
|
||||||
@@ -165,28 +170,6 @@ 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
|
||||||
@@ -591,7 +574,7 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error {
|
|||||||
|
|
||||||
if len(toDelete) == 0 {
|
if len(toDelete) == 0 {
|
||||||
if !opts.Quiet {
|
if !opts.Quiet {
|
||||||
v.printlnStdout("No snapshots to delete")
|
v.UI.Infof("No snapshots to delete.")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -648,19 +631,19 @@ func selectSnapshotsToPurge(
|
|||||||
func (v *Vaultik) confirmAndExecutePurge(
|
func (v *Vaultik) confirmAndExecutePurge(
|
||||||
toDelete []SnapshotInfo, force, quiet bool,
|
toDelete []SnapshotInfo, force, quiet bool,
|
||||||
) error {
|
) error {
|
||||||
if !quiet {
|
// Confirm unless --force is used. The list, the prompt and its answer
|
||||||
|
// bypass the UI: they are an interactive exchange the operator must
|
||||||
|
// see, so --quiet does not silence them.
|
||||||
|
if !force {
|
||||||
v.stdoutf("The following snapshots will be deleted:\n\n")
|
v.stdoutf("The following snapshots will be deleted:\n\n")
|
||||||
|
|
||||||
for _, snap := range toDelete {
|
for _, snap := range toDelete {
|
||||||
v.stdoutf(" %s (%s, %s)\n",
|
v.stdoutf(" %s (%s, %s)\n",
|
||||||
snap.ID,
|
snap.ID,
|
||||||
snap.Timestamp.Format("2006-01-02 15:04:05"),
|
snap.Timestamp.Format(time.DateTime),
|
||||||
ubytes(snap.CompressedSize))
|
ubytes(snap.CompressedSize))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Confirm unless --force is used
|
|
||||||
if !force {
|
|
||||||
v.stdoutf("\nDelete %d snapshot(s)? [y/N] ", len(toDelete))
|
v.stdoutf("\nDelete %d snapshot(s)? [y/N] ", len(toDelete))
|
||||||
|
|
||||||
var confirm string
|
var confirm string
|
||||||
@@ -678,7 +661,16 @@ func (v *Vaultik) confirmAndExecutePurge(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
} else if !quiet {
|
} else if !quiet {
|
||||||
v.stdoutf("\nDeleting %d snapshot(s) (--force specified)\n", len(toDelete))
|
v.UI.Infof("The following snapshots will be deleted:")
|
||||||
|
|
||||||
|
for _, snap := range toDelete {
|
||||||
|
v.UI.Detailf("%s (%s, %s)",
|
||||||
|
v.UI.Snapshot(snap.ID.String()),
|
||||||
|
snap.Timestamp.Format(time.DateTime),
|
||||||
|
ubytes(snap.CompressedSize))
|
||||||
|
}
|
||||||
|
|
||||||
|
v.UI.Infof("Deleting %d snapshot(s) (--force specified).", len(toDelete))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete snapshots (both local and remote)
|
// Delete snapshots (both local and remote)
|
||||||
@@ -711,9 +703,9 @@ func (v *Vaultik) confirmAndExecutePurge(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !quiet {
|
if !quiet {
|
||||||
v.stdoutf("Deleted %d snapshot(s)\n", len(toDelete))
|
v.UI.Infof("Deleted %d snapshot(s).", len(toDelete))
|
||||||
v.printlnStdout(
|
v.UI.Noticef("Run '%s' to clean up unreferenced remote blobs.",
|
||||||
"\nNote: Run 'vaultik prune' to clean up unreferenced remote blobs.")
|
pruneCommandHint)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -1086,7 +1078,7 @@ func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error {
|
|||||||
log.Info("Removing stale local snapshot record", "snapshot_id", id)
|
log.Info("Removing stale local snapshot record", "snapshot_id", id)
|
||||||
|
|
||||||
if !opts.JSON {
|
if !opts.JSON {
|
||||||
v.stdoutf("Removing stale local record: %s\n", id)
|
v.UI.Infof("Removing stale local record: %s.", v.UI.Snapshot(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
err = v.deleteSnapshotFromLocalDB(id)
|
err = v.deleteSnapshotFromLocalDB(id)
|
||||||
@@ -1109,9 +1101,9 @@ func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if removed == 0 {
|
if removed == 0 {
|
||||||
v.printlnStdout("No stale local snapshots found.")
|
v.UI.Infof("No stale local snapshots found.")
|
||||||
} else {
|
} else {
|
||||||
v.stdoutf("Removed %d stale local snapshot record(s).\n", removed)
|
v.UI.Infof("Removed %d stale local snapshot record(s).", removed)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -1260,18 +1252,10 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
return v.removeSnapshotDryRun(result, snapshotID, opts)
|
return v.removeSnapshotDryRun(result, snapshotID, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !v.confirmRemoveSnapshot(snapshotID, opts) {
|
if !opts.Force && !opts.JSON && !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)
|
||||||
|
|
||||||
@@ -1282,7 +1266,7 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
result.RemoteRemoved = v.removeSnapshotRemote(snapshotID, markerErr, opts)
|
result.RemoteRemoved = v.removeSnapshotRemote(snapshotID, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.SnapshotManager != nil {
|
if v.SnapshotManager != nil {
|
||||||
@@ -1298,14 +1282,15 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if inLocalIndex {
|
if inLocalIndex {
|
||||||
v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID)
|
v.UI.Infof("Removed snapshot '%s' from local database.",
|
||||||
|
v.UI.Snapshot(snapshotID))
|
||||||
}
|
}
|
||||||
|
|
||||||
if result.RemoteRemoved {
|
if result.RemoteRemoved {
|
||||||
v.printlnStdout("Removed snapshot metadata from remote storage")
|
v.UI.Infof("Removed snapshot metadata from remote storage.")
|
||||||
v.stdoutf("\nNote: The removed snapshot's blobs remain on the remote. "+
|
v.UI.Noticef("The removed snapshot's blobs remain on the remote. "+
|
||||||
"Run '%s' to delete any blobs no longer referenced by any "+
|
"Run '%s' to delete any blobs no longer referenced by any "+
|
||||||
"remaining remote snapshot.\n", pruneCommandHint)
|
"remaining remote snapshot.", pruneCommandHint)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
@@ -1361,26 +1346,24 @@ func (v *Vaultik) removeSnapshotDryRun(
|
|||||||
return result, v.outputRemoveJSON(result)
|
return result, v.outputRemoveJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.stdoutf("Would remove snapshot: %s\n", snapshotID)
|
v.UI.Infof("Would remove snapshot: %s.", v.UI.Snapshot(snapshotID))
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
v.printlnStdout("Would also remove snapshot metadata from " +
|
v.UI.Infof("Would also remove snapshot metadata from " +
|
||||||
"remote storage (blobs untouched)")
|
"remote storage (blobs untouched).")
|
||||||
}
|
}
|
||||||
|
|
||||||
v.printlnStdout("[Dry run - no changes made]")
|
v.UI.Noticef("Dry run: no changes made.")
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// confirmRemoveSnapshot prompts for confirmation before removing a
|
// confirmRemoveSnapshot prompts for confirmation before removing a
|
||||||
// snapshot, unless --force or --json is set. Returns false (treating
|
// snapshot. Returns false (treating EOF/read errors as "no") unless the
|
||||||
// EOF/read errors as "no") unless the user answers "y".
|
// user answers "y". The prompt and its answer bypass the UI: they are an
|
||||||
|
// interactive exchange the operator must see, so --quiet does not
|
||||||
|
// silence them.
|
||||||
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)
|
||||||
@@ -1412,24 +1395,15 @@ 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). markerErr is the result of
|
// removes snapshot metadata). Returns true when the remote removal
|
||||||
// checkDestinationMarker; when it is set, nothing is deleted and it is
|
// succeeded and deleted something.
|
||||||
// the failure reported. Returns true when the remote removal succeeded
|
func (v *Vaultik) removeSnapshotRemote(snapshotID string, opts *RemoveOptions) bool {
|
||||||
// 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)
|
||||||
|
|
||||||
var deleted int
|
remoteKey := snapshot.RemoteSnapshotKey(snapshotID)
|
||||||
|
|
||||||
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 "+
|
||||||
@@ -1494,7 +1468,7 @@ func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error)
|
|||||||
|
|
||||||
if len(localSnaps) == 0 && len(orphanRemoteKeys) == 0 {
|
if len(localSnaps) == 0 && len(orphanRemoteKeys) == 0 {
|
||||||
if !opts.JSON {
|
if !opts.JSON {
|
||||||
v.printlnStdout("No snapshots found")
|
v.UI.Infof("No snapshots found.")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &RemoveResult{}, nil
|
return &RemoveResult{}, nil
|
||||||
@@ -1533,8 +1507,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, or is not present by checkDestinationMarker; callers must
|
// listed; callers must treat that as "no remote info available," not
|
||||||
// treat that as "no remote info available," not fatal.
|
// 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")
|
||||||
|
|
||||||
@@ -1583,11 +1557,6 @@ func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := v.checkDestinationMarker()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return keys, nil
|
return keys, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1604,27 +1573,27 @@ func (v *Vaultik) handleRemoveAllDryRun(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !opts.JSON {
|
if !opts.JSON {
|
||||||
v.stdoutf("Would remove %d local snapshot(s):\n", len(localSnaps))
|
v.UI.Infof("Would remove %d local snapshot(s):", len(localSnaps))
|
||||||
|
|
||||||
for _, id := range localSnaps {
|
for _, id := range localSnaps {
|
||||||
v.stdoutf(" %s\n", id)
|
v.UI.Detailf("%s", v.UI.Snapshot(id))
|
||||||
}
|
}
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
if len(orphanRemoteKeys) > 0 {
|
if len(orphanRemoteKeys) > 0 {
|
||||||
v.stdoutf("Would also remove %d orphan remote snapshot key(s):\n",
|
v.UI.Infof("Would also remove %d orphan remote snapshot key(s):",
|
||||||
len(orphanRemoteKeys))
|
len(orphanRemoteKeys))
|
||||||
|
|
||||||
for _, key := range orphanRemoteKeys {
|
for _, key := range orphanRemoteKeys {
|
||||||
v.stdoutf(" %s\n", key)
|
v.UI.Detailf("%s", key)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
v.printlnStdout("Would also remove snapshot metadata from " +
|
v.UI.Infof("Would also remove snapshot metadata from " +
|
||||||
"remote storage (blobs untouched)")
|
"remote storage (blobs untouched).")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
v.printlnStdout("[Dry run - no changes made]")
|
v.UI.Noticef("Dry run: no changes made.")
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.JSON {
|
if opts.JSON {
|
||||||
@@ -1673,10 +1642,10 @@ func (v *Vaultik) executeRemoveAll(
|
|||||||
return result, v.outputRemoveJSON(result)
|
return result, v.outputRemoveJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.stdoutf("Removed %d snapshot(s)\n", len(result.SnapshotsRemoved))
|
v.UI.Infof("Removed %d snapshot(s).", len(result.SnapshotsRemoved))
|
||||||
|
|
||||||
if !opts.LocalOnly && result.RemoteRemoved {
|
if !opts.LocalOnly && result.RemoteRemoved {
|
||||||
v.printlnStdout("Removed snapshot metadata from remote storage")
|
v.UI.Infof("Removed snapshot metadata from remote storage.")
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ func TestSnapshotSummaryCountsFileNotStoredAsFailed(t *testing.T) {
|
|||||||
"src": {Paths: []string{srcDir}},
|
"src": {Paths: []string{srcDir}},
|
||||||
}
|
}
|
||||||
|
|
||||||
store, err := storage.NewFileStorer(t.TempDir())
|
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
db, err := database.New(ctx, cfg.IndexPath)
|
db, err := database.New(ctx, cfg.IndexPath)
|
||||||
|
|||||||
@@ -122,9 +122,6 @@ 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(t.TempDir())
|
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
||||||
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(t.TempDir())
|
inner, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
||||||
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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
restoreDir := filepath.Join(tempDir, "restored")
|
restoreDir := filepath.Join(tempDir, "restored")
|
||||||
dbPath := filepath.Join(tempDir, "index.sqlite")
|
dbPath := filepath.Join(tempDir, "index.sqlite")
|
||||||
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ func TestUncompressedSizeOfChangedFileStaysFixed(t *testing.T) {
|
|||||||
|
|
||||||
appendRandomBytes(t, fs, files, changedPath, appendedFileSize)
|
appendRandomBytes(t, fs, files, changedPath, appendedFileSize)
|
||||||
|
|
||||||
store, err := storage.NewFileStorer(t.TempDir())
|
store, err := storage.NewFileStorer(filepath.Join(tempDir, "remote"))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
db, err := database.New(ctx, dbPath)
|
db, err := database.New(ctx, dbPath)
|
||||||
|
|||||||
@@ -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 := t.TempDir()
|
storeDir := filepath.Join(tempDir, "remote")
|
||||||
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