Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c4af6d0df |
@@ -271,17 +271,8 @@ existing file. Created with mode `0600` since it will contain credentials.
|
|||||||
**`config set`**: Set a scalar config value by dotted YAML path
|
**`config set`**: Set a scalar config value by dotted YAML path
|
||||||
(e.g. `vaultik config set compression_level 9`,
|
(e.g. `vaultik config set compression_level 9`,
|
||||||
`vaultik config set storage_url "file:///mnt/backups"`). Comments and
|
`vaultik config set storage_url "file:///mnt/backups"`). Comments and
|
||||||
formatting in the file are preserved. Missing keys along the path are
|
formatting in the file are preserved; intermediate maps are created as
|
||||||
created: as a list when the next path element is a number (so
|
needed.
|
||||||
`vaultik config set age_recipients.0 age1...` works on a file without
|
|
||||||
`age_recipients`), otherwise as a map. If the config loads, a change
|
|
||||||
after which it would not, such as `vaultik config set compression_level 99`,
|
|
||||||
is refused and the file is left unchanged. A config that does not load,
|
|
||||||
such as the one `config init` writes before `storage_url` is set or one
|
|
||||||
with a `${ENV:...}` reference to a variable not set in this shell, is
|
|
||||||
checked one setting at a time: only a change after which the changed
|
|
||||||
setting cannot be read, such as one giving it the wrong type (a single
|
|
||||||
value where a list belongs or a word where a number belongs), is refused.
|
|
||||||
|
|
||||||
**`snapshot create`**: Perform incremental backup of configured snapshots.
|
**`snapshot create`**: Perform incremental backup of configured snapshots.
|
||||||
* Optional snapshot names argument to create specific snapshots (default: all)
|
* Optional snapshot names argument to create specific snapshots (default: all)
|
||||||
@@ -348,7 +339,9 @@ local index alone, and still exits zero.
|
|||||||
|
|
||||||
**`snapshot purge`**: Remove old snapshots based on criteria. Retention is
|
**`snapshot purge`**: Remove old snapshots based on criteria. Retention is
|
||||||
per-snapshot-name (`--keep-latest` keeps the latest of each name, not the
|
per-snapshot-name (`--keep-latest` keeps the latest of each name, not the
|
||||||
latest globally).
|
latest globally). If a snapshot cannot be removed from the local index, the
|
||||||
|
command stops there, leaves that snapshot's metadata on the destination store
|
||||||
|
and exits non-zero; `snapshot create --prune` fails the same way.
|
||||||
* `--keep-latest`: Keep only the most recent snapshot of each name
|
* `--keep-latest`: Keep only the most recent snapshot of each name
|
||||||
* `--older-than <duration>`: Remove snapshots older than duration (e.g. `30d`,
|
* `--older-than <duration>`: Remove snapshots older than duration (e.g. `30d`,
|
||||||
`4w`, `6mo`, `1y`; `m` is minutes, `mo` is months)
|
`4w`, `6mo`, `1y`; `m` is minutes, `mo` is months)
|
||||||
@@ -422,12 +415,11 @@ under `blobs/` whose name is not a blob hash is not counted as a blob,
|
|||||||
since `prune` never deletes it.
|
since `prune` never deletes it.
|
||||||
* `--json`: Output as JSON
|
* `--json`: Output as JSON
|
||||||
|
|
||||||
**`remote nuke`**: Delete every object under `metadata/` and `blobs/` on
|
**`remote nuke`**: Delete every snapshot's metadata and every blob from the
|
||||||
the backup destination store, whatever its name, leaving the bucket prefix
|
backup destination store, leaving the bucket prefix empty. Destructive and
|
||||||
empty. Destructive and irreversible. This is the single supported way to
|
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 anything cannot be deleted, the command exits
|
||||||
anything there, the command names each object left and exits non-zero;
|
non-zero; running it again deletes what is left.
|
||||||
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
|
||||||
@@ -710,10 +702,8 @@ 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
|
||||||
confirmation prompts of `database delete`, `prune`, `snapshot purge`
|
`database delete` confirmation prompt is also written this way and
|
||||||
and `snapshot remove`, each with what it asks to delete, are also
|
always shown: it is an interactive exchange the operator must see.
|
||||||
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
|
||||||
|
|||||||
+25
-120
@@ -8,7 +8,6 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
"slices"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
@@ -45,9 +44,6 @@ var (
|
|||||||
errNeedNumericIndex = errors.New("key is a list; use a numeric index")
|
errNeedNumericIndex = errors.New("key is a list; use a numeric index")
|
||||||
errIndexOutOfRange = errors.New("index out of range")
|
errIndexOutOfRange = errors.New("index out of range")
|
||||||
errNotMapOrList = errors.New("key is not a map or list")
|
errNotMapOrList = errors.New("key is not a map or list")
|
||||||
errWouldNotLoad = errors.New(
|
|
||||||
"vaultik would not load the config after this change, " +
|
|
||||||
"so the file was not changed")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultConfigTemplate = `# vaultik configuration
|
const defaultConfigTemplate = `# vaultik configuration
|
||||||
@@ -395,17 +391,8 @@ func newConfigSetCommand() *cobra.Command {
|
|||||||
Use: "set <key> <value>",
|
Use: "set <key> <value>",
|
||||||
Short: "Set a config value by dotted path (e.g. compression_level 5)",
|
Short: "Set a config value by dotted path (e.g. compression_level 5)",
|
||||||
Long: `Sets a scalar config value addressed by dotted YAML path and writes
|
Long: `Sets a scalar config value addressed by dotted YAML path and writes
|
||||||
the file back, preserving comments and formatting. Missing keys along
|
the file back, preserving comments and formatting. Intermediate maps
|
||||||
the path are created: as a list when the next path element is a
|
are created as needed.
|
||||||
number, otherwise as a map.
|
|
||||||
|
|
||||||
If the config loads, a change after which it would not, such as
|
|
||||||
compression_level 99, is refused and the file is left unchanged. A
|
|
||||||
config that does not load, such as the one config init writes before
|
|
||||||
storage_url is set or one with a ${ENV:...} reference to a variable
|
|
||||||
not set here, is checked one setting at a time: only a change after
|
|
||||||
which the changed setting cannot be read, such as one giving it the
|
|
||||||
wrong type, is refused.
|
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
vaultik config set storage_url "file:///mnt/backups"
|
vaultik config set storage_url "file:///mnt/backups"
|
||||||
@@ -435,14 +422,7 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
oldData, err := marshalConfigYAML(root)
|
err = yamlPathSet(root, strings.Split(key, "."), value)
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("marshaling config: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
keys := strings.Split(key, ".")
|
|
||||||
|
|
||||||
err = yamlPathSet(root, keys, value)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -452,21 +432,6 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error {
|
|||||||
return fmt.Errorf("marshaling config: %w", err)
|
return fmt.Errorf("marshaling config: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
setting, err := yamlPathOnly(root, keys)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
settingData, err := marshalConfigYAML(setting)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("marshaling config: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = checkConfigChange(oldData, data, settingData)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("%w: %w", errWouldNotLoad, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = os.WriteFile(path, data, configFileMode)
|
err = os.WriteFile(path, data, configFileMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("writing config file: %w", err)
|
return fmt.Errorf("writing config file: %w", err)
|
||||||
@@ -488,58 +453,6 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// checkConfigChange returns the reason vaultik would not load newData, the
|
|
||||||
// config after a change, if the change brings that failure in. If oldData,
|
|
||||||
// the config before it, loads, the new one must load too. A config that
|
|
||||||
// does not load, such as one still being filled in or one with a ${...}
|
|
||||||
// reference that cannot be filled in here, is checked one setting at a
|
|
||||||
// time: settingData, the changed setting on its own, must decode into the
|
|
||||||
// config type.
|
|
||||||
func checkConfigChange(oldData, newData, settingData []byte) error {
|
|
||||||
oldCfg, err := config.Parse(oldData)
|
|
||||||
if err == nil && oldCfg.Validate() == nil {
|
|
||||||
newCfg, err := config.Parse(newData)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return newCfg.Validate()
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = config.Parse(settingData)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// yamlPathOnly returns a document holding only the value at the dotted key
|
|
||||||
// path in root, inside the maps and lists that lead to it there.
|
|
||||||
func yamlPathOnly(root *yaml.Node, keys []string) (*yaml.Node, error) {
|
|
||||||
node, err := yamlPathGet(root, keys)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, key := range slices.Backward(keys) {
|
|
||||||
parent, err := yamlPathGet(root, keys[:i])
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if parent.Kind == yaml.SequenceNode {
|
|
||||||
node = &yaml.Node{
|
|
||||||
Kind: yaml.SequenceNode, Content: []*yaml.Node{node},
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key}
|
|
||||||
node = &yaml.Node{
|
|
||||||
Kind: yaml.MappingNode, Content: []*yaml.Node{keyNode, node},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{node}}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// marshalConfigYAML renders a config document tree with 2-space indentation,
|
// marshalConfigYAML renders a config document tree with 2-space indentation,
|
||||||
// matching defaultConfigTemplate. yaml.Marshal defaults to 4 spaces, which
|
// matching defaultConfigTemplate. yaml.Marshal defaults to 4 spaces, which
|
||||||
// would reindent the whole file on the first `config set` despite the promise
|
// would reindent the whole file on the first `config set` despite the promise
|
||||||
@@ -646,8 +559,8 @@ func yamlPathGet(root *yaml.Node, keys []string) (*yaml.Node, error) {
|
|||||||
return node, nil
|
return node, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// yamlPathSet navigates a dotted key path, creating missing keys as needed,
|
// yamlPathSet navigates a dotted key path, creating intermediate maps as
|
||||||
// and sets the final key to the given scalar value. Numeric path
|
// needed, and sets the final key to the given scalar value. Numeric path
|
||||||
// components index into sequences; an index equal to the sequence length
|
// components index into sequences; an index equal to the sequence length
|
||||||
// appends a new element (e.g. "age_recipients.1" on a 1-element list).
|
// appends a new element (e.g. "age_recipients.1" on a 1-element list).
|
||||||
func yamlPathSet(root *yaml.Node, keys []string, value string) error {
|
func yamlPathSet(root *yaml.Node, keys []string, value string) error {
|
||||||
@@ -660,12 +573,12 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error {
|
|||||||
node = node.Content[0]
|
node = node.Content[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := range keys {
|
for i, key := range keys {
|
||||||
last := i == len(keys)-1
|
last := i == len(keys)-1
|
||||||
|
|
||||||
switch node.Kind {
|
switch node.Kind {
|
||||||
case yaml.MappingNode:
|
case yaml.MappingNode:
|
||||||
node = yamlSetInMapping(node, keys, i, value, last)
|
node = yamlSetInMapping(node, key, value, last)
|
||||||
case yaml.SequenceNode:
|
case yaml.SequenceNode:
|
||||||
next, err := yamlSetInSequence(node, keys, i, value, last)
|
next, err := yamlSetInSequence(node, keys, i, value, last)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -734,16 +647,14 @@ func yamlField(typ reflect.Type, key string) (reflect.StructField, bool) {
|
|||||||
return reflect.StructField{}, false
|
return reflect.StructField{}, false
|
||||||
}
|
}
|
||||||
|
|
||||||
// yamlSetInMapping resolves (creating if needed) the value node for the
|
// yamlSetInMapping resolves (creating if needed) the value node for key
|
||||||
// path element keys[i] within a mapping node, setting it to value when it
|
// within a mapping node, setting it to value when it is the final path
|
||||||
// is the final path element, and returns the node to descend into.
|
// element, and returns the node to descend into.
|
||||||
func yamlSetInMapping(
|
func yamlSetInMapping(node *yaml.Node, key, value string, last bool) *yaml.Node {
|
||||||
node *yaml.Node, keys []string, i int, value string, last bool,
|
|
||||||
) *yaml.Node {
|
|
||||||
var valueNode *yaml.Node
|
var valueNode *yaml.Node
|
||||||
|
|
||||||
for j := 0; j+1 < len(node.Content); j += 2 {
|
for j := 0; j+1 < len(node.Content); j += 2 {
|
||||||
if node.Content[j].Value == keys[i] {
|
if node.Content[j].Value == key {
|
||||||
valueNode = node.Content[j+1]
|
valueNode = node.Content[j+1]
|
||||||
|
|
||||||
break
|
break
|
||||||
@@ -751,8 +662,13 @@ func yamlSetInMapping(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if valueNode == nil {
|
if valueNode == nil {
|
||||||
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: keys[i]}
|
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key}
|
||||||
valueNode = newPathNode(keys, i, value)
|
|
||||||
|
valueNode = &yaml.Node{Kind: yaml.MappingNode}
|
||||||
|
if last {
|
||||||
|
valueNode = &yaml.Node{Kind: yaml.ScalarNode, Value: value}
|
||||||
|
}
|
||||||
|
|
||||||
node.Content = append(node.Content, keyNode, valueNode)
|
node.Content = append(node.Content, keyNode, valueNode)
|
||||||
} else if last {
|
} else if last {
|
||||||
setScalar(valueNode, value)
|
setScalar(valueNode, value)
|
||||||
@@ -780,7 +696,12 @@ func yamlSetInSequence(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if idx == len(node.Content) {
|
if idx == len(node.Content) {
|
||||||
node.Content = append(node.Content, newPathNode(keys, i, value))
|
newNode := &yaml.Node{Kind: yaml.MappingNode}
|
||||||
|
if last {
|
||||||
|
newNode = &yaml.Node{Kind: yaml.ScalarNode, Value: value}
|
||||||
|
}
|
||||||
|
|
||||||
|
node.Content = append(node.Content, newNode)
|
||||||
} else if last {
|
} else if last {
|
||||||
setScalar(node.Content[idx], value)
|
setScalar(node.Content[idx], value)
|
||||||
}
|
}
|
||||||
@@ -788,22 +709,6 @@ func yamlSetInSequence(
|
|||||||
return node.Content[idx], nil
|
return node.Content[idx], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// newPathNode returns the node to create for the missing path element
|
|
||||||
// keys[i]: the value when it is the final path element, otherwise an empty
|
|
||||||
// list when the next path element is a number and an empty map when not.
|
|
||||||
func newPathNode(keys []string, i int, value string) *yaml.Node {
|
|
||||||
if i == len(keys)-1 {
|
|
||||||
return &yaml.Node{Kind: yaml.ScalarNode, Value: value}
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := strconv.Atoi(keys[i+1])
|
|
||||||
if err == nil {
|
|
||||||
return &yaml.Node{Kind: yaml.SequenceNode}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &yaml.Node{Kind: yaml.MappingNode}
|
|
||||||
}
|
|
||||||
|
|
||||||
// setScalar overwrites a node in place with a plain scalar value.
|
// setScalar overwrites a node in place with a plain scalar value.
|
||||||
func setScalar(n *yaml.Node, value string) {
|
func setScalar(n *yaml.Node, value string) {
|
||||||
n.Kind = yaml.ScalarNode
|
n.Kind = yaml.ScalarNode
|
||||||
|
|||||||
+5
-211
@@ -58,17 +58,14 @@ func TestDefaultConfigTemplateParses(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// testRecipient is a valid age public key.
|
|
||||||
const testRecipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj"
|
|
||||||
|
|
||||||
// TestConfigSetRecipientOnFreshConfig follows the README quickstart: on the
|
// TestConfigSetRecipientOnFreshConfig follows the README quickstart: on the
|
||||||
// file `config init` writes, `config set age_recipients.0` and
|
// file `config init` writes, `config set age_recipients.0` and
|
||||||
// `config set storage_url` give a config that loads with that recipient.
|
// `config set storage_url` give a config that loads with that recipient.
|
||||||
// Neither is refused, although the config does not load until both are set;
|
|
||||||
// once it loads, a recipient that is not a valid key is.
|
|
||||||
func TestConfigSetRecipientOnFreshConfig(t *testing.T) {
|
func TestConfigSetRecipientOnFreshConfig(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
const recipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj"
|
||||||
|
|
||||||
path := filepath.Join(t.TempDir(), "config.yml")
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
err := os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode)
|
err := os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode)
|
||||||
@@ -78,7 +75,7 @@ func TestConfigSetRecipientOnFreshConfig(t *testing.T) {
|
|||||||
|
|
||||||
out := ui.NewWithColor(&bytes.Buffer{}, false)
|
out := ui.NewWithColor(&bytes.Buffer{}, false)
|
||||||
|
|
||||||
err = writeConfigSet(out, path, "age_recipients.0", testRecipient)
|
err = writeConfigSet(out, path, "age_recipients.0", recipient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("config set age_recipients.0: %v", err)
|
t.Fatalf("config set age_recipients.0: %v", err)
|
||||||
}
|
}
|
||||||
@@ -93,211 +90,8 @@ func TestConfigSetRecipientOnFreshConfig(t *testing.T) {
|
|||||||
t.Fatalf("config.Load: %v", err)
|
t.Fatalf("config.Load: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(cfg.AgeRecipients) != 1 || cfg.AgeRecipients[0] != testRecipient {
|
if len(cfg.AgeRecipients) != 1 || cfg.AgeRecipients[0] != recipient {
|
||||||
t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, testRecipient)
|
t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, recipient)
|
||||||
}
|
|
||||||
|
|
||||||
err = writeConfigSet(out, path, "age_recipients.0", "notakey")
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "not a valid recipient") {
|
|
||||||
t.Errorf("config set age_recipients.0 notakey gives error %v, "+
|
|
||||||
"want one saying it is not a valid recipient", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = config.Load(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("config.Load after the refused change: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// configWithoutRecipients loads, but has no age_recipients key and no
|
|
||||||
// snapshot named work.
|
|
||||||
const configWithoutRecipients = `storage_url: file:///mnt/backups
|
|
||||||
snapshots:
|
|
||||||
home:
|
|
||||||
paths:
|
|
||||||
- "~"
|
|
||||||
`
|
|
||||||
|
|
||||||
// configWithUnsetReference loads only where VAULTIK_TEST_UNSET_SECRET is
|
|
||||||
// set, as a backup job's environment might set it. No test sets it.
|
|
||||||
const configWithUnsetReference = configWithoutRecipients + `s3:
|
|
||||||
secret_access_key: ${ENV:VAULTIK_TEST_UNSET_SECRET}
|
|
||||||
`
|
|
||||||
|
|
||||||
// configWithLevelReference returns configWithoutRecipients with a ${FILE:...}
|
|
||||||
// reference on compression_level to a file holding 9, so that the config
|
|
||||||
// loads once the reference is filled in.
|
|
||||||
func configWithLevelReference(t *testing.T) string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
levelPath := filepath.Join(t.TempDir(), "level")
|
|
||||||
|
|
||||||
err := os.WriteFile(levelPath, []byte("9"), configFileMode)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("write level: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return configWithoutRecipients +
|
|
||||||
"compression_level: ${FILE:" + levelPath + "}\n"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestConfigSetIndexUnderMissingKey checks that a list index under a key
|
|
||||||
// the file does not have creates a list, and that the result loads.
|
|
||||||
func TestConfigSetIndexUnderMissingKey(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
key string
|
|
||||||
value string
|
|
||||||
field func(cfg *config.Config) []string
|
|
||||||
}{
|
|
||||||
{"age_recipients.0", testRecipient,
|
|
||||||
func(cfg *config.Config) []string { return cfg.AgeRecipients }},
|
|
||||||
{"snapshots.work.paths.0", "/srv/work",
|
|
||||||
func(cfg *config.Config) []string { return cfg.Snapshots["work"].Paths }},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.key, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
path := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
|
|
||||||
err := os.WriteFile(path, []byte(configWithoutRecipients), configFileMode)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("write config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false),
|
|
||||||
path, tt.key, tt.value)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("config set %s: %v", tt.key, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg, err := config.Load(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("config.Load: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
got := tt.field(cfg)
|
|
||||||
if len(got) != 1 || got[0] != tt.value {
|
|
||||||
t.Errorf("%s gives %v, want [%s]", tt.key, got, tt.value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestConfigSetKeepsFileThatWouldNotLoad checks that config set refuses a
|
|
||||||
// change after which the config would not load, with an error giving the
|
|
||||||
// reason, and leaves the file as it was. On the file `config init` writes,
|
|
||||||
// which does not load until storage_url is set, and on one that cannot be
|
|
||||||
// read here, only a value of the wrong type is refused.
|
|
||||||
func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
levelReference := configWithLevelReference(t)
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
config string
|
|
||||||
key string
|
|
||||||
value string
|
|
||||||
reason string
|
|
||||||
}{
|
|
||||||
// Index 1 of the empty list the missing key gives.
|
|
||||||
{configWithoutRecipients, "age_recipients.1", testRecipient,
|
|
||||||
"index out of range"},
|
|
||||||
// A list set to a single value.
|
|
||||||
{configWithoutRecipients, "snapshots.home.paths", "/srv",
|
|
||||||
"into []string"},
|
|
||||||
{configWithoutRecipients, "chunk_size", "fast",
|
|
||||||
"invalid size format"},
|
|
||||||
// Values of the right type that fail validation.
|
|
||||||
{configWithoutRecipients, "compression_level", "99",
|
|
||||||
"compression_level must be between 1 and 19"},
|
|
||||||
{configWithoutRecipients, "chunk_size", "1KB",
|
|
||||||
"chunk_size must be at least 1MB"},
|
|
||||||
// With its reference filled in, the config loads.
|
|
||||||
{levelReference, "blob_size_limit", "1MB",
|
|
||||||
"blob_size_limit must be at least"},
|
|
||||||
// The type check on a config that does not load yet.
|
|
||||||
{defaultConfigTemplate, "snapshots.apps.paths", "/srv",
|
|
||||||
"into []string"},
|
|
||||||
// The type check on a config that cannot be read here.
|
|
||||||
{configWithUnsetReference, "snapshots.home.paths", "/x",
|
|
||||||
"cannot unmarshal !!str `/x`"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.key+" "+tt.value, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
path := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
|
|
||||||
err := os.WriteFile(path, []byte(tt.config), configFileMode)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("write config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false),
|
|
||||||
path, tt.key, tt.value)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), tt.reason) {
|
|
||||||
t.Errorf("config set %s %s gives error %v, want one saying %q",
|
|
||||||
tt.key, tt.value, err, tt.reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if string(data) != tt.config {
|
|
||||||
t.Errorf("config set %s changed the file to:\n%s",
|
|
||||||
tt.key, data)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestConfigSetRefusesOnlyItsOwnFailure checks that setting another key
|
|
||||||
// works on a config with a ${...} reference on compression_level, which
|
|
||||||
// loads because loading fills the reference in, on one whose
|
|
||||||
// compression_level already fails to load, and on one with a reference
|
|
||||||
// that cannot be filled in here.
|
|
||||||
func TestConfigSetRefusesOnlyItsOwnFailure(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
configs := map[string]string{
|
|
||||||
"reference": configWithLevelReference(t),
|
|
||||||
"failing": configWithoutRecipients + "compression_level: fast\n",
|
|
||||||
"unset reference": configWithUnsetReference,
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, configYAML := range configs {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
path := filepath.Join(t.TempDir(), "config.yml")
|
|
||||||
|
|
||||||
err := os.WriteFile(path, []byte(configYAML), configFileMode)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("write config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false),
|
|
||||||
path, "hostname", "myhost")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("config set hostname: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read config: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.Contains(string(data), "hostname: myhost") {
|
|
||||||
t.Errorf("config set hostname wrote:\n%s", data)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,126 +0,0 @@
|
|||||||
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Flags used to build the argument vectors below.
|
|
||||||
const (
|
|
||||||
flagCron = "--cron"
|
|
||||||
flagForce = "--force"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 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")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
|
"sneak.berlin/go/vaultik/internal/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The `snapshot purge` command word and flags used below.
|
||||||
|
const (
|
||||||
|
cmdPurge = "purge"
|
||||||
|
flagKeepLatest = "--keep-latest"
|
||||||
|
flagForce = "--force"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails makes
|
||||||
|
// removing a snapshot from the local index fail and checks that
|
||||||
|
// `snapshot purge` exits non-zero and leaves that snapshot's metadata on
|
||||||
|
// the destination store. It used to log the error, delete the metadata
|
||||||
|
// anyway and exit 0.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
configPath := writeHermeticPruneConfig(t, false)
|
||||||
|
|
||||||
|
// writeHermeticPruneConfig puts the index and the store directory
|
||||||
|
// beside the config file.
|
||||||
|
dir := filepath.Dir(configPath)
|
||||||
|
|
||||||
|
// Two snapshots of the same name: --keep-latest purges the older.
|
||||||
|
olderStart := time.Date(2026, 5, 1, 9, 0, 0, 0, time.UTC)
|
||||||
|
newerStart := olderStart.Add(time.Hour)
|
||||||
|
olderID := "test-host_test_" + olderStart.Format(time.RFC3339)
|
||||||
|
newerID := "test-host_test_" + newerStart.Format(time.RFC3339)
|
||||||
|
|
||||||
|
db, err := database.New(ctx, filepath.Join(dir, "index.sqlite"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
manifestPaths := make(map[string]string)
|
||||||
|
|
||||||
|
for id, startedAt := range map[string]time.Time{
|
||||||
|
olderID: olderStart,
|
||||||
|
newerID: newerStart,
|
||||||
|
} {
|
||||||
|
completedAt := startedAt.Add(time.Minute)
|
||||||
|
snap := &database.Snapshot{
|
||||||
|
ID: types.SnapshotID(id),
|
||||||
|
Hostname: "test-host",
|
||||||
|
VaultikVersion: "test",
|
||||||
|
StartedAt: startedAt,
|
||||||
|
CompletedAt: &completedAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
err = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
return repos.Snapshots.Create(ctx, tx, snap)
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
manifestPaths[id] = filepath.Join(dir, "store", "metadata",
|
||||||
|
snapshot.RemoteSnapshotKey(id), "manifest.json.zst")
|
||||||
|
require.NoError(t, os.MkdirAll(filepath.Dir(manifestPaths[id]), 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(manifestPaths[id], []byte("stub"), 0o600))
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = db.Conn().ExecContext(ctx, `
|
||||||
|
CREATE TRIGGER refuse_snapshot_delete BEFORE DELETE ON snapshots
|
||||||
|
BEGIN SELECT RAISE(ABORT, 'simulated index error'); END`)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, db.Close())
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdPurge, flagKeepLatest, flagForce)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Contains(t, stderr, "simulated index error")
|
||||||
|
assert.FileExists(t, manifestPaths[olderID],
|
||||||
|
"a snapshot still in the local index keeps its metadata")
|
||||||
|
}
|
||||||
+24
-41
@@ -4,7 +4,6 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
@@ -234,48 +233,14 @@ func New(path Path) (*Config, error) {
|
|||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load reads the configuration file at path, parses it with Parse, warns
|
// Load reads and parses the configuration file from the specified path.
|
||||||
// when others can read the file, and validates the configuration.
|
// It applies default values for optional fields, performs environment variable
|
||||||
// Returns an error if the file cannot be read, parsed, or if validation
|
// substitution using smartconfig, and validates the configuration.
|
||||||
// fails.
|
// The configuration file should be in YAML format. Returns an error if the file
|
||||||
|
// cannot be read, parsed, or if validation fails.
|
||||||
func Load(path string) (*Config, error) {
|
func Load(path string) (*Config, error) {
|
||||||
data, err := os.ReadFile(path) //nolint:gosec // G304: config path is operator-supplied
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to load config file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg, err := Parse(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check config file permissions (warn if world or group readable)
|
|
||||||
//nolint:gosec // G703: config path is operator-supplied by design
|
|
||||||
info, statErr := os.Stat(path)
|
|
||||||
if statErr == nil {
|
|
||||||
mode := info.Mode().Perm()
|
|
||||||
if mode&0044 != 0 { // group or world readable
|
|
||||||
log.Warn(cfg.readableByOthersWarning(),
|
|
||||||
"path", path,
|
|
||||||
"mode", fmt.Sprintf("%04o", mode),
|
|
||||||
"recommendation", "chmod 600 "+path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
err = cfg.Validate()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid config: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return cfg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse reads YAML config data as Load does, without validating it. It
|
|
||||||
// applies default values for optional fields, fills in ${...} references
|
|
||||||
// using smartconfig, and expands ~ in paths.
|
|
||||||
func Parse(data []byte) (*Config, error) {
|
|
||||||
// Load config using smartconfig for interpolation
|
// Load config using smartconfig for interpolation
|
||||||
sc, err := smartconfig.NewFromReader(bytes.NewReader(data))
|
sc, err := smartconfig.NewFromConfigPath(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to load config file: %w", err)
|
return nil, fmt.Errorf("failed to load config file: %w", err)
|
||||||
}
|
}
|
||||||
@@ -337,6 +302,24 @@ func Parse(data []byte) (*Config, error) {
|
|||||||
cfg.S3.Region = "us-east-1"
|
cfg.S3.Region = "us-east-1"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check config file permissions (warn if world or group readable)
|
||||||
|
//nolint:gosec // G703: config path is operator-supplied by design
|
||||||
|
info, statErr := os.Stat(path)
|
||||||
|
if statErr == nil {
|
||||||
|
mode := info.Mode().Perm()
|
||||||
|
if mode&0044 != 0 { // group or world readable
|
||||||
|
log.Warn(cfg.readableByOthersWarning(),
|
||||||
|
"path", path,
|
||||||
|
"mode", fmt.Sprintf("%04o", mode),
|
||||||
|
"recommendation", "chmod 600 "+path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err = cfg.Validate()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid config: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+13
-63
@@ -120,10 +120,9 @@ func (f *FileStorer) Delete(_ context.Context, key string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// List returns all keys with the given prefix, reading through symlinked
|
// List returns all keys with the given prefix. It fails when the
|
||||||
// directories. It fails when the destination directory is missing, or
|
// destination directory is missing; a missing prefix under it is an
|
||||||
// when the prefix or a directory above it is a symlink whose target is
|
// empty listing.
|
||||||
// missing; a prefix that is truly missing is an empty listing.
|
|
||||||
func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) {
|
func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) {
|
||||||
var keys []string
|
var keys []string
|
||||||
|
|
||||||
@@ -134,7 +133,8 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error)
|
|||||||
|
|
||||||
basePath := f.fullPath(prefix)
|
basePath := f.fullPath(prefix)
|
||||||
|
|
||||||
exists, err := f.prefixExists(prefix)
|
// Check if the prefix exists
|
||||||
|
exists, err := afero.Exists(f.fs, basePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("checking path: %w", err)
|
return nil, fmt.Errorf("checking path: %w", err)
|
||||||
}
|
}
|
||||||
@@ -143,7 +143,7 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error)
|
|||||||
return keys, nil // Empty list for non-existent prefix
|
return keys, nil // Empty list for non-existent prefix
|
||||||
}
|
}
|
||||||
|
|
||||||
err = f.walk(basePath, func(path string, info os.FileInfo, err error) error {
|
err = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -176,9 +176,7 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListStream returns a channel of ObjectInfo for large result sets. Like
|
// ListStream returns a channel of ObjectInfo for large result sets. Like
|
||||||
// List, it reads through symlinked directories and sends an error when
|
// List, it sends an error when the destination directory is missing.
|
||||||
// the destination directory is missing, or when the prefix or a directory
|
|
||||||
// above it is a symlink whose target is missing.
|
|
||||||
func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan ObjectInfo {
|
func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan ObjectInfo {
|
||||||
ch := make(chan ObjectInfo)
|
ch := make(chan ObjectInfo)
|
||||||
|
|
||||||
@@ -194,7 +192,8 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec
|
|||||||
|
|
||||||
basePath := f.fullPath(prefix)
|
basePath := f.fullPath(prefix)
|
||||||
|
|
||||||
exists, err := f.prefixExists(prefix)
|
// Check if the prefix exists
|
||||||
|
exists, err := afero.Exists(f.fs, basePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ch <- ObjectInfo{Err: fmt.Errorf("checking path: %w", err)}
|
ch <- ObjectInfo{Err: fmt.Errorf("checking path: %w", err)}
|
||||||
|
|
||||||
@@ -205,7 +204,7 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec
|
|||||||
return // Empty channel for non-existent prefix
|
return // Empty channel for non-existent prefix
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = f.walk(basePath, func(path string, info os.FileInfo, err error) error {
|
_ = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error {
|
||||||
// Check context cancellation
|
// Check context cancellation
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
@@ -244,12 +243,11 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DeletePartialUploads removes every file under prefix whose name ends in
|
// DeletePartialUploads removes every file under prefix whose name ends in
|
||||||
// tempSuffix. Like List, it reads through symlinked directories and fails
|
// tempSuffix. A missing prefix has none to remove.
|
||||||
// on one whose target is missing. A missing prefix has none to remove.
|
|
||||||
func (f *FileStorer) DeletePartialUploads(ctx context.Context, prefix string) error {
|
func (f *FileStorer) DeletePartialUploads(ctx context.Context, prefix string) error {
|
||||||
basePath := f.fullPath(prefix)
|
basePath := f.fullPath(prefix)
|
||||||
|
|
||||||
exists, err := f.prefixExists(prefix)
|
exists, err := afero.Exists(f.fs, basePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("checking path: %w", err)
|
return fmt.Errorf("checking path: %w", err)
|
||||||
}
|
}
|
||||||
@@ -258,7 +256,7 @@ func (f *FileStorer) DeletePartialUploads(ctx context.Context, prefix string) er
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
err = f.walk(basePath, func(path string, info os.FileInfo, err error) error {
|
err = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -354,54 +352,6 @@ func (f *FileStorer) writeAtomic(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// walk is afero.Walk, except that it reads through a symlinked directory
|
|
||||||
// the way Get and Stat do, where afero.Walk reports the link as one file.
|
|
||||||
// afero.Walk uses Lstat, which does not follow a link, whenever the
|
|
||||||
// filesystem has one; the struct below carries only the afero.Fs methods,
|
|
||||||
// so the walk uses Stat instead. A link back up the tree is followed until
|
|
||||||
// the operating system refuses the path for too many levels of links, and
|
|
||||||
// the walk then fails.
|
|
||||||
func (f *FileStorer) walk(root string, fn filepath.WalkFunc) error {
|
|
||||||
return afero.Walk(struct{ afero.Fs }{f.fs}, root, fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// prefixExists reports whether prefix exists under the destination
|
|
||||||
// directory. It checks each directory on the way down to prefix in turn,
|
|
||||||
// and the first one Stat cannot find decides: if it is not there at all,
|
|
||||||
// prefix is missing; if it is a symlink whose target is missing, such as
|
|
||||||
// a link to a volume that is not mounted, prefixExists fails, since
|
|
||||||
// listing it as empty would let prune delete every blob.
|
|
||||||
func (f *FileStorer) prefixExists(prefix string) (bool, error) {
|
|
||||||
lstater, canLstat := f.fs.(afero.Lstater)
|
|
||||||
path := f.basePath
|
|
||||||
|
|
||||||
for name := range strings.SplitSeq(prefix, "/") {
|
|
||||||
path = filepath.Join(path, name)
|
|
||||||
|
|
||||||
_, err := f.fs.Stat(path)
|
|
||||||
if err == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if !os.IsNotExist(err) {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lstat does not follow a symlink at path, so it finds the link
|
|
||||||
// that Stat could not follow.
|
|
||||||
if canLstat {
|
|
||||||
_, _, lstatErr := lstater.LstatIfPossible(path)
|
|
||||||
if lstatErr == nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// fullPath returns the full filesystem path for a key.
|
// fullPath returns the full filesystem path for a key.
|
||||||
func (f *FileStorer) fullPath(key string) string {
|
func (f *FileStorer) fullPath(key string) string {
|
||||||
return filepath.Join(f.basePath, key)
|
return filepath.Join(f.basePath, key)
|
||||||
|
|||||||
@@ -4,10 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"sneak.berlin/go/vaultik/internal/storage"
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
@@ -63,232 +60,3 @@ func TestFileStorerListMissingDestination(t *testing.T) {
|
|||||||
t.Errorf("ListStream error = %v, want a not-exist error", streamErr)
|
t.Errorf("ListStream error = %v, want a not-exist error", streamErr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The two directories at the top of a destination, either of which the
|
|
||||||
// tests below replace with a symlink.
|
|
||||||
const (
|
|
||||||
metadataDir = "metadata"
|
|
||||||
blobsDir = "blobs"
|
|
||||||
)
|
|
||||||
|
|
||||||
// moveBehindSymlink moves base/dir to a directory elsewhere and puts a
|
|
||||||
// symlink to it in its place.
|
|
||||||
func moveBehindSymlink(t *testing.T, base, dir string) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
linkPath := filepath.Join(base, dir)
|
|
||||||
movedPath := filepath.Join(t.TempDir(), dir)
|
|
||||||
|
|
||||||
err := os.Rename(linkPath, movedPath)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("moving %s away: %v", dir, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = os.Symlink(movedPath, linkPath)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("linking %s: %v", dir, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestFileStorerListsThroughSymlinkedDirectory checks that List and
|
|
||||||
// ListStream read through a symlinked metadata/ or blobs/ directory, as Get
|
|
||||||
// and Stat do, instead of listing the link as one key. Listing the whole
|
|
||||||
// destination meets the link part-way through the walk; listing its prefix
|
|
||||||
// starts the walk at the link. A prefix missing behind the link lists as
|
|
||||||
// empty.
|
|
||||||
func TestFileStorerListsThroughSymlinkedDirectory(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
for _, dir := range []string{metadataDir, blobsDir} {
|
|
||||||
t.Run(dir, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
base := t.TempDir()
|
|
||||||
key := dir + "/aa/bb/object"
|
|
||||||
|
|
||||||
s, err := storage.NewFileStorer(base)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewFileStorer: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = s.Put(context.Background(), key, strings.NewReader("data"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Put: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
moveBehindSymlink(t, base, dir)
|
|
||||||
|
|
||||||
want := []string{key}
|
|
||||||
|
|
||||||
for _, prefix := range []string{"", dir + "/"} {
|
|
||||||
got := listSorted(t, s, prefix)
|
|
||||||
if !reflect.DeepEqual(got, want) {
|
|
||||||
t.Errorf("List(%q) = %v, want %v", prefix, got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
got = listStreamKeys(t, s, prefix)
|
|
||||||
if !reflect.DeepEqual(got, want) {
|
|
||||||
t.Errorf("ListStream(%q) = %v, want %v", prefix, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
absent := dir + "/absent/"
|
|
||||||
|
|
||||||
if got := listSorted(t, s, absent); len(got) != 0 {
|
|
||||||
t.Errorf("List(%q) = %v, want empty", absent, got)
|
|
||||||
}
|
|
||||||
|
|
||||||
if got := listStreamKeys(t, s, absent); len(got) != 0 {
|
|
||||||
t.Errorf("ListStream(%q) = %v, want empty", absent, got)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestFileStorerListFailsOnSymlinkWithMissingTarget checks that List and
|
|
||||||
// ListStream fail on a symlinked metadata/ or blobs/ directory whose target
|
|
||||||
// is missing, such as a link to a volume that is not mounted, as they do on
|
|
||||||
// a missing destination directory, instead of listing it as empty. That
|
|
||||||
// holds for a prefix below the link too.
|
|
||||||
func TestFileStorerListFailsOnSymlinkWithMissingTarget(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
for _, dir := range []string{metadataDir, blobsDir} {
|
|
||||||
t.Run(dir, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
base := t.TempDir()
|
|
||||||
|
|
||||||
s, err := storage.NewFileStorer(base)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewFileStorer: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
unmounted := filepath.Join(t.TempDir(), "unmounted")
|
|
||||||
|
|
||||||
err = os.Symlink(unmounted, filepath.Join(base, dir))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Symlink: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, prefix := range []string{"", dir + "/", dir + "/aa/"} {
|
|
||||||
keys, err := s.List(ctx, prefix)
|
|
||||||
if !errors.Is(err, fs.ErrNotExist) {
|
|
||||||
t.Errorf("List(%q) = %v, %v; want a not-exist error",
|
|
||||||
prefix, keys, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var streamErr error
|
|
||||||
|
|
||||||
for object := range s.ListStream(ctx, prefix) {
|
|
||||||
if object.Err != nil {
|
|
||||||
streamErr = object.Err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !errors.Is(streamErr, fs.ErrNotExist) {
|
|
||||||
t.Errorf("ListStream(%q) error = %v, want a not-exist error",
|
|
||||||
prefix, streamErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestFileStorerListFailsOnSymlinkLoop checks that a symlink pointing back
|
|
||||||
// at the destination makes List and ListStream fail instead of walking it
|
|
||||||
// forever.
|
|
||||||
func TestFileStorerListFailsOnSymlinkLoop(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
base := t.TempDir()
|
|
||||||
|
|
||||||
s, err := storage.NewFileStorer(base)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewFileStorer: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = s.Put(ctx, testBlobKey, strings.NewReader("data"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Put: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = os.Symlink(base, filepath.Join(base, "blobs", "loop"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Symlink: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
keys, err := s.List(ctx, "blobs/")
|
|
||||||
if err == nil {
|
|
||||||
t.Errorf("List = %d keys and no error, want an error", len(keys))
|
|
||||||
}
|
|
||||||
|
|
||||||
var streamErr error
|
|
||||||
|
|
||||||
for object := range s.ListStream(ctx, "blobs/") {
|
|
||||||
if object.Err != nil {
|
|
||||||
streamErr = object.Err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if streamErr == nil {
|
|
||||||
t.Error("ListStream sent no error, want one")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory checks that
|
|
||||||
// DeletePartialUploads, which remote nuke uses, removes a leftover temp
|
|
||||||
// file behind a symlinked metadata/ or blobs/ directory and keeps the
|
|
||||||
// object at the real key.
|
|
||||||
func TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
for _, dir := range []string{metadataDir, blobsDir} {
|
|
||||||
t.Run(dir, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
base := t.TempDir()
|
|
||||||
key := dir + "/aa/bb/object"
|
|
||||||
|
|
||||||
s, err := storage.NewFileStorer(base)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewFileStorer: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = s.Put(ctx, key, strings.NewReader("data"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Put: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
leftover := filepath.Join(base, key+"-123456.partial")
|
|
||||||
|
|
||||||
err = os.WriteFile(leftover, []byte("half"), 0o600)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("writing leftover temp file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
moveBehindSymlink(t, base, dir)
|
|
||||||
|
|
||||||
err = s.DeletePartialUploads(ctx, dir+"/")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("DeletePartialUploads: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// leftover runs through the link.
|
|
||||||
_, err = os.Stat(leftover)
|
|
||||||
if !os.IsNotExist(err) {
|
|
||||||
t.Errorf("leftover temp file was not removed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.Stat(ctx, key)
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("Stat of the real key: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ import (
|
|||||||
// TestNukeRemoteLeavesNoFiles checks that remote nuke leaves no file
|
// TestNukeRemoteLeavesNoFiles checks that remote nuke leaves no file
|
||||||
// under a file:// destination, including the `.partial` files uploads
|
// under a file:// destination, including the `.partial` files uploads
|
||||||
// killed part-way leave next to a snapshot's metadata and next to where a
|
// killed part-way leave next to a snapshot's metadata and next to where a
|
||||||
// blob would have been, a snapshot's database whose manifest was never
|
// blob would have been.
|
||||||
// uploaded, and a file under blobs/ whose name is not a blob hash.
|
|
||||||
func TestNukeRemoteLeavesNoFiles(t *testing.T) {
|
func TestNukeRemoteLeavesNoFiles(t *testing.T) {
|
||||||
log.Initialize(log.Config{})
|
log.Initialize(log.Config{})
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
@@ -39,9 +38,6 @@ func TestNukeRemoteLeavesNoFiles(t *testing.T) {
|
|||||||
"db.zst.age-123456.partial"),
|
"db.zst.age-123456.partial"),
|
||||||
filepath.Join(storeDir, "blobs", hash[:2], hash[2:4],
|
filepath.Join(storeDir, "blobs", hash[:2], hash[2:4],
|
||||||
hash+"-123456.partial"),
|
hash+"-123456.partial"),
|
||||||
filepath.Join(storeDir, "metadata",
|
|
||||||
snapshot.RemoteSnapshotKey("no-manifest"), "db.zst.age"),
|
|
||||||
filepath.Join(storeDir, "blobs", "0b", "01", ".DS_Store"),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, leftover := range leftovers {
|
for _, leftover := range leftovers {
|
||||||
@@ -104,34 +100,6 @@ func TestNukeRemoteFailsWhenADeleteFails(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestNukeRemoteNamesWhatIsLeft checks that remote nuke, when an object
|
|
||||||
// it does not recognise cannot be deleted, does not report the store
|
|
||||||
// empty but names that object and fails.
|
|
||||||
func TestNukeRemoteNamesWhatIsLeft(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
storeDir := filepath.Join(t.TempDir(), "store")
|
|
||||||
v, _, out := backUpToFileDestination(ctx, t, storeDir)
|
|
||||||
|
|
||||||
const leftKey = "blobs/0b/01/.DS_Store"
|
|
||||||
|
|
||||||
leftPath := filepath.Join(storeDir, filepath.FromSlash(leftKey))
|
|
||||||
require.NoError(t, os.MkdirAll(filepath.Dir(leftPath), 0o750))
|
|
||||||
require.NoError(t, os.WriteFile(leftPath, []byte("finder"), 0o600))
|
|
||||||
|
|
||||||
store := faultstore.New(v.Storage)
|
|
||||||
store.OnDelete = func(key string) bool { return key == leftKey }
|
|
||||||
v.Storage = store
|
|
||||||
|
|
||||||
require.Error(t, v.NukeRemote(true))
|
|
||||||
|
|
||||||
assert.Contains(t, out.String(), leftKey)
|
|
||||||
assert.NotContains(t, out.String(), "now empty")
|
|
||||||
assert.Contains(t, out.String(), "vaultik remote nuke --force")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice checks that
|
// TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice checks that
|
||||||
// remote nuke, when the local index belongs to a different destination
|
// remote nuke, when the local index belongs to a different destination
|
||||||
// than the configured one, fails without advising to run nuke again:
|
// than the configured one, fails without advising to run nuke again:
|
||||||
|
|||||||
+18
-67
@@ -22,11 +22,6 @@ var errNukeRequiresForce = errors.New(
|
|||||||
// errBlobDeleteFailed reports unreferenced blobs prune could not delete.
|
// errBlobDeleteFailed reports unreferenced blobs prune could not delete.
|
||||||
var errBlobDeleteFailed = errors.New("blob(s) could not be deleted")
|
var errBlobDeleteFailed = errors.New("blob(s) could not be deleted")
|
||||||
|
|
||||||
// errObjectsLeft reports objects remote nuke still finds on the backup
|
|
||||||
// destination store after deleting.
|
|
||||||
var errObjectsLeft = errors.New(
|
|
||||||
"object(s) still on the backup destination store")
|
|
||||||
|
|
||||||
// nukeCommandHint is the command suggested when a remote nuke could not
|
// nukeCommandHint is the command suggested when a remote nuke could not
|
||||||
// delete everything: running it again deletes what is left, which
|
// delete everything: running it again deletes what is left, which
|
||||||
// `vaultik prune` does not do for snapshot metadata.
|
// `vaultik prune` does not do for snapshot metadata.
|
||||||
@@ -40,11 +35,10 @@ const metadataDirName = "metadata"
|
|||||||
// (blobs/<aa>/<bb>/<hash>).
|
// (blobs/<aa>/<bb>/<hash>).
|
||||||
const blobKeyParts = 4
|
const blobKeyParts = 4
|
||||||
|
|
||||||
// NukeRemote deletes every object under metadata/ and blobs/ in remote
|
// NukeRemote deletes every snapshot's metadata and every blob from remote
|
||||||
// storage, whatever its name, along with any object an upload cut off
|
// storage, along with any object an upload cut off part-way left under a
|
||||||
// part-way left under a temporary `.partial` name. It returns
|
// temporary `.partial` name. After this returns successfully the bucket
|
||||||
// successfully only when a listing afterwards finds nothing left there,
|
// prefix is empty and the next backup starts from scratch.
|
||||||
// and the next 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.
|
||||||
@@ -74,8 +68,7 @@ func (v *Vaultik) NukeRemote(force bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// emptyDestinationStore does the deleting for NukeRemote and stops at
|
// emptyDestinationStore does the deleting for NukeRemote and stops at
|
||||||
// the first step that fails. It also fails when objects are still
|
// the first step that fails.
|
||||||
// listed at the end, naming each one.
|
|
||||||
func (v *Vaultik) emptyDestinationStore() error {
|
func (v *Vaultik) emptyDestinationStore() error {
|
||||||
v.UI.Beginf("Removing all snapshot metadata from backup destination store.")
|
v.UI.Beginf("Removing all snapshot metadata from backup destination store.")
|
||||||
|
|
||||||
@@ -84,62 +77,25 @@ func (v *Vaultik) emptyDestinationStore() error {
|
|||||||
return fmt.Errorf("removing all snapshots: %w", err)
|
return fmt.Errorf("removing all snapshots: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.UI.Beginf("Removing everything still present in backup destination store.")
|
v.UI.Beginf("Removing any blobs still present in backup destination store.")
|
||||||
|
|
||||||
var left []string
|
err = v.PruneBlobs(&PruneOptions{Force: true})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("pruning blobs: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The file and rclone listings skip `.partial` objects, so the two
|
||||||
|
// steps above never delete them.
|
||||||
for _, prefix := range []string{"metadata/", "blobs/"} {
|
for _, prefix := range []string{"metadata/", "blobs/"} {
|
||||||
keys, err := v.deleteEverythingUnder(prefix)
|
err = v.Storage.DeletePartialUploads(v.ctx, prefix)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return fmt.Errorf("deleting partial uploads: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
left = append(left, keys...)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, key := range left {
|
|
||||||
v.UI.Warningf("Still on the backup destination store: %s", key)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(left) > 0 {
|
|
||||||
return fmt.Errorf("%d %w", len(left), errObjectsLeft)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteEverythingUnder deletes every object under prefix, whatever its
|
|
||||||
// name, and returns the keys a listing afterwards still finds. A delete
|
|
||||||
// that fails is logged and the others still run; that object then
|
|
||||||
// shows up in the listing afterwards.
|
|
||||||
func (v *Vaultik) deleteEverythingUnder(prefix string) ([]string, error) {
|
|
||||||
keys, err := v.Storage.List(v.ctx, prefix)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("listing %s: %w", prefix, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, key := range keys {
|
|
||||||
err = v.Storage.Delete(v.ctx, key)
|
|
||||||
if err != nil {
|
|
||||||
log.Error("Failed to delete object", "key", key, "error", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The file and rclone listings skip `.partial` objects, so the
|
|
||||||
// deletes above never reach them.
|
|
||||||
err = v.Storage.DeletePartialUploads(v.ctx, prefix)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("deleting partial uploads: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
left, err := v.Storage.List(v.ctx, prefix)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("listing %s: %w", prefix, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return left, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PruneBlobsResult contains the result of a blob prune operation
|
// PruneBlobsResult contains the result of a blob prune operation
|
||||||
//
|
//
|
||||||
//nolint:tagliatelle // snake_case is the established JSON output format
|
//nolint:tagliatelle // snake_case is the established JSON output format
|
||||||
@@ -204,7 +160,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error {
|
|||||||
return v.outputPruneBlobsJSON(result)
|
return v.outputPruneBlobsJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.UI.Infof("No unreferenced blobs to remove.")
|
v.printlnStdout("No unreferenced blobs to remove.")
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -212,17 +168,12 @@ 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.Force && !opts.JSON {
|
if !opts.JSON {
|
||||||
v.UI.Infof("Found %d unreferenced blob(s) totaling %s.",
|
v.stdoutf("Found %d unreferenced blob(s) totaling %s\n",
|
||||||
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
|
||||||
@@ -249,7 +200,7 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
v.UI.Infof("Deleted %d blob(s) totaling %s.",
|
v.stdoutf("\nDeleted %d blob(s) totaling %s\n",
|
||||||
result.BlobsDeleted, ubytes(result.BytesFreed))
|
result.BlobsDeleted, ubytes(result.BytesFreed))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -59,16 +58,13 @@ 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: stdout,
|
Stdout: &bytes.Buffer{},
|
||||||
Stderr: &bytes.Buffer{},
|
Stderr: &bytes.Buffer{},
|
||||||
Stdin: &bytes.Buffer{},
|
Stdin: &bytes.Buffer{},
|
||||||
UI: ui.NewWithColor(stdout, false),
|
|
||||||
}
|
}
|
||||||
v.SetContext(ctx)
|
v.SetContext(ctx)
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -87,7 +86,6 @@ 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)
|
||||||
|
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
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())
|
|
||||||
}
|
|
||||||
@@ -350,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
|
||||||
@@ -504,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) {
|
||||||
|
|||||||
@@ -574,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.UI.Infof("No snapshots to delete.")
|
v.printlnStdout("No snapshots to delete")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -627,23 +627,24 @@ func selectSnapshotsToPurge(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// confirmAndExecutePurge shows deletion candidates, confirms with the
|
// confirmAndExecutePurge shows deletion candidates, confirms with the
|
||||||
// user, and deletes snapshots.
|
// user, and deletes snapshots. It stops with an error at the first
|
||||||
|
// snapshot it cannot delete.
|
||||||
func (v *Vaultik) confirmAndExecutePurge(
|
func (v *Vaultik) confirmAndExecutePurge(
|
||||||
toDelete []SnapshotInfo, force, quiet bool,
|
toDelete []SnapshotInfo, force, quiet bool,
|
||||||
) error {
|
) error {
|
||||||
// Confirm unless --force is used. The list, the prompt and its answer
|
if !quiet {
|
||||||
// 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(time.DateTime),
|
snap.Timestamp.Format("2006-01-02 15:04:05"),
|
||||||
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
|
||||||
@@ -661,16 +662,7 @@ func (v *Vaultik) confirmAndExecutePurge(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
} else if !quiet {
|
} else if !quiet {
|
||||||
v.UI.Infof("The following snapshots will be deleted:")
|
v.stdoutf("\nDeleting %d snapshot(s) (--force specified)\n", len(toDelete))
|
||||||
|
|
||||||
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)
|
||||||
@@ -678,10 +670,11 @@ func (v *Vaultik) confirmAndExecutePurge(
|
|||||||
snapshotID := snap.ID.String()
|
snapshotID := snap.ID.String()
|
||||||
log.Info("Deleting snapshot", "id", snapshotID)
|
log.Info("Deleting snapshot", "id", snapshotID)
|
||||||
|
|
||||||
|
// Stop before the remote delete: a snapshot still in the local
|
||||||
|
// index must keep its metadata on the destination store.
|
||||||
err := v.deleteSnapshotFromLocalDB(snapshotID)
|
err := v.deleteSnapshotFromLocalDB(snapshotID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Failed to delete from local database",
|
return fmt.Errorf("deleting snapshot %s from local index: %w", snapshotID, err)
|
||||||
"snapshot_id", snapshotID, "error", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID))
|
_, err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID))
|
||||||
@@ -702,9 +695,9 @@ func (v *Vaultik) confirmAndExecutePurge(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !quiet {
|
if !quiet {
|
||||||
v.UI.Infof("Deleted %d snapshot(s).", len(toDelete))
|
v.stdoutf("Deleted %d snapshot(s)\n", len(toDelete))
|
||||||
v.UI.Noticef("Run '%s' to clean up unreferenced remote blobs.",
|
v.printlnStdout(
|
||||||
pruneCommandHint)
|
"\nNote: Run 'vaultik prune' to clean up unreferenced remote blobs.")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -1077,7 +1070,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.UI.Infof("Removing stale local record: %s.", v.UI.Snapshot(id))
|
v.stdoutf("Removing stale local record: %s\n", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = v.deleteSnapshotFromLocalDB(id)
|
err = v.deleteSnapshotFromLocalDB(id)
|
||||||
@@ -1100,9 +1093,9 @@ func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if removed == 0 {
|
if removed == 0 {
|
||||||
v.UI.Infof("No stale local snapshots found.")
|
v.printlnStdout("No stale local snapshots found.")
|
||||||
} else {
|
} else {
|
||||||
v.UI.Infof("Removed %d stale local snapshot record(s).", removed)
|
v.stdoutf("Removed %d stale local snapshot record(s).\n", removed)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -1281,15 +1274,14 @@ func (v *Vaultik) RemoveSnapshot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if inLocalIndex {
|
if inLocalIndex {
|
||||||
v.UI.Infof("Removed snapshot '%s' from local database.",
|
v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID)
|
||||||
v.UI.Snapshot(snapshotID))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if result.RemoteRemoved {
|
if result.RemoteRemoved {
|
||||||
v.UI.Infof("Removed snapshot metadata from remote storage.")
|
v.printlnStdout("Removed snapshot metadata from remote storage")
|
||||||
v.UI.Noticef("The removed snapshot's blobs remain on the remote. "+
|
v.stdoutf("\nNote: The removed snapshot's blobs remain on the remote. "+
|
||||||
"Run '%s' to delete any blobs no longer referenced by any "+
|
"Run '%s' to delete any blobs no longer referenced by any "+
|
||||||
"remaining remote snapshot.", pruneCommandHint)
|
"remaining remote snapshot.\n", pruneCommandHint)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
@@ -1345,23 +1337,21 @@ func (v *Vaultik) removeSnapshotDryRun(
|
|||||||
return result, v.outputRemoveJSON(result)
|
return result, v.outputRemoveJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.UI.Infof("Would remove snapshot: %s.", v.UI.Snapshot(snapshotID))
|
v.stdoutf("Would remove snapshot: %s\n", snapshotID)
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
v.UI.Infof("Would also remove snapshot metadata from " +
|
v.printlnStdout("Would also remove snapshot metadata from " +
|
||||||
"remote storage (blobs untouched).")
|
"remote storage (blobs untouched)")
|
||||||
}
|
}
|
||||||
|
|
||||||
v.UI.Noticef("Dry run: no changes made.")
|
v.printlnStdout("[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. Returns false (treating EOF/read errors as "no") unless the
|
// snapshot. Returns false (treating EOF/read errors as "no") unless the
|
||||||
// user answers "y". The prompt and its answer bypass the UI: they are an
|
// user answers "y".
|
||||||
// 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.LocalOnly {
|
if opts.LocalOnly {
|
||||||
v.stdoutf("Remove snapshot '%s' from local database "+
|
v.stdoutf("Remove snapshot '%s' from local database "+
|
||||||
@@ -1467,7 +1457,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.UI.Infof("No snapshots found.")
|
v.printlnStdout("No snapshots found")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &RemoveResult{}, nil
|
return &RemoveResult{}, nil
|
||||||
@@ -1572,27 +1562,27 @@ func (v *Vaultik) handleRemoveAllDryRun(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !opts.JSON {
|
if !opts.JSON {
|
||||||
v.UI.Infof("Would remove %d local snapshot(s):", len(localSnaps))
|
v.stdoutf("Would remove %d local snapshot(s):\n", len(localSnaps))
|
||||||
|
|
||||||
for _, id := range localSnaps {
|
for _, id := range localSnaps {
|
||||||
v.UI.Detailf("%s", v.UI.Snapshot(id))
|
v.stdoutf(" %s\n", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !opts.LocalOnly {
|
if !opts.LocalOnly {
|
||||||
if len(orphanRemoteKeys) > 0 {
|
if len(orphanRemoteKeys) > 0 {
|
||||||
v.UI.Infof("Would also remove %d orphan remote snapshot key(s):",
|
v.stdoutf("Would also remove %d orphan remote snapshot key(s):\n",
|
||||||
len(orphanRemoteKeys))
|
len(orphanRemoteKeys))
|
||||||
|
|
||||||
for _, key := range orphanRemoteKeys {
|
for _, key := range orphanRemoteKeys {
|
||||||
v.UI.Detailf("%s", key)
|
v.stdoutf(" %s\n", key)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
v.UI.Infof("Would also remove snapshot metadata from " +
|
v.printlnStdout("Would also remove snapshot metadata from " +
|
||||||
"remote storage (blobs untouched).")
|
"remote storage (blobs untouched)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
v.UI.Noticef("Dry run: no changes made.")
|
v.printlnStdout("[Dry run - no changes made]")
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.JSON {
|
if opts.JSON {
|
||||||
@@ -1641,10 +1631,10 @@ func (v *Vaultik) executeRemoveAll(
|
|||||||
return result, v.outputRemoveJSON(result)
|
return result, v.outputRemoveJSON(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
v.UI.Infof("Removed %d snapshot(s).", len(result.SnapshotsRemoved))
|
v.stdoutf("Removed %d snapshot(s)\n", len(result.SnapshotsRemoved))
|
||||||
|
|
||||||
if !opts.LocalOnly && result.RemoteRemoved {
|
if !opts.LocalOnly && result.RemoteRemoved {
|
||||||
v.UI.Infof("Removed snapshot metadata from remote storage.")
|
v.printlnStdout("Removed snapshot metadata from remote storage")
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
|
|||||||
@@ -1,147 +0,0 @@
|
|||||||
package vaultik_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"io/fs"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"sneak.berlin/go/vaultik/internal/log"
|
|
||||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestPruneDeletesNothingThroughSymlinkedDirectory checks that prune keeps
|
|
||||||
// every blob and the local snapshot record when the metadata/ or blobs/
|
|
||||||
// directory of a file:// destination is a symlink to a directory elsewhere
|
|
||||||
// (https://git.eeqj.de/sneak/vaultik/issues/296). A backup writes through
|
|
||||||
// such a link, so prune has to list through it too.
|
|
||||||
func TestPruneDeletesNothingThroughSymlinkedDirectory(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
for _, dir := range []string{"metadata", "blobs"} {
|
|
||||||
t.Run(dir, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
storeDir := filepath.Join(t.TempDir(), "store")
|
|
||||||
v, repos, _ := backUpToFileDestination(ctx, t, storeDir)
|
|
||||||
blobFiles := blobFilesIn(t, storeDir)
|
|
||||||
moveBehindSymlink(t, storeDir, dir)
|
|
||||||
|
|
||||||
require.NoError(t, v.Prune(&vaultik.PruneOptions{Force: true}))
|
|
||||||
|
|
||||||
// When blobs/ is the link, these paths run through it.
|
|
||||||
for _, blobFile := range blobFiles {
|
|
||||||
assert.FileExists(t, blobFile, "prune must delete no blob")
|
|
||||||
}
|
|
||||||
|
|
||||||
snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Len(t, snapshots, 1, "prune must delete no local snapshot record")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestPruneFailsOnSymlinkedDirectoryWithMissingTarget checks that prune
|
|
||||||
// fails, deleting no blob and keeping the local snapshot record, when the
|
|
||||||
// metadata/ or blobs/ directory of a file:// destination is a symlink
|
|
||||||
// whose target is missing, as a link to a volume that is not mounted is.
|
|
||||||
func TestPruneFailsOnSymlinkedDirectoryWithMissingTarget(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
for _, dir := range []string{"metadata", "blobs"} {
|
|
||||||
t.Run(dir, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
storeDir := filepath.Join(t.TempDir(), "store")
|
|
||||||
v, repos, _ := backUpToFileDestination(ctx, t, storeDir)
|
|
||||||
blobFiles := blobFilesIn(t, storeDir)
|
|
||||||
targetPath := moveBehindSymlink(t, storeDir, dir)
|
|
||||||
|
|
||||||
// Unmount the volume the link points to, and mount it again
|
|
||||||
// once prune has run.
|
|
||||||
unmountedPath := targetPath + "-unmounted"
|
|
||||||
require.NoError(t, os.Rename(targetPath, unmountedPath))
|
|
||||||
|
|
||||||
err := v.Prune(&vaultik.PruneOptions{Force: true})
|
|
||||||
require.ErrorIs(t, err, fs.ErrNotExist)
|
|
||||||
|
|
||||||
require.NoError(t, os.Rename(unmountedPath, targetPath))
|
|
||||||
|
|
||||||
// When blobs/ is the link, these paths run through it.
|
|
||||||
for _, blobFile := range blobFiles {
|
|
||||||
assert.FileExists(t, blobFile, "prune must delete no blob")
|
|
||||||
}
|
|
||||||
|
|
||||||
snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Len(t, snapshots, 1, "prune must delete no local snapshot record")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRemoveSnapshotWarnsOnSymlinkedMetadataWithMissingTarget checks that
|
|
||||||
// snapshot remove warns that the metadata could not be removed from the
|
|
||||||
// destination when metadata/ is a symlink whose target is missing, as it
|
|
||||||
// does when the destination directory is missing, instead of finding no
|
|
||||||
// metadata to remove.
|
|
||||||
func TestRemoveSnapshotWarnsOnSymlinkedMetadataWithMissingTarget(t *testing.T) {
|
|
||||||
log.Initialize(log.Config{})
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
storeDir := filepath.Join(t.TempDir(), "store")
|
|
||||||
v, repos, out := backUpToFileDestination(ctx, t, storeDir)
|
|
||||||
targetPath := moveBehindSymlink(t, storeDir, "metadata")
|
|
||||||
require.NoError(t, os.Rename(targetPath, targetPath+"-unmounted"))
|
|
||||||
|
|
||||||
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.NotContains(t, out.String(),
|
|
||||||
"Removed snapshot metadata from remote storage")
|
|
||||||
}
|
|
||||||
|
|
||||||
// blobFilesIn returns the paths of the blob files under storeDir/blobs, and
|
|
||||||
// fails the test when there are none.
|
|
||||||
func blobFilesIn(t *testing.T, storeDir string) []string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
var blobFiles []string
|
|
||||||
|
|
||||||
err := filepath.WalkDir(filepath.Join(storeDir, "blobs"),
|
|
||||||
func(path string, entry fs.DirEntry, err error) error {
|
|
||||||
if err == nil && !entry.IsDir() {
|
|
||||||
blobFiles = append(blobFiles, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
})
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NotEmpty(t, blobFiles)
|
|
||||||
|
|
||||||
return blobFiles
|
|
||||||
}
|
|
||||||
|
|
||||||
// moveBehindSymlink moves storeDir/dir to a directory elsewhere, puts a
|
|
||||||
// symlink to it in its place, and returns where it went.
|
|
||||||
func moveBehindSymlink(t *testing.T, storeDir, dir string) string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
linkPath := filepath.Join(storeDir, dir)
|
|
||||||
targetPath := filepath.Join(t.TempDir(), dir)
|
|
||||||
require.NoError(t, os.Rename(linkPath, targetPath))
|
|
||||||
require.NoError(t, os.Symlink(targetPath, linkPath))
|
|
||||||
|
|
||||||
return targetPath
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user