Compare commits
105
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68ba6bafa8 | ||
|
|
1df6867cd4 | ||
|
|
5ca0d46932 | ||
|
|
6a8bb2f389 | ||
|
|
5f1f8c4f66 | ||
|
|
e8ab13b526 | ||
|
|
f6df500ba2 | ||
|
|
7aae6e4ff3 | ||
|
|
d6eed26482 | ||
|
|
cdcbe8adfd | ||
|
|
1a478ef275 | ||
|
|
d8d13d1c8b | ||
|
|
028a166256 | ||
|
|
c07db21b45 | ||
|
|
1df1d23094 | ||
|
|
0d0c76fa24 | ||
|
|
88a2aa7953 | ||
|
|
098ed80990 | ||
|
|
aae7fa17ae | ||
|
|
9236c0727c | ||
|
|
4418dc3e97 | ||
|
|
5a0da6da12 | ||
|
|
13a35a986a | ||
|
|
5abacbc5c1 | ||
|
|
ff50a137dd | ||
|
|
e9b17cc5fd | ||
|
|
850e2de25a | ||
|
|
6a57750a7b | ||
|
|
2590f49583 | ||
|
|
5b8d84e38a | ||
|
|
7a950ea2aa | ||
|
|
16b03dfda5 | ||
|
|
2125a9d451 | ||
|
|
a0de8bfdb7 | ||
|
|
291c39174f | ||
|
|
65036bba1b | ||
|
|
54ad279dd6 | ||
|
|
d156a02c49 | ||
|
|
aeac897805 | ||
|
|
d8f4f62f41 | ||
|
|
9fd88a34c7 | ||
|
|
5db2e920e5 | ||
|
|
66ea7f5f45 | ||
|
|
dd3667c8e9 | ||
|
|
30285c7a8c | ||
|
|
8d5e6f3399 | ||
|
|
abad8161bc | ||
|
|
05a2c86d65 | ||
|
|
d8f78a1f45 | ||
|
|
2c087be577 | ||
|
|
37d525c322 | ||
|
|
f89fac34f7 | ||
|
|
5d8c515192 | ||
|
|
42eb50b151 | ||
|
|
25ee9211d3 | ||
|
|
3361e9ebd9 | ||
|
|
fb8abcd049 | ||
|
|
6aceaaf086 | ||
|
|
3b2b9cec84 | ||
|
|
dfa3bbc9e1 | ||
|
|
740f474c59 | ||
|
|
27e9798da5 | ||
|
|
4193ced1f6 | ||
|
|
e48bafccef | ||
|
|
bffd4578fc | ||
|
|
f4ab1ba5ae | ||
|
|
005927a7fc | ||
|
|
09a0c01c43 | ||
|
|
8c54e0ff75 | ||
|
|
d1213ecb34 | ||
|
|
5f6455ba17 | ||
|
|
0288735aaf | ||
|
|
35eed79b1a | ||
|
|
94412d9ef3 | ||
|
|
167c0a0746 | ||
|
|
07c957f84b | ||
|
|
c9a519c233 | ||
|
|
fa56165fe4 | ||
|
|
34f61fb408 | ||
|
|
05bf73c48a | ||
|
|
79a73fa122 | ||
|
|
0d0368df81 | ||
|
|
c06c4d201b | ||
|
|
70f008a21a | ||
|
|
fce253fa39 | ||
|
|
e459a66099 | ||
|
|
32c4a46b49 | ||
|
|
b5389a62b5 | ||
|
|
d87202fb70 | ||
|
|
e161343eac | ||
|
|
d53202eb86 | ||
|
|
8b22ae8d42 | ||
|
|
3fc8a8f2f4 | ||
|
|
7696f83258 | ||
|
|
5d1118d143 | ||
|
|
b57ce2277d | ||
|
|
8496404d8b | ||
|
|
cdc60c4dfa | ||
|
|
49eed7a3e5 | ||
|
|
85d4ef118d | ||
|
|
b06f992152 | ||
|
|
5d685f03ce | ||
|
|
f59086c0e5 | ||
|
|
d276d891da | ||
|
|
5aa5ba5544 |
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules/
|
||||||
|
yarn.lock
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"tabWidth": 4,
|
||||||
|
"proseWrap": "always"
|
||||||
|
}
|
||||||
@@ -4,127 +4,122 @@ Version: 2025-06-08
|
|||||||
|
|
||||||
# Instructions and Contextual Information
|
# Instructions and Contextual Information
|
||||||
|
|
||||||
* Be direct, robotic, expert, accurate, and professional.
|
- Be direct, robotic, expert, accurate, and professional.
|
||||||
|
|
||||||
* Do not butter me up or kiss my ass.
|
- Do not butter me up or kiss my ass.
|
||||||
|
|
||||||
* Come in hot with strong opinions, even if they are contrary to the
|
- Come in hot with strong opinions, even if they are contrary to the direction I
|
||||||
direction I am headed.
|
am headed.
|
||||||
|
|
||||||
* If either you or I are possibly wrong, say so and explain your point of
|
- If either you or I are possibly wrong, say so and explain your point of view.
|
||||||
view.
|
|
||||||
|
|
||||||
* Point out great alternatives I haven't thought of, even when I'm not
|
- Point out great alternatives I haven't thought of, even when I'm not asking
|
||||||
asking for them.
|
for them.
|
||||||
|
|
||||||
* Treat me like the world's leading expert in every situation and every
|
- Treat me like the world's leading expert in every situation and every
|
||||||
conversation, and deliver the absolute best recommendations.
|
conversation, and deliver the absolute best recommendations.
|
||||||
|
|
||||||
* I want excellence, so always be on the lookout for divergences from good
|
- I want excellence, so always be on the lookout for divergences from good data
|
||||||
data model design or best practices for object oriented development.
|
model design or best practices for object oriented development.
|
||||||
|
|
||||||
* IMPORTANT: This is production code, not a research or teaching exercise.
|
- IMPORTANT: This is production code, not a research or teaching exercise.
|
||||||
Deliver professional-level results, not prototypes.
|
Deliver professional-level results, not prototypes.
|
||||||
|
|
||||||
* Please read and understand the `README.md` file in the root of the repo
|
- Please read and understand the `README.md` file in the root of the repo for
|
||||||
for project-specific contextual information, including development
|
project-specific contextual information, including development policies,
|
||||||
policies, practices, and current implementation status.
|
practices, and current implementation status.
|
||||||
|
|
||||||
* Be proactive in suggesting improvements or refactorings in places where we
|
- Be proactive in suggesting improvements or refactorings in places where we
|
||||||
diverge from best practices for clean, modular, maintainable code.
|
diverge from best practices for clean, modular, maintainable code.
|
||||||
|
|
||||||
# Policies
|
# Policies
|
||||||
|
|
||||||
1. Before committing, tests must pass (`make test`), linting must pass
|
1. Before committing, tests must pass (`make test`), linting must pass
|
||||||
(`make lint`), and code must be formatted (`make fmt`). For go, those
|
(`make lint`), and code must be formatted (`make fmt`). For go, those
|
||||||
makefile targets should use `go fmt` and `go test -v ./...` and
|
makefile targets should use `go fmt` and `go test -v ./...` and
|
||||||
`golangci-lint run`. Each Makefile target does exactly one thing — to
|
`golangci-lint run`. Each Makefile target does exactly one thing — to run
|
||||||
run lint + fmt-check + test together (the standard pre-commit gate),
|
lint + fmt-check + test together (the standard pre-commit gate), use
|
||||||
use `make check`.
|
`make check`.
|
||||||
|
|
||||||
2. Always write a `Makefile` with the default target being `test`, and with
|
2. Always write a `Makefile` with the default target being `test`, and with a
|
||||||
a `fmt` target that formats the code. The `test` target should run all
|
`fmt` target that formats the code. The `test` target should run all tests in
|
||||||
tests in the project, and the `fmt` target should format the code.
|
the project, and the `fmt` target should format the code. `test` should also
|
||||||
`test` should also have a prerequisite target `lint` that should run any
|
have a prerequisite target `lint` that should run any linters that are
|
||||||
linters that are configured for the project.
|
configured for the project.
|
||||||
|
|
||||||
3. After each completed bugfix or feature, the code must be committed. Do
|
3. After each completed bugfix or feature, the code must be committed. Do all of
|
||||||
all of the pre-commit checks (test, lint, fmt) before committing, of
|
the pre-commit checks (test, lint, fmt) before committing, of course.
|
||||||
course.
|
|
||||||
|
|
||||||
4. When creating a very simple test script for testing out a new feature,
|
4. When creating a very simple test script for testing out a new feature,
|
||||||
instead of making a throwaway to be deleted after verification, write an
|
instead of making a throwaway to be deleted after verification, write an
|
||||||
actual test file into the test suite. It doesn't need to be very big or
|
actual test file into the test suite. It doesn't need to be very big or
|
||||||
complex, but it should be a real test that can be run.
|
complex, but it should be a real test that can be run.
|
||||||
|
|
||||||
5. When you are instructed to make the tests pass, DO NOT delete tests, skip
|
5. When you are instructed to make the tests pass, DO NOT delete tests, skip
|
||||||
tests, or change the tests specifically to make them pass (unless there
|
tests, or change the tests specifically to make them pass (unless there is a
|
||||||
is a bug in the test). This is cheating, and it is bad. You should only
|
bug in the test). This is cheating, and it is bad. You should only be
|
||||||
be modifying the test if it is incorrect or if the test is no longer
|
modifying the test if it is incorrect or if the test is no longer relevant.
|
||||||
relevant. In almost all cases, you should be fixing the code that is
|
In almost all cases, you should be fixing the code that is being tested, or
|
||||||
being tested, or updating the tests to match a refactored implementation.
|
updating the tests to match a refactored implementation.
|
||||||
|
|
||||||
6. When dealing with dates and times or timestamps, always use, display, and
|
6. When dealing with dates and times or timestamps, always use, display, and
|
||||||
store UTC. Set the local timezone to UTC on startup. If the user needs
|
store UTC. Set the local timezone to UTC on startup. If the user needs to see
|
||||||
to see the time in a different timezone, store the user's timezone in a
|
the time in a different timezone, store the user's timezone in a separate
|
||||||
separate field and convert the UTC time to the user's timezone when
|
field and convert the UTC time to the user's timezone when displaying it. For
|
||||||
displaying it. For internal use and internal applications and
|
internal use and internal applications and administrative purposes, always
|
||||||
administrative purposes, always display UTC.
|
display UTC.
|
||||||
|
|
||||||
7. Always write tests, even if they are extremely simple and just check for
|
7. Always write tests, even if they are extremely simple and just check for
|
||||||
correct syntax (ability to compile/import). If you are writing a new
|
correct syntax (ability to compile/import). If you are writing a new feature,
|
||||||
feature, write a test for it. You don't need to target complete
|
write a test for it. You don't need to target complete coverage, but you
|
||||||
coverage, but you should at least test any new functionality you add. If
|
should at least test any new functionality you add. If you are fixing a bug,
|
||||||
you are fixing a bug, write a test first that reproduces the bug, and
|
write a test first that reproduces the bug, and then fix the bug in the code.
|
||||||
then fix the bug in the code.
|
|
||||||
|
|
||||||
8. When implementing new features, be aware of potential side-effects (such
|
8. When implementing new features, be aware of potential side-effects (such as
|
||||||
as state files on disk, data in the database, etc.) and ensure that it is
|
state files on disk, data in the database, etc.) and ensure that it is
|
||||||
possible to mock or stub these side-effects in tests.
|
possible to mock or stub these side-effects in tests.
|
||||||
|
|
||||||
9. Always use structured logging. Log any relevant state/context with the
|
9. Always use structured logging. Log any relevant state/context with the
|
||||||
messages (but do not log secrets). If the log stream is not a terminal,
|
messages (but do not log secrets). If the log stream is not a terminal,
|
||||||
output the structured logs in jsonl format.
|
output the structured logs in jsonl format.
|
||||||
|
|
||||||
10. Avoid using bare strings or numbers in code, especially if they appear
|
10. Avoid using bare strings or numbers in code, especially if they appear
|
||||||
anywhere more than once. Always define a constant (usually at the top
|
anywhere more than once. Always define a constant (usually at the top of the
|
||||||
of the file) and give it a descriptive name, then use that constant in
|
file) and give it a descriptive name, then use that constant in the code
|
||||||
the code instead of the bare string or number.
|
instead of the bare string or number.
|
||||||
|
|
||||||
11. You do not need to summarize your changes in the chat after making them.
|
11. You do not need to summarize your changes in the chat after making them.
|
||||||
Making the changes and committing them is sufficient. If anything out
|
Making the changes and committing them is sufficient. If anything out of the
|
||||||
of the ordinary happened, please explain it, but in the normal case
|
ordinary happened, please explain it, but in the normal case where you found
|
||||||
where you found and fixed the bug, or implemented the feature, there is
|
and fixed the bug, or implemented the feature, there is no need for the
|
||||||
no need for the end-of-change summary.
|
end-of-change summary.
|
||||||
|
|
||||||
12. Do not create additional files in the root directory of the project
|
12. Do not create additional files in the root directory of the project without
|
||||||
without asking permission first. Configuration files, documentation, and
|
asking permission first. Configuration files, documentation, and build files
|
||||||
build files are acceptable in the root, but source code and other files
|
are acceptable in the root, but source code and other files should be
|
||||||
should be organized in appropriate subdirectories.
|
organized in appropriate subdirectories.
|
||||||
|
|
||||||
13. Pre-1.0: NEVER add a database migration. Migrations are supported, but
|
13. Pre-1.0: NEVER add a database migration. Migrations are supported, but
|
||||||
nothing is installed anywhere yet, so there is nothing to migrate. To
|
nothing is installed anywhere yet, so there is nothing to migrate. To change
|
||||||
change the schema, edit `internal/database/schema/001.sql` (and any
|
the schema, edit `internal/database/schema/001.sql` (and any code that
|
||||||
code that touches the affected tables) directly. After 1.0, each schema
|
touches the affected tables) directly. After 1.0, each schema change is a
|
||||||
change is a new numbered file in that directory and a released file is
|
new numbered file in that directory and a released file is never edited; an
|
||||||
never edited; an existing local database is then migrated when vaultik
|
existing local database is then migrated when vaultik is updated. Before
|
||||||
is updated. Before 1.0, a local database left on an older schema is
|
1.0, a local database left on an older schema is deleted and re-created by a
|
||||||
deleted and re-created by a full backup. See
|
full backup. See [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations).
|
||||||
[`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations).
|
|
||||||
|
|
||||||
14. Never use `git add -A`. Stage only the files you intentionally
|
14. Never use `git add -A`. Stage only the files you intentionally changed.
|
||||||
changed.
|
|
||||||
|
|
||||||
15. Commit messages carry no attribution or advertising trailers for the
|
15. Commit messages carry no attribution or advertising trailers for the tool
|
||||||
tool that helped write the code, or for its vendor: the owner is the
|
that helped write the code, or for its vendor: the owner is the sole author
|
||||||
sole author of code written with a tool.
|
of code written with a tool.
|
||||||
|
|
||||||
16. Run the whole test suite with `make test` every time, and read its full
|
16. Run the whole test suite with `make test` every time, and read its full
|
||||||
output. Never run `go test`, a single test or a single package, and
|
output. Never run `go test`, a single test or a single package, and never
|
||||||
never grep the output.
|
grep the output.
|
||||||
|
|
||||||
17. Do not stop working on a task until the definition of done given in the
|
17. Do not stop working on a task until the definition of done given in the
|
||||||
initial instruction is met: all of the work, not part or most of it.
|
initial instruction is met: all of the work, not part or most of it.
|
||||||
|
|
||||||
18. For estimates: backing up over 2.5Gbit/s ethernet to an S3 server
|
18. For estimates: backing up over 2.5Gbit/s ethernet to an S3 server backed by
|
||||||
backed by 2000MB/sec SSD takes about 4 seconds per gigabyte.
|
2000MB/sec SSD takes about 4 seconds per gigabyte.
|
||||||
+24
-3
@@ -5,7 +5,16 @@
|
|||||||
FROM golangci/golangci-lint:v2.14.0@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint
|
FROM golangci/golangci-lint:v2.14.0@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
# Without the time limit a stalled connection to the module proxy holds
|
||||||
|
# this step, and every build on the host sharing it, until the kernel
|
||||||
|
# drops the connection, which can take an hour. The limit is well above
|
||||||
|
# the three minutes a working download can take on a busy build host.
|
||||||
|
RUN for attempt in 1 2 3; do \
|
||||||
|
timeout 300 go mod download && exit 0; \
|
||||||
|
echo "go mod download attempt $attempt failed or ran over 300s" >&2; \
|
||||||
|
done; \
|
||||||
|
echo "module download failed: giving up after 3 attempts" >&2; \
|
||||||
|
exit 1
|
||||||
COPY . .
|
COPY . .
|
||||||
# `golangci-lint run` silently ignores an unknown top-level key in
|
# `golangci-lint run` silently ignores an unknown top-level key in
|
||||||
# .golangci.yml, such as a misspelt `linters:`; `config verify` fails on it.
|
# .golangci.yml, such as a misspelt `linters:`; `config verify` fails on it.
|
||||||
@@ -18,7 +27,13 @@ RUN golangci-lint run --config .golangci.yml ./...
|
|||||||
FROM golang:1.26.1@sha256:cd78d88e00afadbedd272f977d375a6247455f3a4b1178f8ae8bbcb201743a8a AS test
|
FROM golang:1.26.1@sha256:cd78d88e00afadbedd272f977d375a6247455f3a4b1178f8ae8bbcb201743a8a AS test
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
# Limited and retried as in the lint phase above.
|
||||||
|
RUN for attempt in 1 2 3; do \
|
||||||
|
timeout 300 go mod download && exit 0; \
|
||||||
|
echo "go mod download attempt $attempt failed or ran over 300s" >&2; \
|
||||||
|
done; \
|
||||||
|
echo "module download failed: giving up after 3 attempts" >&2; \
|
||||||
|
exit 1
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN go test -timeout 90s -race -cover ./... || \
|
RUN go test -timeout 90s -race -cover ./... || \
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
@@ -36,7 +51,13 @@ RUN apk add --no-cache git
|
|||||||
RUN git config --system --add safe.directory /src
|
RUN git config --system --add safe.directory /src
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
# Limited and retried as in the lint phase above.
|
||||||
|
RUN for attempt in 1 2 3; do \
|
||||||
|
timeout 300 go mod download && exit 0; \
|
||||||
|
echo "go mod download attempt $attempt failed or ran over 300s" >&2; \
|
||||||
|
done; \
|
||||||
|
echo "module download failed: giving up after 3 attempts" >&2; \
|
||||||
|
exit 1
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# The VERSION build arg when one is given, otherwise
|
# The VERSION build arg when one is given, otherwise
|
||||||
|
|||||||
@@ -1,772 +0,0 @@
|
|||||||
# Workflow
|
|
||||||
|
|
||||||
* branch (from `main`)
|
|
||||||
* do the work in Next Step
|
|
||||||
* move Next Step to the top of Completed Steps
|
|
||||||
* move the top item of Future Steps into Next Step
|
|
||||||
* commit (`TODO.md` changes in the same commit as the work)
|
|
||||||
* merge to `main` if the branch is not protected, otherwise open a PR
|
|
||||||
* push
|
|
||||||
|
|
||||||
# Status
|
|
||||||
|
|
||||||
pre-1.0
|
|
||||||
|
|
||||||
# Next Step
|
|
||||||
|
|
||||||
The 1.0 work is complete on `next`: the scope settled on
|
|
||||||
[issue #125](https://git.eeqj.de/sneak/vaultik/issues/125) was the work
|
|
||||||
already planned for 1.0, and all of it has landed. The mechanism to cut
|
|
||||||
the tag exists and is exercised; what is left is merging `next` to
|
|
||||||
`main` and tagging, both the owner's.
|
|
||||||
|
|
||||||
# Completed Steps
|
|
||||||
|
|
||||||
- 2026-10-06: Made `go.mod` what `go mod tidy` writes, so the
|
|
||||||
pre-commit hook no longer stops every commit
|
|
||||||
([issue #246](https://git.eeqj.de/sneak/vaultik/issues/246)). A test
|
|
||||||
in `internal/cli` imports `github.com/spf13/pflag` directly, but
|
|
||||||
`go.mod` still marked it `// indirect`, and `script/precommit` fails
|
|
||||||
whenever the tidy changes `go.mod`. It is now in the direct `require`
|
|
||||||
block.
|
|
||||||
|
|
||||||
- 2026-10-06: Made the README's steps for restoring on another machine
|
|
||||||
work ([issue #221](https://git.eeqj.de/sneak/vaultik/issues/221)).
|
|
||||||
`config init` wrote a placeholder recipient that `config.Load`
|
|
||||||
rejects, so every command on the new machine failed before reaching
|
|
||||||
the store. The file now has an empty `age_recipients` list,
|
|
||||||
`config.Load` accepts an empty list, and `snapshot create` refuses to
|
|
||||||
run without a recipient.
|
|
||||||
|
|
||||||
- 2026-10-06: Made `snapshot restore --skip-errors` skip the files that
|
|
||||||
need a blob it cannot download
|
|
||||||
([issue #218](https://git.eeqj.de/sneak/vaultik/issues/218)). A missing
|
|
||||||
or damaged blob ended the restore even with the flag, after restoring
|
|
||||||
whichever files happened to come first. Every file that needs such a
|
|
||||||
blob is now reported as failed, the rest are restored, and the command
|
|
||||||
still exits non-zero. Without the flag the blob error still aborts.
|
|
||||||
|
|
||||||
- 2026-10-06: Re-vendored the canonical files from `sneak/prompts` at
|
|
||||||
`dd4027b` ([issue #213](https://git.eeqj.de/sneak/vaultik/issues/213)).
|
|
||||||
Linting and testing are now the `lint` and `test` phases of the
|
|
||||||
`Dockerfile`, and the build stage depends on both. `Dockerfile.lint`,
|
|
||||||
`CHECK_EPOCH` and the tests that checked them are gone; every
|
|
||||||
`docker build` in `script/` passes `--no-cache` instead. golangci-lint
|
|
||||||
is v2.14.0, with its new findings fixed in the code, and the rules in
|
|
||||||
`CLAUDE.md` now live in `AGENTS.md`.
|
|
||||||
|
|
||||||
- 2026-10-06: Made the local index actually run in WAL mode with a busy
|
|
||||||
timeout ([issue #217](https://git.eeqj.de/sneak/vaultik/issues/217)).
|
|
||||||
The connection settings were written in a form the SQLite driver
|
|
||||||
ignores, so the index ran without either and `snapshot list` or `info`
|
|
||||||
during a backup could make the backup's next write fail with
|
|
||||||
`database is locked`. They are now `_pragma=` parameters, and the
|
|
||||||
metadata export copies the open index with `VACUUM INTO`, because a
|
|
||||||
copy of the file alone misses rows still in the `-wal` file.
|
|
||||||
|
|
||||||
- 2026-10-06: Made a backup record the real uid and gid of files,
|
|
||||||
directories and symlinks
|
|
||||||
([issue #216](https://git.eeqj.de/sneak/vaultik/issues/216)). The
|
|
||||||
scanner asked the stat result for `Uid()` and `Gid()` methods, which
|
|
||||||
`*syscall.Stat_t` does not have, so every entry was stored as `0:0`
|
|
||||||
and a restore as root gave every file to root. It now reads the
|
|
||||||
`Uid` and `Gid` fields of `*syscall.Stat_t`.
|
|
||||||
|
|
||||||
- 2026-10-06: Made a `file://` destination whose directory is missing
|
|
||||||
count as one that cannot be listed
|
|
||||||
([issue #220](https://git.eeqj.de/sneak/vaultik/issues/220)). The file
|
|
||||||
backend listed a missing directory as an empty store, so with the
|
|
||||||
quickstart's USB stick unplugged `snapshot list` reported every local
|
|
||||||
snapshot as missing from the store, `snapshot remove` claimed to have
|
|
||||||
removed metadata it never reached, and `prune` dropped every local
|
|
||||||
snapshot record. Listing a missing destination directory is now an
|
|
||||||
error; a first backup still creates the directory.
|
|
||||||
|
|
||||||
- 2026-10-06: Made `--older-than` and `--keep-newer-than` reject a
|
|
||||||
duration with characters outside its number-and-unit parts
|
|
||||||
([issue #215](https://git.eeqj.de/sneak/vaultik/issues/215)). The
|
|
||||||
parser picked out the parts it recognised and skipped the rest, so
|
|
||||||
`1.0y` became zero and `--prune --keep-newer-than 1.0y` deleted every
|
|
||||||
snapshot of the backed-up names, the new one included. `1.0y`,
|
|
||||||
`1,5y`, `30 days`, `x7d` and a bare `0` are now errors; decimals still
|
|
||||||
work in Go units such as `1.5h`.
|
|
||||||
|
|
||||||
- 2026-10-06: Made a backup re-chunk a known file that lists a chunk no
|
|
||||||
uploaded blob holds
|
|
||||||
([issue #214](https://git.eeqj.de/sneak/vaultik/issues/214)). File
|
|
||||||
rows are shared by every snapshot and updated in place, so removing or
|
|
||||||
pruning the only snapshot that referenced a changed file's current
|
|
||||||
blob left an older snapshot keeping a row that matched the disk while
|
|
||||||
no blob held its chunks. The next backup skipped the file and
|
|
||||||
completed a snapshot that could not restore it.
|
|
||||||
|
|
||||||
- 2026-09-22: Routed the last direct-to-stdout command output through
|
|
||||||
`internal/ui`
|
|
||||||
([issue #149](https://git.eeqj.de/sneak/vaultik/issues/149)). The
|
|
||||||
`version`, `info`, `remote info`, `config`, and `database delete`
|
|
||||||
commands wrote plain text straight to stdout, so they were unstyled and
|
|
||||||
ignored `--quiet`. Output now falls in two buckets, both governed by
|
|
||||||
`internal/ui`: status lines and confirmations go through its message
|
|
||||||
methods (styled, and `--quiet` silences them), while the data a command
|
|
||||||
exists to produce — the reports, the `snapshot list` table, `config get`
|
|
||||||
values, and the `--json` documents — is written plain. `--quiet`
|
|
||||||
silences the human reports and tables but never the `config get` value
|
|
||||||
or the `--json` documents, which a script depends on, and the
|
|
||||||
`database delete` confirmation prompt is always shown. The README
|
|
||||||
output-style section now states this rule.
|
|
||||||
|
|
||||||
- 2026-09-22: Validated blob hashes, offsets and lengths read back from
|
|
||||||
the destination before using them
|
|
||||||
([issue #155](https://git.eeqj.de/sneak/vaultik/issues/155)). A blob
|
|
||||||
hash taken from the downloaded database or the store listing was
|
|
||||||
trusted unchecked, so a hostile remote could drive a decrypted blob to
|
|
||||||
be written outside the cache directory (a hash like `aa/../../etc`) or
|
|
||||||
crash a command with a short or negative value. `blobDiskCache.path`
|
|
||||||
now refuses any key containing a path separator, and `ReadAt` rejects a
|
|
||||||
negative offset or length and bounds with `length > size-offset` so a
|
|
||||||
sum cannot overflow past the check. A new `isBlobHash` helper (a plain
|
|
||||||
function, not a method — the packer stores `temp-placeholder-{uuid}` as
|
|
||||||
a hash) gates `FetchBlob`, shallow and deep verify; the `blobs/` and
|
|
||||||
`metadata/` listings skip a non-conforming name with a warning; and
|
|
||||||
short-hash prefixes in log and error text go through a `shortHash`
|
|
||||||
helper that cannot panic. `verify`'s chunk reader also rejects a
|
|
||||||
negative `blob_chunks` length and streams the chunk instead of
|
|
||||||
allocating a database-supplied size. `restore.go` and
|
|
||||||
`internal/database` were left untouched to avoid colliding with the
|
|
||||||
in-flight [issue #156](https://git.eeqj.de/sneak/vaultik/issues/156)
|
|
||||||
work; the cache-path and `FetchBlob` guards already stop the unsafe
|
|
||||||
write and fetch, so restore's own `buildBlobIndexes` early check is
|
|
||||||
deferred as fail-fast defense in depth.
|
|
||||||
|
|
||||||
- 2026-09-21: Stopped an interrupted blob upload from making a later
|
|
||||||
backup deduplicate against data that was never stored
|
|
||||||
([issue #148](https://git.eeqj.de/sneak/vaultik/issues/148)). The
|
|
||||||
packer commits a blob's `chunks`, `blob_chunks`, and `blobs` rows
|
|
||||||
before the upload is attempted, so a failed upload left chunk rows
|
|
||||||
behind and the next run skipped re-uploading them, producing a
|
|
||||||
snapshot that reported success but could not be restored. A run now
|
|
||||||
deduplicates only against chunks held by a blob whose `uploaded_ts` is
|
|
||||||
set, and at startup drops any un-uploaded blob rows (and the chunks
|
|
||||||
they orphan) so the affected data is re-chunked and re-uploaded. Blobs
|
|
||||||
recorded with no remote backend are marked uploaded so this invariant
|
|
||||||
holds uniformly.
|
|
||||||
|
|
||||||
- 2026-09-22: Made restore refuse any snapshot path that would write
|
|
||||||
outside the target directory
|
|
||||||
([issue #154](https://git.eeqj.de/sneak/vaultik/issues/154)).
|
|
||||||
`restoreFile` and `verifyRestoredFiles` joined the stored path onto the
|
|
||||||
target with no containment check, so a `..` segment or an absolute path
|
|
||||||
escaped the target and a restored symlink could redirect a later child
|
|
||||||
write anywhere on disk. Every stored path is now rejected unless
|
|
||||||
`filepath.IsLocal` accepts it with the leading separator removed, and
|
|
||||||
each existing ancestor directory below the target is `Lstat`ed to refuse
|
|
||||||
descending through a symlink; honest symlinks pointing outside the tree
|
|
||||||
are still written verbatim. age decryption proves a snapshot is
|
|
||||||
readable, not honest, and restore usually runs as root.
|
|
||||||
|
|
||||||
- 2026-09-21: Stopped `--json` from silencing stderr diagnostics
|
|
||||||
([issue #112](https://git.eeqj.de/sneak/vaultik/issues/112)). `--json`
|
|
||||||
used to be folded into `Quiet`, which pinned the log level to `WARN`,
|
|
||||||
so `prune --json` gave a machine consumer no record of the local index
|
|
||||||
rows it deleted even under `--verbose`. `--json` now quiets only the
|
|
||||||
stdout UI (the JSON document must stay clean, per
|
|
||||||
[issue #108](https://git.eeqj.de/sneak/vaultik/issues/108)); the stderr
|
|
||||||
log level follows `--verbose`/`--debug` again. The coupling was
|
|
||||||
removed the same way for `snapshot verify`, `snapshot remove`, and
|
|
||||||
`remote info`, which carried it for the same outdated reason.
|
|
||||||
|
|
||||||
- 2026-09-21: Stopped `prune` from reporting a failed row count as 0
|
|
||||||
([issue #96](https://git.eeqj.de/sneak/vaultik/issues/96)). The seven
|
|
||||||
`getTableCount` reads in `PruneDatabase` discarded their error, so a
|
|
||||||
query that could not run became a plausible `0` and the before/after
|
|
||||||
delta computed from it looked like real work. Each read now logs at
|
|
||||||
warn on failure and renders as `unknown`, never `0`, so an empty table
|
|
||||||
is distinguishable from one that could not be queried. The counts have
|
|
||||||
no `--json` representation — under `--json` the summary is suppressed
|
|
||||||
entirely — so nothing there can show a false `0`.
|
|
||||||
|
|
||||||
- 2026-09-21: Made the s3 storage backend report a missing object as
|
|
||||||
`storage.ErrNotFound`, like the `file` and `rclone` backends and as the
|
|
||||||
`Storer` interface documents. `S3Storer.Get` and `Stat` returned the raw
|
|
||||||
AWS SDK error, so `errors.Is(err, storage.ErrNotFound)` was false on s3
|
|
||||||
and callers branched differently per backend. Added a small `s3.IsNotFound`
|
|
||||||
helper (reused by `HeadObject`) and a test that a missing key maps to
|
|
||||||
`ErrNotFound`
|
|
||||||
([issue #129](https://git.eeqj.de/sneak/vaultik/issues/129)).
|
|
||||||
- 2026-09-21: Fixed `verify --deep` reporting healthy snapshots as
|
|
||||||
corrupt. Its final blob-integrity check hashed the encrypted
|
|
||||||
downloaded bytes with a single SHA256 and compared that to the blob
|
|
||||||
ID, which is the double SHA256 of the plaintext, so the two could
|
|
||||||
never match. It now hashes the decompressed plaintext and compares the
|
|
||||||
double SHA256. Added a test that backs up a real snapshot, deep-verifies
|
|
||||||
it, then flips a byte in one stored blob and confirms deep verification
|
|
||||||
then fails
|
|
||||||
([issue #131](https://git.eeqj.de/sneak/vaultik/issues/131)).
|
|
||||||
|
|
||||||
- 2026-09-21: Made `snapshot create` VACUUM the per-snapshot metadata
|
|
||||||
database through the `modernc.org/sqlite` driver instead of shelling
|
|
||||||
out to the external `sqlite` command-line binary (issue #120). A
|
|
||||||
backup no longer needs that binary on `PATH`, so `make check` passes
|
|
||||||
on a stock `go install` host; `script/bootstrap` and the `Dockerfile`
|
|
||||||
(both the test-build and the shipped runtime stage) no longer install
|
|
||||||
it, and a new test asserts the uploaded database keeps no pages from
|
|
||||||
deleted rows. Dropped the now-false note on the 2026-08-07 entry below
|
|
||||||
that said bootstrap installs it.
|
|
||||||
- 2026-09-21: Made `.gitea/workflows/check.yml` run on pushes to `main`
|
|
||||||
and `next` and on pull requests against either, so unit PRs (whose
|
|
||||||
base is `next`) and `next` itself get a CI run instead of relying on a
|
|
||||||
local `make check`
|
|
||||||
([issue #122](https://git.eeqj.de/sneak/vaultik/issues/122)).
|
|
||||||
|
|
||||||
- 2026-09-21: Hash-verified the Go toolchain in the release workflow
|
|
||||||
([issue #105](https://git.eeqj.de/sneak/vaultik/issues/105)). New
|
|
||||||
`script/install-go` downloads the exact `go.dev` archive for `go.mod`'s
|
|
||||||
`go` directive and refuses it unless its sha256 matches a value
|
|
||||||
committed in the script; `.gitea/workflows/release.yml` calls it
|
|
||||||
instead of `actions/setup-go`, which verified the downloaded toolchain
|
|
||||||
against nothing in the repo. `GOTOOLCHAIN: local` on the release step
|
|
||||||
keeps that exact compiler from auto-switching. Bumping Go now touches
|
|
||||||
`go.mod`, the checksum, and the `Dockerfile` `golang` digest together.
|
|
||||||
|
|
||||||
- 2026-09-21: Collapsed the two duration parsers into one and fixed the
|
|
||||||
`--older-than` months example
|
|
||||||
([issue #123](https://git.eeqj.de/sneak/vaultik/issues/123)). Two
|
|
||||||
functions named `parseDuration` existed with different grammars;
|
|
||||||
`snapshot purge --older-than` and `--keep-newer-than` both already went
|
|
||||||
through the one in `internal/vaultik`, while the richer copy in
|
|
||||||
`internal/cli/duration.go` was reachable only from its own test. Kept
|
|
||||||
the live-path parser and deleted the unused one, so no flag's accepted
|
|
||||||
grammar changes. The trap the issue was filed over: `README.md`
|
|
||||||
documented `6m` as the months example for `--older-than`, but `m` is
|
|
||||||
minutes, so the documented command deleted every snapshot older than
|
|
||||||
six minutes on a destructive flag. Corrected the doc to `6mo` and put
|
|
||||||
both flags' help text on one example list that states `m` is minutes
|
|
||||||
and `mo` is months. The surviving parser now rejects negatives, which
|
|
||||||
it previously accepted (`-5h`) or silently made positive (`-5d`).
|
|
||||||
Table-driven tests cover every unit, `6m` as six minutes, `6mo` as 180
|
|
||||||
days, and rejection of a bare number, an unknown unit, and a negative.
|
|
||||||
|
|
||||||
- 2026-08-10: Moved every lint run into its own container, as a build
|
|
||||||
step ([issue #113](https://git.eeqj.de/sneak/vaultik/issues/113)).
|
|
||||||
New root `Dockerfile.lint`, built by `script/lint`, runs
|
|
||||||
`golangci-lint run --config .golangci.yml ./...` as a `RUN`
|
|
||||||
instruction in the digest-pinned `golangci/golangci-lint` image: a
|
|
||||||
successful build of that file *is* a clean lint, and it works even
|
|
||||||
where the daemon is remote and bind mounts are impossible. That
|
|
||||||
`FROM` line is now the only pin of the linter version in the repo.
|
|
||||||
|
|
||||||
This supersedes the per-worktree cache isolation landed for
|
|
||||||
[issue #99](https://git.eeqj.de/sneak/vaultik/issues/99). Isolation
|
|
||||||
fixed cross-worktree contamination but not lock contention — two
|
|
||||||
concurrent runs with entirely separate cache directories still
|
|
||||||
collided. A container per run has its own cache and its own lock, so
|
|
||||||
the whole class is gone, and with it the per-worktree cache
|
|
||||||
machinery, the lock-retry loop, and `script/lint-audit`, which
|
|
||||||
existed to catch replayed findings from a cache that no longer
|
|
||||||
exists. The host lint path went too: no escape hatch, no
|
|
||||||
`VAULTIK_LINT_IN_CONTAINER`, no version detection. Nothing lints on
|
|
||||||
the host at any version.
|
|
||||||
|
|
||||||
A cached build lints nothing, so the same `CHECK_EPOCH` mechanism the
|
|
||||||
product `Dockerfile` already used is what makes the green mean
|
|
||||||
something: `ARG CHECK_EPOCH` with no default below the module layers,
|
|
||||||
a `RUN [ -n "$CHECK_EPOCH" ] || exit 1` guard, the value expanded
|
|
||||||
into each check command, and a fresh `$(date +%s%N)$$` per invocation
|
|
||||||
computed as a bare assignment. `cmd/vaultik/lintdocker_test.go`
|
|
||||||
parses both Dockerfiles and both scripts and fails if any part of
|
|
||||||
that is dropped, because every way of losing it is silent. No test
|
|
||||||
asserts that no script runs the host linter: `script/lint` is the one
|
|
||||||
lint entry point and runs `golangci-lint` only inside the container,
|
|
||||||
and keeping it that way is a review matter, not something a test
|
|
||||||
proves.
|
|
||||||
|
|
||||||
The product `Dockerfile` lost its lint stage rather than gaining a
|
|
||||||
second linter pin: `make lint` is now `docker build`, so the stage
|
|
||||||
would have been docker-in-docker with no daemon, and calling
|
|
||||||
`golangci-lint` directly there would have restored the two-pins drift
|
|
||||||
of [issue #78](https://git.eeqj.de/sneak/vaultik/issues/78).
|
|
||||||
`make fmt-check` moved beside `make test` in the builder stage, and
|
|
||||||
`script/cibuild` now builds `Dockerfile.lint` and then `Dockerfile`,
|
|
||||||
each with its own fresh epoch. Consequence, stated rather than left
|
|
||||||
to be found: `script/docker` builds the product image only and no
|
|
||||||
longer lints; the gates are `script/check` and `script/cibuild`.
|
|
||||||
|
|
||||||
`golangci-lint config verify` runs as its own epoch-keyed layer,
|
|
||||||
above the lint. `golangci-lint run` rejects a config it cannot parse
|
|
||||||
but silently ignores an unknown top-level *key*: renaming `linters:`
|
|
||||||
to `linterz:` discarded `default: all` and every threshold and still
|
|
||||||
exited 0 on a tree the real config fails. `config verify` catches
|
|
||||||
that, and it does so with the network off at this pin — checked under
|
|
||||||
`docker run --network none`, not assumed. An earlier revision omitted
|
|
||||||
it on the claim that it fetches its schema over live HTTPS; that
|
|
||||||
claim was false at v2.12.2.
|
|
||||||
|
|
||||||
`script/lint-fix` is kept, reimplemented as a
|
|
||||||
bind-mounted `docker run` against the image parsed out of
|
|
||||||
`Dockerfile.lint` — it cannot be a build step, because fixes have to
|
|
||||||
land in the worktree — and marked in its header as a developer
|
|
||||||
convenience that no gate reads.
|
|
||||||
|
|
||||||
- 2026-08-09: Finished the `--json` stdout contract and gave `make build`
|
|
||||||
a rule ([issue #108](https://git.eeqj.de/sneak/vaultik/issues/108),
|
|
||||||
[issue #110](https://git.eeqj.de/sneak/vaultik/issues/110)). Two
|
|
||||||
unrelated defects of the same shape — a command reporting something it
|
|
||||||
did not do — landed together because both are small.
|
|
||||||
|
|
||||||
`CleanupLocalSnapshots` wrote three prose lines to stdout with no
|
|
||||||
`--json` awareness, covering every branch of the function, so no input
|
|
||||||
avoided them and `vaultik prune --json | jq` failed even after
|
|
||||||
[issue #106](https://git.eeqj.de/sneak/vaultik/issues/106) removed the
|
|
||||||
banner. `-q` never helped either: `printlnStdout` and `stdoutf` write
|
|
||||||
straight to `Vaultik.Stdout` and never consult `Vaultik.UI`, which is
|
|
||||||
what `SetQuiet` affects. The issue offered three fixes and asked for a
|
|
||||||
decision. Taken: thread `*PruneOptions` into the function and gate each
|
|
||||||
write on `!opts.JSON`, matching `PruneBlobs` (its sibling phase, which
|
|
||||||
already takes the same struct), `RemoveSnapshot` and `remote info`, so
|
|
||||||
the package has one pattern rather than two. Rejected: moving the lines
|
|
||||||
to `log.Info`, because the logger's default level is `slog.LevelWarn`,
|
|
||||||
so that would not relocate them to stderr — it would delete them from a
|
|
||||||
plain `vaultik prune`, and the removal of rows from the local index is
|
|
||||||
not something to narrate only under `--verbose`. Also rejected: putting
|
|
||||||
the stale-record count into `PruneBlobsResult`, whose every field is
|
|
||||||
blob-scoped and which is produced by the later phase; a prune document
|
|
||||||
covering both phases is a reasonable thing to want, but it is a schema
|
|
||||||
design question and not a stream-hygiene fix. The narration is
|
|
||||||
duplicated as `log.Info` records, which `PruneBlobs` already does
|
|
||||||
alongside its own prints, so the events survive on stderr for anyone
|
|
||||||
running `--verbose`.
|
|
||||||
|
|
||||||
`make build` printed "Nothing to be done for 'build'" and exited 0
|
|
||||||
without producing a binary: `build` was listed in `.PHONY` with no
|
|
||||||
`build:` rule anywhere, and declaring a name phony is exactly what
|
|
||||||
converts make's "No rule to make target" error into a silent success.
|
|
||||||
Fixed with `build: vaultik`, keeping `vaultik:` as the file rule. The
|
|
||||||
audit the issue asked for covers all 19 `.PHONY` names; `build` was the
|
|
||||||
only one without a rule, and `vaultik` is correctly absent from
|
|
||||||
`.PHONY`, being a real file target.
|
|
||||||
|
|
||||||
Tests, each verified to fail with the fix reverted rather than assumed
|
|
||||||
to: `CleanupLocalSnapshots` leaves stdout untouched under `--json` in
|
|
||||||
all three branches (stale records, none, empty index) and still emits
|
|
||||||
every line without it, so the guard cannot be satisfied by deleting the
|
|
||||||
output; `prune --json` run end to end through `Entry`, cobra and fx
|
|
||||||
over the process's real stdout descriptor against a `file://` store,
|
|
||||||
asserting exactly one JSON document, in both the stale and non-stale
|
|
||||||
branches; and a parse of the `Makefile` asserting every `.PHONY` name
|
|
||||||
has a rule and that `build` reaches the rule that produces the binary,
|
|
||||||
which keeps the audit true for names added later. That last one is a
|
|
||||||
parse rather than an invocation of `make`, since `make test` is what
|
|
||||||
runs it and shelling back into `make build` would nest a build inside
|
|
||||||
the test run. The property a parse cannot establish — that the recipe
|
|
||||||
still fails when the build fails — was verified by hand against a
|
|
||||||
deliberately broken tree: `make build` exits 2 and produces nothing.
|
|
||||||
`cmd/vaultik` gains its first test file, so `make test` now reports 16
|
|
||||||
packages `ok` where it reported 15.
|
|
||||||
|
|
||||||
- 2026-08-09: Stopped the startup banner from contaminating `--json`
|
|
||||||
documents ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)).
|
|
||||||
`Entry` writes the banner to stdout before cobra parses anything, and
|
|
||||||
the flag scan that suppresses it knew `--quiet`, `-q` and `--cron` but
|
|
||||||
not `--json`, so every `--json` document arrived behind two lines of
|
|
||||||
prose and a blank line, and `vaultik snapshot list --json | jq` failed.
|
|
||||||
With the logger already on stderr from
|
|
||||||
[issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), this was the
|
|
||||||
last writer that could put something on stdout that the caller did not
|
|
||||||
ask for. The design question the issue raised — extend the raw-argv
|
|
||||||
scan, or move the banner after parsing — is answered in favour of the
|
|
||||||
scan: the banner is printed first deliberately, so that it still
|
|
||||||
appears when cobra rejects the arguments and on `--help`, and after
|
|
||||||
parsing there is no single place that covers those paths. The stated
|
|
||||||
cost of the scan, that `--json` is a subcommand flag matched anywhere
|
|
||||||
in the vector, is a cost `--cron` already carries — it exists only on
|
|
||||||
`snapshot create` — so this adds an instance of an accepted
|
|
||||||
imprecision rather than a new kind, and the two error directions are
|
|
||||||
not symmetric: a false positive loses a decorative banner, a false
|
|
||||||
negative corrupts a document. Regression tests at the CLI layer, where
|
|
||||||
`internal/vaultik`'s existing guard cannot reach: one runs `Entry`
|
|
||||||
itself over the process's real stdout descriptor, through cobra and fx
|
|
||||||
to the document, made hermetic by `file://` storage; a second covers
|
|
||||||
the argument vectors of all five `--json` commands; a third asserts the
|
|
||||||
banner is still printed without a suppressing flag, so the first
|
|
||||||
cannot be satisfied by deleting the banner. Also corrected `AGENTS.md`
|
|
||||||
policy 9, which still keyed the structured-log format on stdout's
|
|
||||||
TTY-ness after #82 moved that decision to stderr — a rules file that
|
|
||||||
misdescribes the code misleads exactly the readers who trust it most.
|
|
||||||
Two smaller findings from the same review: `bytesAttrKey`'s
|
|
||||||
human-readable byte formatting silently stopped applying under an open
|
|
||||||
group, because the key reaching the comparison is group-qualified
|
|
||||||
(`transfer.bytes`), now matched on its final segment and tested both
|
|
||||||
ways; and `listEnv.stderr` in `snapshot_list_test.go`, assigned but
|
|
||||||
never read since those tests began capturing the process's stderr, is
|
|
||||||
removed. `Vaultik.Stderr` is kept — nothing writes to it today, which
|
|
||||||
its comment now says outright.
|
|
||||||
|
|
||||||
- 2026-08-09: Moved the logger to stderr and fixed `TTYHandler`'s
|
|
||||||
discarded attributes
|
|
||||||
([issue #82](https://git.eeqj.de/sneak/vaultik/issues/82),
|
|
||||||
[issue #97](https://git.eeqj.de/sneak/vaultik/issues/97)). Two defects
|
|
||||||
in `internal/log`, fixed together because both live in the handler
|
|
||||||
construction path. The first: both handlers were built over
|
|
||||||
`os.Stdout`, and `WARN`/`ERROR` are never suppressed, so a config file
|
|
||||||
with group- or world-readable permissions was enough to put a log
|
|
||||||
record inside a `--json` document and break `jq`. Diagnostics now go
|
|
||||||
to stderr, and the TTY/JSON format choice follows stderr rather than
|
|
||||||
stdout — testing the wrong stream would colorize records on a
|
|
||||||
redirected stderr whenever stdout happened to be a terminal. This is
|
|
||||||
user-visible: `--verbose` and `--debug` output moves to stderr too,
|
|
||||||
which is documented in `README.md` under "stdout and stderr". It also
|
|
||||||
let the local workaround in `internal/vaultik/snapshot_list.go` go:
|
|
||||||
`warnWhileListing` had been hand-rolling structured-log formatting to
|
|
||||||
reach a non-stdout writer, and the `jsonOutput` parameter threaded
|
|
||||||
through the remote-listing helpers existed only to choose between the
|
|
||||||
two writers. The collect-then-emit machinery around `listingWarning`
|
|
||||||
stays, but on its remaining merit — warnings emitted in key order
|
|
||||||
after `group.Wait()` are deterministic run to run, where emitting from
|
|
||||||
the fetch workers would order them by network timing. The second
|
|
||||||
defect: `TTYHandler.WithAttrs` and `WithGroup` discarded their
|
|
||||||
arguments and returned the receiver while their doc comments claimed
|
|
||||||
otherwise, so `log.With` attributes vanished on a terminal and
|
|
||||||
appeared correctly in CI — failing precisely when someone is debugging
|
|
||||||
interactively. Both now return a new handler (the receiver is never
|
|
||||||
written to, since `slog` permits concurrent derivation), attributes
|
|
||||||
persist across records, and grouping is implemented as dotted key
|
|
||||||
prefixes, which is the only honest rendering for a format with nowhere
|
|
||||||
to nest. New tests cover both, including one that feeds the same
|
|
||||||
derivation chain to the TTY and JSON handlers and compares the
|
|
||||||
attribute sets, so the two paths cannot drift apart again. Found and
|
|
||||||
filed while verifying: the startup banner is written to stdout and
|
|
||||||
`--json` does not suppress it
|
|
||||||
([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)), which is
|
|
||||||
a separate writer on a separate path and the remaining source of
|
|
||||||
stdout contamination.
|
|
||||||
|
|
||||||
- 2026-08-09: Made the tagged-release path actually work on Gitea
|
|
||||||
([issue #65](https://git.eeqj.de/sneak/vaultik/issues/65)). Three
|
|
||||||
independent blockers, one of which was the whole
|
|
||||||
release: `.goreleaser.yaml` had no `gitea_urls:` block, so goreleaser
|
|
||||||
defaulted to the GitHub API and a `goreleaser release` from this repo
|
|
||||||
would have failed or published where nobody is looking. It now points
|
|
||||||
at `https://git.eeqj.de/api/v1`. The version is the second: it was a
|
|
||||||
hardcoded `VERSION := 1.0.0-rc.1` in the `Makefile`, so every local
|
|
||||||
build claimed to be a release candidate that had never been tagged and
|
|
||||||
did not exist, while `git tag -l` was empty and `internal/globals`
|
|
||||||
defaulted to `dev`. Version now comes from git via the new
|
|
||||||
`script/version` — the exact tag with a leading `v` stripped (so a
|
|
||||||
`make` build and a goreleaser build of one commit report the same
|
|
||||||
string, and it matches the archive names), otherwise `dev-<12-char
|
|
||||||
sha>`, with `-dirty` appended in either case when tracked files are
|
|
||||||
modified. Untracked files are deliberately not counted, matching
|
|
||||||
`git describe --dirty`. The same honesty was owed by the snapshot
|
|
||||||
path: `snapshot.version_template` was `{{ incpatch .Version }}-next`,
|
|
||||||
which manufactures a release number from the last tag and, with no
|
|
||||||
tags at all, from goreleaser's fabricated `v0.0.0`; it now emits the
|
|
||||||
same `dev-<sha>`. The one non-obvious consequence is that
|
|
||||||
`internal/cli/version.go` gated its "this is a development build"
|
|
||||||
notice on the version being exactly `dev`, so the moment untagged
|
|
||||||
builds began carrying a commit sha that notice would have gone silent
|
|
||||||
and an unreleased binary would have read as a release — the gate is
|
|
||||||
now `globals.IsDevVersion`, which is a predicate over a string rather
|
|
||||||
than a comparison against a global precisely so it can be tested, and
|
|
||||||
it is tested at the boundary (`1.0.0-dev` is a release, `dev-<sha>`
|
|
||||||
is not). Release automation is the third blocker: a tag-triggered
|
|
||||||
`.gitea/workflows/release.yml` runs the build in CI rather than from
|
|
||||||
a laptop, with `fetch-depth: 0` because a shallow checkout has no
|
|
||||||
tags and would silently mislabel the release, and with the
|
|
||||||
`RELEASE_TOKEN` repository secret passed as `GITEA_TOKEN` (documented
|
|
||||||
in `README.md`; the runner's automatic token is not used because it
|
|
||||||
is not guaranteed to carry release write scope). `script/release`
|
|
||||||
unsets any `GITHUB_TOKEN`/`GITLAB_TOKEN` it finds, since goreleaser
|
|
||||||
chooses its forge from whichever token variable is set and refuses to
|
|
||||||
run when it sees more than one — a runner-provided token must not get
|
|
||||||
to decide where these artifacts are published. `make release` and
|
|
||||||
`make release-snapshot`, the last two Makefile targets that were not
|
|
||||||
shims, now call `script/release` and `script/release-snapshot`, which
|
|
||||||
resolve goreleaser exactly the way `script/lint` resolves the linter:
|
|
||||||
a `PATH` binary is used only at the pinned version, never as a silent
|
|
||||||
fallback. `script/bootstrap` installs it, from a sha256-verified
|
|
||||||
GitHub release archive per `REPO_POLICIES.md`, via a separate
|
|
||||||
`script/install-goreleaser` — separate because `script/bootstrap`
|
|
||||||
hard-fails without a usable Docker daemon by design, and the release
|
|
||||||
runner needs goreleaser without needing Docker. Verified by running
|
|
||||||
the thing rather than reading it: `make release-snapshot` produced
|
|
||||||
four archives and `checksums.txt`, and the linux/amd64 binary from
|
|
||||||
`dist/` reports `dev-<sha>` with the development-build notice. Tag
|
|
||||||
handling was exercised in a throwaway repository rather than by
|
|
||||||
tagging this one; no tag was created here, since that is the owner's
|
|
||||||
call. Signing, SBOM, reproducible builds, completions and a man page
|
|
||||||
are out of scope by the issue.
|
|
||||||
|
|
||||||
- 2026-08-09: Isolated the lint cache per worktree and context-gated the
|
|
||||||
native lint path (issues #99, #80). One defect seen twice:
|
|
||||||
`script/lint` decided whether it could skip the pinned image by asking
|
|
||||||
what version was on `PATH` rather than where it was running, and cache
|
|
||||||
isolation is part of that same question. The cache was one directory
|
|
||||||
per repo, shared by every worktree on the host, so two checkouts with
|
|
||||||
identical Go file contents collided and golangci-lint replayed the
|
|
||||||
stored analysis — paths and all. The loud direction of that failure
|
|
||||||
(a clean tree failed by a dirty sibling) is the harmless one; the
|
|
||||||
silent direction, a dirty tree **passed** by a clean sibling, is a
|
|
||||||
sixth way for a gate here to report a green it did not earn. The cache
|
|
||||||
is now keyed on a digest of the worktree path, and every run is
|
|
||||||
audited by the new `script/lint-audit`, which rejects output citing any
|
|
||||||
file that is not in the tree being linted — a backstop that runs on
|
|
||||||
clean output too, because that is the case nobody investigates. Caches
|
|
||||||
record the worktree they belong to and are collected when it
|
|
||||||
disappears, so throwaway worktrees do not accumulate them; the whole
|
|
||||||
tree lives under `XDG_CACHE_HOME` and is disposable. The
|
|
||||||
`parallel golangci-lint is running` refusal is now a bounded retry
|
|
||||||
rather than a verdict: it is not a lint result, and exiting non-zero
|
|
||||||
on it is indistinguishable to a caller from real findings (#88 showed
|
|
||||||
a private cache does not remove that contention). The native path now
|
|
||||||
requires `VAULTIK_LINT_IN_CONTAINER=1`, set only by the `Dockerfile`
|
|
||||||
lint stage, in addition to matching the pin, so a developer's locally
|
|
||||||
installed 2.12.2 no longer bypasses the digest pin; `/.dockerenv` was
|
|
||||||
rejected as the signal because `dockerd` creates it for `docker run`
|
|
||||||
and it is not reliably present during a BuildKit `docker build`, which
|
|
||||||
is the case the exception exists for. Version detection uses
|
|
||||||
`golangci-lint version --short` with the old banner scrape kept only
|
|
||||||
as a fallback. `script/bootstrap` no longer prints `bootstrap
|
|
||||||
complete` on a machine that cannot run the gate: a missing docker, or
|
|
||||||
one whose daemon is unreachable, is a hard failure naming exactly what
|
|
||||||
breaks. Verification was by reproduction rather than inspection — two
|
|
||||||
concurrent lints from two worktrees of differing cleanliness, a real
|
|
||||||
run made to report an outside path, a matching linter shimmed onto
|
|
||||||
`PATH`, and a `PATH` with docker removed — and is recorded on the pull
|
|
||||||
request.
|
|
||||||
- 2026-08-09: Closed the fifth false-green mechanism (issues #93, #69).
|
|
||||||
`script/test` omitted `-count=1`, so Go's test result cache could
|
|
||||||
satisfy the gate outright: a second back-to-back `make test` printed
|
|
||||||
the full set of 14 `ok` lines, every one marked `(cached)`, having
|
|
||||||
executed no test at all. Since `ok <pkg> (cached)` is an `ok` line,
|
|
||||||
the "14 `ok` lines means the suite ran" signal this repo leans on was
|
|
||||||
forgeable, one level below the Docker layer cache that #85 addressed.
|
|
||||||
Fixed with `-count=1` unconditionally rather than only in the
|
|
||||||
container, because the pre-commit hook runs the same script and a
|
|
||||||
gate honest only in CI is dishonest where people rely on it most;
|
|
||||||
`test-coverage` got the same flag, and `script/check` inherits it by
|
|
||||||
calling `script/test`. In the same area, `make test-integration` was
|
|
||||||
deleted rather than made real: no file in the repo carried a build
|
|
||||||
tag, so `-tags=integration` selected nothing and the target was an
|
|
||||||
exact duplicate of `make test`. Tagging a subset was rejected because
|
|
||||||
the entire suite runs in well under a minute, and a scheme whose
|
|
||||||
failure mode is "some tests silently stopped running" is a poor trade
|
|
||||||
for those seconds in a repo with this particular history. The
|
|
||||||
`-timeout` was raised from 30s after measuring rather than after
|
|
||||||
assuming: the standing claim that cold-cache compilation is charged
|
|
||||||
against `-timeout` is **false**, disproved by a containerised run
|
|
||||||
that spent 46s compiling and still reported per-package durations
|
|
||||||
within noise of a warm host run. `-timeout` reaches the test binary
|
|
||||||
as `-test.timeout` and its clock starts inside `testing.M.Run`, after
|
|
||||||
the build. The real exposure was margin, not compilation. The 120s
|
|
||||||
landed on is a **deliberate, documented divergence** from
|
|
||||||
`REPO_POLICIES.md:192`, which mandates 30s, and from that file's
|
|
||||||
canonical recipe at `:212-214`; the divergence is recorded in
|
|
||||||
`script/test`'s comment because `REPO_POLICIES.md` is org-canonical
|
|
||||||
and not editable here, and issue #101 proposes amending the policy
|
|
||||||
text upstream. Numbers and the full verification are recorded once,
|
|
||||||
on the pull request, and are deliberately not restated here.
|
|
||||||
|
|
||||||
- 2026-08-09: Triaged all fifteen stale remote branches (issue #71) and
|
|
||||||
deleted fourteen of them; the full per-branch disposition with
|
|
||||||
evidence is recorded on that issue. Method mattered more than the
|
|
||||||
outcome here: a three-dot `git diff main...branch` diffs from the
|
|
||||||
merge base, so it replays everything that landed on `main` after the
|
|
||||||
branch diverged and makes any old branch look like it holds unlanded
|
|
||||||
work. That artifact is what made `golangci-v2.12.2` appear to carry
|
|
||||||
126 files of unpushed changes when its tree was byte-identical to
|
|
||||||
`main`'s. Every containment claim here therefore rests on two-dot tip
|
|
||||||
diffs, tree-hash equality, `git cherry`, and `git branch -r --merged`.
|
|
||||||
Nine branches were plain ancestors of `main` with zero `git cherry`
|
|
||||||
`+` commits. `golangci-v2.12.2` had landed squashed as `cc58583`,
|
|
||||||
whose tree hash equals the branch tip's exactly; note the hash
|
|
||||||
recorded in the issue had gone stale because `main` advanced, so the
|
|
||||||
check had to be redone rather than repeated.
|
|
||||||
`fix/sync-snapshot-cleanup` was redundant, its one line already on
|
|
||||||
`main` in `syncWithRemote`. `feature/restore-progress-bar` was
|
|
||||||
superseded by `printRestoreProgress` and the disk-backed blob cache,
|
|
||||||
and had become actively regressive — it would have deleted
|
|
||||||
`internal/blobgen/compress_test.go`, the #28 regression test that
|
|
||||||
landed separately. The two branches this issue was filed for both
|
|
||||||
turned out to be closed questions that `main` had already moved past
|
|
||||||
by a recorded decision, so neither was landed and no regression test
|
|
||||||
was owed: `ctime` no longer exists anywhere in the codebase after
|
|
||||||
`1c72a37` removed the column, the `File.CTime` field and every use
|
|
||||||
(#54/#55), and change detection compares size, mtime, mode, uid and
|
|
||||||
gid only, exactly as `ARCHITECTURE.md` documents — so the
|
|
||||||
silently-skipped-file data-loss risk that made this a 1.0 item does
|
|
||||||
not exist. The SQL allow-list branch would have reverted `bfd7334`,
|
|
||||||
which replaced that very allow-list with regex sanitisation on review
|
|
||||||
feedback, and would have broken `getTableCount("snapshots")` because
|
|
||||||
its allow-list omits that table. `feature/daemon-mode` is untouched
|
|
||||||
and deferred to #94 pending an owner decision, so it is the one
|
|
||||||
branch besides `main` still on the remote. The stale `TODO.md` entry
|
|
||||||
named in the issue needed no fix: `e496aa3` had already removed it.
|
|
||||||
No product code changed.
|
|
||||||
- 2026-08-09: Adopted the remaining upstream `CHECK_EPOCH` hardening
|
|
||||||
(issue #91), closing the gap #85 knowingly left open. Four changes,
|
|
||||||
all four decided as adopt upstream in `sneak/prompts` #26. (1) Each
|
|
||||||
check stage now asserts `[ -n "$CHECK_EPOCH" ] || exit 1` before
|
|
||||||
running anything, so a build that supplies no `--build-arg` fails
|
|
||||||
instead of lying. This is the item that mattered: an unset `ARG` is
|
|
||||||
an empty string and an empty string is a stable cache key, so the
|
|
||||||
second and every later bare `docker build .` on an unchanged tree
|
|
||||||
replayed all three check layers and still exited 0 — and `docker
|
|
||||||
build .` is the command `REPO_POLICIES.md` names verbatim as a thing
|
|
||||||
that must be green, so the documented command was precisely the one
|
|
||||||
that lied. Failed steps are never cached, which is what makes the
|
|
||||||
guard fire on every invocation rather than once. (2) The epoch is now
|
|
||||||
expanded into each check command rather than left as a bare
|
|
||||||
declaration, so the cache miss no longer depends on BuildKit's
|
|
||||||
unreferenced-`ARG` handling staying as it is, and the value appears
|
|
||||||
in the build log. (3) `script/cibuild` uses
|
|
||||||
`epoch="$(date +%s%N)$$"`, unique per invocation rather than per
|
|
||||||
second; `%N` alone is insufficient because busybox drops it silently
|
|
||||||
and exits 0, and `$$` is what makes the guarantee hold regardless.
|
|
||||||
The bare-assignment form is kept deliberately — inlined in an
|
|
||||||
argument, a failing substitution does not abort under `set -eu` and
|
|
||||||
would yield an empty constant epoch, restoring the exact false green
|
|
||||||
being fixed. (4) `script/docker` passes the same fresh arg, so the
|
|
||||||
two entrypoints cannot disagree about whether the tree is green;
|
|
||||||
local builds are almost always warm, which made it the likelier
|
|
||||||
fooling in practice. The `ARG` placement from #85 is unchanged, below
|
|
||||||
`apk add`, `COPY go.mod go.sum` and `go mod download`, so dependency
|
|
||||||
layers still cache and the build is not cold. Verified by negative
|
|
||||||
control rather than inspection — a bare `docker build .` run twice
|
|
||||||
back to back, plus back-to-back pairs of both scripts and a host-side
|
|
||||||
`make check`; the measurements are recorded once, in the PR
|
|
||||||
verification comment, rather than restated here. `.golangci.yml`, the
|
|
||||||
lint-stage `FROM` line and its digest, `script/lint`,
|
|
||||||
`REPO_POLICIES.md` and `.gitea/workflows/check.yml` are all
|
|
||||||
untouched.
|
|
||||||
- 2026-08-09: Stopped `script/cibuild` from reporting a green it did
|
|
||||||
not earn (issue #85). A bare `docker build .` let Docker serve the
|
|
||||||
check layers from the layer cache whenever the tree had not changed:
|
|
||||||
the checks never executed and the build still exited 0. The fix is an
|
|
||||||
`ARG CHECK_EPOCH` declared immediately above the check `RUN`s in both
|
|
||||||
the lint stage and the builder stage (`ARG` scope is per-stage, so
|
|
||||||
each declares its own), with `script/cibuild` assigning
|
|
||||||
`epoch="$(date +%s)"` and passing `--build-arg CHECK_EPOCH="$epoch"`.
|
|
||||||
The assignment is separate on purpose: under `set -eu` a command
|
|
||||||
substitution that fails inside an argument does not abort the script,
|
|
||||||
which would leave an empty constant `CHECK_EPOCH` and restore the
|
|
||||||
very false green being fixed. Placement is the rest of the point —
|
|
||||||
the `ARG` sits below the `apk add`, `COPY go.mod go.sum`, and `go mod
|
|
||||||
download` layers, so only the checks are invalidated and the
|
|
||||||
dependency layers still cache. The guarantee is conditional on a
|
|
||||||
fresh value rather than absolute: a bare `docker build .` gets an
|
|
||||||
empty `CHECK_EPOCH` and can still serve the check layers from cache,
|
|
||||||
which `README.md` and the `Dockerfile` now say plainly, with issue
|
|
||||||
#91 tracking the upstream hardening (expanded `ARG` form, unset
|
|
||||||
guard, per-invocation epoch, `script/docker`) that would close it.
|
|
||||||
Verified by re-running the reproduction plus the withheld-`--build-arg`
|
|
||||||
counterfactual; the measurements are recorded once, in the PR #89
|
|
||||||
verification comment, rather than restated here. `.golangci.yml`, the
|
|
||||||
lint-stage `FROM` line and its digest, `script/lint`, and
|
|
||||||
`.gitea/workflows/check.yml` are all untouched.
|
|
||||||
- 2026-08-09: Corrected the `Vaultik.UI` doc comment (issue #84). It
|
|
||||||
claimed the cli layer replaces the writer with a discarding one in
|
|
||||||
`--cron` mode; the actual mechanism is `UI.SetQuiet(true)` in
|
|
||||||
`setupGlobals`, which drops Begin/Complete/Info/Notice/Detail/
|
|
||||||
Progress/Banner but still emits Warning and Error. The `--cron` line
|
|
||||||
in `README.md` said "Silent unless error", which understated what
|
|
||||||
survives, and now names warnings too. The other `--cron` comments
|
|
||||||
(`internal/log/log.go`, `internal/cli/snapshot.go`,
|
|
||||||
`internal/vaultik/snapshot.go`) were audited and already accurate.
|
|
||||||
Comments and docs only, no behavior change.
|
|
||||||
- 2026-08-09: Made `snapshot list` list the destination store without
|
|
||||||
the private key (issue #64). The listing is now the union of the
|
|
||||||
local index and a single streamed listing of the `metadata/` prefix,
|
|
||||||
with no `age_secret_key` gate — the manifest is unencrypted, so a
|
|
||||||
host holding only the public key can enumerate its own backups and a
|
|
||||||
host that lost its local index can still see them. A remote-only
|
|
||||||
snapshot's hostname and name are deliberately not recovered (they are
|
|
||||||
not recoverable without the private key, and making them so would
|
|
||||||
undo the privacy property tracked in issue #81); such rows are
|
|
||||||
labelled by an abbreviation of their remote key and carry the real
|
|
||||||
timestamp and compressed size from the manifest, with `<remote only>`
|
|
||||||
in the two columns that require the local index. Local-only snapshots
|
|
||||||
are reported as drift, and the hint now names `vaultik prune`, which
|
|
||||||
exists, instead of `vaultik snapshot cleanup`, which does not.
|
|
||||||
`reportRemoteDrift` collapsed into the merged view. Every remote
|
|
||||||
manifest read in the codebase now goes through
|
|
||||||
`downloadManifestByKey`, so issue #81 has one call site to change.
|
|
||||||
Review rework: snapshot timestamps now normalize to UTC in
|
|
||||||
`scanSnapshotRows`, the one place they enter the domain, so the merged
|
|
||||||
TIMESTAMP column cannot show local time for a locally tracked row and
|
|
||||||
UTC for a remote-only row on a non-UTC host; `GetIncompleteByHostname`
|
|
||||||
was folded onto that same scanner. `--json` now reports the
|
|
||||||
unreadable-manifest count and the 1000-row truncation on stderr
|
|
||||||
instead of returning a silently short document (the document's shape
|
|
||||||
is unchanged). The two per-snapshot `log.Warn` calls on the listing
|
|
||||||
path now route through the same JSON-aware writer as the existing
|
|
||||||
workaround, so one corrupt manifest can no longer put a log line on
|
|
||||||
stdout ahead of the document and break `| jq` — still a local
|
|
||||||
workaround pending issue #82. Verified with `script/cibuild` and with
|
|
||||||
an uncached `make check` (`0 issues.`, no cached test packages), plus
|
|
||||||
end to end against a `file://` destination with no secret key present.
|
|
||||||
- 2026-08-09: Closed the gap between `make lint` and CI (issue #78).
|
|
||||||
`script/lint` now runs the digest-pinned `golangci-lint` image taken
|
|
||||||
from the `Dockerfile` lint stage, which is the single source of truth
|
|
||||||
for the linter version; the duplicate pin in the `Makefile` `deps`
|
|
||||||
target and the unpinned `golangci-lint` install in `script/bootstrap`
|
|
||||||
are gone. A `golangci-lint` on `PATH` is used only when its version is
|
|
||||||
exactly the pinned one (which is how the lint stage runs it inside the
|
|
||||||
container); anything else goes through Docker, and a missing or
|
|
||||||
unreachable Docker daemon is a hard error rather than a silent
|
|
||||||
fallback. Only the **lint** leg of `make check` became equivalent to
|
|
||||||
`script/cibuild`; its tests and `gofmt` still run on the host against
|
|
||||||
the host toolchain, as `README.md` states. An earlier version of this
|
|
||||||
entry claimed `make check` was "as trustworthy as `script/cibuild`"
|
|
||||||
outright, which overstated it; corrected under issue #80.
|
|
||||||
- 2026-08-09: Finished the lint remediation under the canonical
|
|
||||||
`.golangci.yml` (issue #61, which also unblocks issue #59). The
|
|
||||||
remaining findings were fixed behavior-preservingly: `wsl_v5`
|
|
||||||
whitespace, `sqlclosecheck`, and `prealloc`. The `sqlclosecheck` sites
|
|
||||||
now close `sql.Rows` in a deferred closure instead of via the
|
|
||||||
`CloseRows` helper, which the linter could not see through. Only the
|
|
||||||
`revive` package-name findings remain suppressed, with per-site
|
|
||||||
`//nolint` directives; the package-rename question behind them is
|
|
||||||
tracked in issue #76. Verified with `script/cibuild`, which exits 0 —
|
|
||||||
that is the only trustworthy gate, because `script/lint` runs whatever
|
|
||||||
`golangci-lint` happens to be on `PATH` rather than the pinned
|
|
||||||
v2.12.2 that CI and the `Dockerfile` use, so `make check` can report
|
|
||||||
green on findings CI still fails. That tooling gap is tracked in issue
|
|
||||||
#78.
|
|
||||||
- 2026-08-09: The earlier next step "reconcile the uncommitted
|
|
||||||
`ARCHITECTURE.md` edits on `main`" needed no work: the working tree is
|
|
||||||
clean and `ARCHITECTURE.md` is committed on `main`.
|
|
||||||
- 2026-08-07: Updated golangci-lint to v2.12.2 everywhere it is pinned
|
|
||||||
(`Dockerfile` lint stage, `Makefile` deps target), replaced
|
|
||||||
`.golangci.yml` with the canonical config (v2 schema, `default: all`),
|
|
||||||
and remediated the bulk of the lint findings it surfaced (issue #61):
|
|
||||||
behavior-preserving fixes across every package, 2,990 findings down to
|
|
||||||
80. `make test` and `make fmt-check` were green at that point but
|
|
||||||
`make lint` was still red; the commit message claiming `make check`
|
|
||||||
was green was wrong.
|
|
||||||
- 2026-08-07: Added the standard `.golangci.yml` and `.editorconfig`
|
|
||||||
(issue #59); lint findings under the new config are tracked in issue
|
|
||||||
#61.
|
|
||||||
- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints,
|
|
||||||
Makefile shims, README Entrypoints section
|
|
||||||
- 2026-07-02: Consolidated CLI verbs, retired overlapping commands; bound
|
|
||||||
the local index to its backup destination URL.
|
|
||||||
- 2026-06-28: snapshot rm now removes metadata only and prints the prune
|
|
||||||
command; restore skips chown when running as non-root.
|
|
||||||
- 2026-06-26: Snapshot IDs hashed at the storage boundary; snapshot list
|
|
||||||
made resilient to bad remote entries.
|
|
||||||
- 2026-06-24: Collapsed snapshot prune into vaultik prune; restore streams
|
|
||||||
blobs to disk and restores files in blob-locality order; cron output
|
|
||||||
fixes.
|
|
||||||
- 2026-06-17: Restore overhaul: ReadAt chunk reads from cached blobs,
|
|
||||||
reference-counted blob sweeper, integration tests; new internal/ui
|
|
||||||
output layer, banner, and progress lines.
|
|
||||||
- 2025-12-18: Added ARCHITECTURE.md and godoc coverage for exported API.
|
|
||||||
- 2025-07-26: End-to-end integration tests; manifest format refactor;
|
|
||||||
renamed backup to snapshot; afero filesystem abstraction.
|
|
||||||
- 2025-07-20: Initial design and implementation: cobra + fx CLI skeleton,
|
|
||||||
SQLite index database, UUID blob storage with streaming chunking.
|
|
||||||
|
|
||||||
# Future Steps
|
|
||||||
|
|
||||||
Work planned after 1.0 is listed in the README
|
|
||||||
[roadmap](README.md#roadmap).
|
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package main_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestDockerfileBoundsEveryModuleDownload fails unless every
|
||||||
|
// `go mod download` in the Dockerfile runs under a time limit, is tried
|
||||||
|
// a fixed number of times, and then fails the build with a message that
|
||||||
|
// names the module download (issue #351). Like the version tests, this
|
||||||
|
// parses the Dockerfile; that a stalled download really is cut off and
|
||||||
|
// retried was checked by hand.
|
||||||
|
func TestDockerfileBoundsEveryModuleDownload(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var downloads []string
|
||||||
|
|
||||||
|
for _, instruction := range instructions(t, productDockerfile) {
|
||||||
|
if strings.Contains(instruction, "go mod download") {
|
||||||
|
downloads = append(downloads, instruction)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
require.NotEmpty(t, downloads, "%s must download modules",
|
||||||
|
productDockerfile)
|
||||||
|
|
||||||
|
for _, download := range downloads {
|
||||||
|
assert.Contains(t, download, "timeout 300 go mod download",
|
||||||
|
"%s: a module download must have a time limit: %s",
|
||||||
|
productDockerfile, download)
|
||||||
|
assert.Contains(t, download, "for attempt in 1 2 3",
|
||||||
|
"%s: a module download must be retried: %s",
|
||||||
|
productDockerfile, download)
|
||||||
|
assert.Contains(t, download, "module download failed",
|
||||||
|
"%s: a module download that never succeeds must say so: %s",
|
||||||
|
productDockerfile, download)
|
||||||
|
assert.True(t, strings.HasSuffix(download, "exit 1"),
|
||||||
|
"%s: a module download that never succeeds must fail the"+
|
||||||
|
" build: %s", productDockerfile, download)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -287,19 +287,24 @@ storage_url: "rclone://myremote/path/to/backups"
|
|||||||
# #use_ssl: true
|
# #use_ssl: true
|
||||||
#
|
#
|
||||||
# # Part size for multipart uploads
|
# # Part size for multipart uploads
|
||||||
# # Minimum 5MB, affects memory usage during upload
|
# # Minimum 5MiB, maximum 5GiB; affects memory usage during upload
|
||||||
# # Supports: 5MB, 10M, 100MiB, etc.
|
# # A blob too large for 10,000 parts of this size gets larger parts
|
||||||
# # Default: 5MB
|
# # Supports: 10MB, 16MiB, 100MiB, etc. (5MB is below the minimum)
|
||||||
# #part_size: 5MB
|
# # Default: 5MiB
|
||||||
|
# #part_size: 5MiB
|
||||||
|
|
||||||
# Path to local SQLite index database
|
# Path to local SQLite index database
|
||||||
# This database tracks file state for incremental backups
|
# This database tracks file state for incremental backups
|
||||||
# Default: /var/lib/vaultik/index.sqlite
|
# It must be an absolute path; ~ is expanded
|
||||||
#index_path: /var/lib/vaultik/index.sqlite
|
# Default: the platform data directory, e.g.
|
||||||
|
# macOS: ~/Library/Application Support/vaultik/index.sqlite
|
||||||
|
# Linux: ~/.local/share/vaultik/index.sqlite
|
||||||
|
#index_path: /path/to/index.sqlite
|
||||||
|
|
||||||
# Average chunk size for content-defined chunking
|
# Average chunk size for content-defined chunking
|
||||||
# Smaller chunks = better deduplication but more metadata
|
# Smaller chunks = better deduplication but more metadata
|
||||||
# Supports: 10MB, 5M, 1GB, 500KB, 64MiB, etc.
|
# Minimum 1MB
|
||||||
|
# Supports: 10MB, 5M, 1GB, 64MiB, etc.
|
||||||
# Default: 10MB
|
# Default: 10MB
|
||||||
#chunk_size: 10MB
|
#chunk_size: 10MB
|
||||||
|
|
||||||
@@ -310,6 +315,12 @@ storage_url: "rclone://myremote/path/to/backups"
|
|||||||
# Chunking uses no secret (the FastCDC parameters are fixed and public). At a
|
# Chunking uses no secret (the FastCDC parameters are fixed and public). At a
|
||||||
# large limit a blob holds hundreds of chunks, so individual chunk lengths are
|
# large limit a blob holds hundreds of chunks, so individual chunk lengths are
|
||||||
# not visible in its size; lowering the limit toward chunk_size exposes them.
|
# not visible in its size; lowering the limit toward chunk_size exposes them.
|
||||||
|
# A backup needs free temporary space, because each blob is written whole to
|
||||||
|
# a temporary file before it is uploaded (up to about blob_size_limit; an
|
||||||
|
# rclone destination that cannot stream uploads needs about twice that) and
|
||||||
|
# the metadata export writes copies of the local index. Temporary files go to
|
||||||
|
# $TMPDIR (default /tmp); with TMPDIR unset, SQLite writes one of those copies
|
||||||
|
# to /var/tmp.
|
||||||
# Supports: 1GB, 10G, 500MB, 1GiB, etc.
|
# Supports: 1GB, 10G, 500MB, 1GiB, etc.
|
||||||
# Default: 10GB
|
# Default: 10GB
|
||||||
#blob_size_limit: 10GB
|
#blob_size_limit: 10GB
|
||||||
@@ -318,6 +329,20 @@ storage_url: "rclone://myremote/path/to/backups"
|
|||||||
# Higher = better compression but slower
|
# Higher = better compression but slower
|
||||||
# Default: 3
|
# Default: 3
|
||||||
compression_level: 5
|
compression_level: 5
|
||||||
|
|
||||||
|
# How old a blob that no snapshot lists must be before prune deletes it, and
|
||||||
|
# how old every object in a directory under metadata/ with no manifest must
|
||||||
|
# be before prune deletes that directory
|
||||||
|
# A backup uploads its blobs and its db.zst.age before its manifest, so on a
|
||||||
|
# destination shared between hosts or users this must be longer than the
|
||||||
|
# longest backup run
|
||||||
|
# It does not protect a blob a backup reuses from an earlier run that stopped
|
||||||
|
# before its manifest: that blob keeps the time of its first upload, so a
|
||||||
|
# prune can delete it
|
||||||
|
# Supports: 36h, 90m, etc.; 0s deletes such blobs and directories at once
|
||||||
|
# Default: 24h
|
||||||
|
#prune_grace_period: 24h
|
||||||
|
|
||||||
# Hostname to use in backup metadata
|
# Hostname to use in backup metadata
|
||||||
# Default: system hostname
|
# Default: system hostname
|
||||||
#hostname: myserver
|
#hostname: myserver
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
# Vaultik Architecture
|
# Vaultik Architecture
|
||||||
|
|
||||||
This document describes the internal architecture of Vaultik, focusing on the data model, type instantiation, and the relationships between core modules.
|
This document describes the internal architecture of Vaultik, focusing on the
|
||||||
|
data model, type instantiation, and the relationships between core modules.
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Vaultik is a backup system that uses content-defined chunking for deduplication and packs chunks into large, compressed, encrypted blobs for efficient cloud storage. The system is built around dependency injection using [uber-go/fx](https://github.com/uber-go/fx).
|
Vaultik is a backup system that uses content-defined chunking for deduplication
|
||||||
|
and packs chunks into large, compressed, encrypted blobs for efficient cloud
|
||||||
|
storage. The system is built around dependency injection using
|
||||||
|
[uber-go/fx](https://github.com/uber-go/fx).
|
||||||
|
|
||||||
## Data Flow
|
## Data Flow
|
||||||
|
|
||||||
@@ -53,53 +57,88 @@ The database tracks five primary entities and their relationships:
|
|||||||
### Entity Descriptions
|
### Entity Descriptions
|
||||||
|
|
||||||
#### File (`database.File`)
|
#### File (`database.File`)
|
||||||
Represents a file, directory, or symlink in the backup system. Stores metadata needed for restoration:
|
|
||||||
- Path, source_path (for restore path stripping), mtime
|
Represents a file, directory, or symlink in the backup system. Stores metadata
|
||||||
|
needed for restoration:
|
||||||
|
|
||||||
|
- Path, mtime
|
||||||
- Size, mode, ownership (uid, gid)
|
- Size, mode, ownership (uid, gid)
|
||||||
- Symlink target (if applicable)
|
- Symlink target (if applicable)
|
||||||
|
|
||||||
|
It also stores `source_path`, the source directory the scan found it under, made
|
||||||
|
absolute and with symlinks resolved. Restore does not read it.
|
||||||
|
|
||||||
#### Chunk (`database.Chunk`)
|
#### Chunk (`database.Chunk`)
|
||||||
A content-addressed unit of data. Files are split into variable-size chunks using the FastCDC algorithm:
|
|
||||||
|
A content-addressed unit of data. Files are split into variable-size chunks
|
||||||
|
using the FastCDC algorithm:
|
||||||
|
|
||||||
- `ChunkHash`: SHA256 hash of chunk content (primary key)
|
- `ChunkHash`: SHA256 hash of chunk content (primary key)
|
||||||
- `Size`: Chunk size in bytes
|
- `Size`: Chunk size in bytes
|
||||||
|
|
||||||
Chunk sizes vary between `avgChunkSize/4` and `avgChunkSize*4` (2.5MB-40MB for the 10MB default average).
|
Chunk sizes vary between `avgChunkSize/4` and `avgChunkSize*4` (2.5MB-40MB for
|
||||||
|
the 10MB default average).
|
||||||
|
|
||||||
#### FileChunk (`database.FileChunk`)
|
#### FileChunk (`database.FileChunk`)
|
||||||
|
|
||||||
Maps files to their constituent chunks:
|
Maps files to their constituent chunks:
|
||||||
|
|
||||||
- `FileID`: Reference to the file
|
- `FileID`: Reference to the file
|
||||||
- `Idx`: Position of this chunk within the file (0-indexed)
|
- `Idx`: Position of this chunk within the file (0-indexed)
|
||||||
- `ChunkHash`: Reference to the chunk
|
- `ChunkHash`: Reference to the chunk
|
||||||
|
|
||||||
#### Blob (`database.Blob`)
|
#### Blob (`database.Blob`)
|
||||||
The final storage unit uploaded to S3. Contains many compressed and encrypted chunks:
|
|
||||||
|
The final storage unit uploaded to S3. Contains many compressed and encrypted
|
||||||
|
chunks:
|
||||||
|
|
||||||
- `ID`: UUID assigned at creation
|
- `ID`: UUID assigned at creation
|
||||||
- `Hash`: `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before compression and encryption (see [docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#blobs-directory-blobs))
|
- `Hash`: `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before
|
||||||
|
compression and encryption (see
|
||||||
|
[docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs))
|
||||||
- `UncompressedSize`: Total raw chunk data before compression
|
- `UncompressedSize`: Total raw chunk data before compression
|
||||||
- `CompressedSize`: Size after zstd compression and age encryption
|
- `CompressedSize`: Size after zstd compression and age encryption
|
||||||
- `CreatedTS`, `FinishedTS`, `UploadedTS`: Lifecycle timestamps
|
- `CreatedTS`, `FinishedTS`, `UploadedTS`: Lifecycle timestamps
|
||||||
|
|
||||||
Blob creation process:
|
Blob creation process:
|
||||||
|
|
||||||
1. Chunks are accumulated (up to MaxBlobSize, typically 10GB)
|
1. Chunks are accumulated (up to MaxBlobSize, typically 10GB)
|
||||||
2. As each chunk is added, its uncompressed bytes are fed to a running SHA-256
|
2. As each chunk is added, its uncompressed bytes are fed to a running SHA-256
|
||||||
3. Concurrently, the same bytes are compressed with zstd, then encrypted with age (recipients configured in config), and streamed to storage
|
3. Concurrently, the same bytes are compressed with zstd, then encrypted with
|
||||||
4. On finalize, the blob's name is the double SHA-256 of the uncompressed contents — `hex(SHA256(SHA256(...)))` — not a hash of the compressed, encrypted bytes
|
age (recipients configured in config), and written to a temporary file
|
||||||
5. Uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}`
|
4. On finalize, the blob's name is the double SHA-256 of the uncompressed
|
||||||
|
contents — `hex(SHA256(SHA256(...)))` — not a hash of the compressed,
|
||||||
|
encrypted bytes
|
||||||
|
5. The finished file is uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}` and
|
||||||
|
then deleted
|
||||||
|
|
||||||
|
A backup needs free temporary space, because each blob is written whole to a
|
||||||
|
temporary file before it is uploaded (up to about `blob_size_limit`; an rclone
|
||||||
|
destination that cannot stream uploads needs about twice that) and the metadata
|
||||||
|
export writes copies of the local index. Temporary files go to `$TMPDIR`
|
||||||
|
(default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to
|
||||||
|
`/var/tmp`.
|
||||||
|
|
||||||
#### BlobChunk (`database.BlobChunk`)
|
#### BlobChunk (`database.BlobChunk`)
|
||||||
|
|
||||||
Maps chunks to their position within blobs:
|
Maps chunks to their position within blobs:
|
||||||
|
|
||||||
- `BlobID`: Reference to the blob
|
- `BlobID`: Reference to the blob
|
||||||
- `ChunkHash`: Reference to the chunk
|
- `ChunkHash`: Reference to the chunk
|
||||||
- `Offset`: Byte offset within the uncompressed blob
|
- `Offset`: Byte offset within the uncompressed blob
|
||||||
- `Length`: Chunk size
|
- `Length`: Chunk size
|
||||||
|
|
||||||
#### Snapshot (`database.Snapshot`)
|
#### Snapshot (`database.Snapshot`)
|
||||||
|
|
||||||
Represents a point-in-time backup:
|
Represents a point-in-time backup:
|
||||||
- `ID`: Format is `{hostname}_{snapshot-name}_{RFC3339}` (e.g. `server1_home_2025-06-01T12:00:00Z`)
|
|
||||||
|
- `ID`: Format is `{hostname}_{snapshot-name}_{RFC3339}` (e.g.
|
||||||
|
`server1_home_2025-06-01T12:00:00Z`)
|
||||||
- Tracks file count, chunk count, blob count, sizes, compression ratio
|
- Tracks file count, chunk count, blob count, sizes, compression ratio
|
||||||
- `CompletedAt`: Null until snapshot finishes successfully
|
- `CompletedAt`: Null until snapshot finishes successfully
|
||||||
|
|
||||||
#### SnapshotFile / SnapshotBlob
|
#### SnapshotFile / SnapshotBlob
|
||||||
|
|
||||||
Join tables linking snapshots to their files and blobs.
|
Join tables linking snapshots to their files and blobs.
|
||||||
|
|
||||||
### Relationship Summary
|
### Relationship Summary
|
||||||
@@ -136,21 +175,27 @@ fx.New(
|
|||||||
### Key Type Instantiation Points
|
### Key Type Instantiation Points
|
||||||
|
|
||||||
#### 1. Config (`config.Config`)
|
#### 1. Config (`config.Config`)
|
||||||
|
|
||||||
- **Created by**: `config.Module` via `config.LoadConfig()`
|
- **Created by**: `config.Module` via `config.LoadConfig()`
|
||||||
- **When**: Application startup (fx DI)
|
- **When**: Application startup (fx DI)
|
||||||
- **Contains**: All configuration from YAML file (S3 credentials, encryption keys, paths, etc.)
|
- **Contains**: All configuration from YAML file (S3 credentials, encryption
|
||||||
|
keys, paths, etc.)
|
||||||
|
|
||||||
#### 2. Database (`database.DB`)
|
#### 2. Database (`database.DB`)
|
||||||
|
|
||||||
- **Created by**: `database.Module` via `database.New()`
|
- **Created by**: `database.Module` via `database.New()`
|
||||||
- **When**: Application startup (fx DI)
|
- **When**: Application startup (fx DI)
|
||||||
- **Contains**: SQLite connection, path reference
|
- **Contains**: SQLite connection, path reference
|
||||||
|
|
||||||
#### 3. Repositories (`database.Repositories`)
|
#### 3. Repositories (`database.Repositories`)
|
||||||
|
|
||||||
- **Created by**: `database.Module` via `database.NewRepositories()`
|
- **Created by**: `database.Module` via `database.NewRepositories()`
|
||||||
- **When**: Application startup (fx DI)
|
- **When**: Application startup (fx DI)
|
||||||
- **Contains**: All repository interfaces (Files, Chunks, Blobs, Snapshots, etc.)
|
- **Contains**: All repository interfaces (Files, Chunks, Blobs, Snapshots,
|
||||||
|
etc.)
|
||||||
|
|
||||||
#### 4. Vaultik (`vaultik.Vaultik`)
|
#### 4. Vaultik (`vaultik.Vaultik`)
|
||||||
|
|
||||||
- **Created by**: `vaultik.New(VaultikParams)`
|
- **Created by**: `vaultik.New(VaultikParams)`
|
||||||
- **When**: Application startup (fx DI)
|
- **When**: Application startup (fx DI)
|
||||||
- **Contains**: All dependencies for backup operations
|
- **Contains**: All dependencies for backup operations
|
||||||
@@ -172,11 +217,13 @@ type Vaultik struct {
|
|||||||
```
|
```
|
||||||
|
|
||||||
#### 5. SnapshotManager (`snapshot.SnapshotManager`)
|
#### 5. SnapshotManager (`snapshot.SnapshotManager`)
|
||||||
|
|
||||||
- **Created by**: `snapshot.Module` via `snapshot.NewSnapshotManager()`
|
- **Created by**: `snapshot.Module` via `snapshot.NewSnapshotManager()`
|
||||||
- **When**: Application startup (fx DI)
|
- **When**: Application startup (fx DI)
|
||||||
- **Responsibility**: Creates/completes snapshots, exports metadata to S3
|
- **Responsibility**: Creates/completes snapshots, exports metadata to S3
|
||||||
|
|
||||||
#### 6. Scanner (`snapshot.Scanner`)
|
#### 6. Scanner (`snapshot.Scanner`)
|
||||||
|
|
||||||
- **Created by**: `ScannerFactory(ScannerParams)`
|
- **Created by**: `ScannerFactory(ScannerParams)`
|
||||||
- **When**: Each `CreateSnapshot()` call
|
- **When**: Each `CreateSnapshot()` call
|
||||||
- **Contains**: Chunker, Packer, progress reporter
|
- **Contains**: Chunker, Packer, progress reporter
|
||||||
@@ -190,20 +237,22 @@ scanner := v.ScannerFactory(snapshot.ScannerParams{
|
|||||||
```
|
```
|
||||||
|
|
||||||
#### 7. Chunker (`chunker.Chunker`)
|
#### 7. Chunker (`chunker.Chunker`)
|
||||||
|
|
||||||
- **Created by**: `chunker.NewChunker(avgChunkSize)`
|
- **Created by**: `chunker.NewChunker(avgChunkSize)`
|
||||||
- **When**: Inside `snapshot.NewScanner()`
|
- **When**: Inside `snapshot.NewScanner()`
|
||||||
- **Configuration**:
|
- **Configuration**:
|
||||||
- `avgChunkSize`: From config (default 10MB)
|
- `avgChunkSize`: From config (default 10MB)
|
||||||
- `minChunkSize`: avgChunkSize / 4
|
- `minChunkSize`: avgChunkSize / 4
|
||||||
- `maxChunkSize`: avgChunkSize * 4
|
- `maxChunkSize`: avgChunkSize \* 4
|
||||||
|
|
||||||
#### 8. Packer (`blob.Packer`)
|
#### 8. Packer (`blob.Packer`)
|
||||||
|
|
||||||
- **Created by**: `blob.NewPacker(PackerConfig)`
|
- **Created by**: `blob.NewPacker(PackerConfig)`
|
||||||
- **When**: Inside `snapshot.NewScanner()`
|
- **When**: Inside `snapshot.NewScanner()`
|
||||||
- **Configuration**:
|
- **Configuration**:
|
||||||
- `MaxBlobSize`: Maximum blob size before finalization (typically 10GB)
|
- `MaxBlobSize`: Maximum blob size before finalization (typically 10GB)
|
||||||
- `CompressionLevel`: zstd level (1-19)
|
- `CompressionLevel`: zstd level (1-19)
|
||||||
- `Recipients`: age public keys for encryption
|
- `Recipients`: age public keys for encryption
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// snapshot/scanner.go: NewScanner()
|
// snapshot/scanner.go: NewScanner()
|
||||||
@@ -220,17 +269,22 @@ packer, err := blob.NewPacker(packerCfg)
|
|||||||
## Module Responsibilities
|
## Module Responsibilities
|
||||||
|
|
||||||
### `internal/cli`
|
### `internal/cli`
|
||||||
Entry point for fx application. Combines all modules and handles signal interrupts.
|
|
||||||
|
Entry point for fx application. Combines all modules and handles signal
|
||||||
|
interrupts.
|
||||||
|
|
||||||
Key functions:
|
Key functions:
|
||||||
|
|
||||||
- `NewApp(AppOptions)` → Creates fx.App with all modules
|
- `NewApp(AppOptions)` → Creates fx.App with all modules
|
||||||
- `RunApp(ctx, app)` → Starts app, handles graceful shutdown
|
- `RunApp(ctx, app)` → Starts app, handles graceful shutdown
|
||||||
- `RunWithApp(ctx, opts)` → Convenience wrapper
|
- `RunWithApp(ctx, opts)` → Convenience wrapper
|
||||||
|
|
||||||
### `internal/vaultik`
|
### `internal/vaultik`
|
||||||
|
|
||||||
Main orchestrator containing all dependencies and command implementations.
|
Main orchestrator containing all dependencies and command implementations.
|
||||||
|
|
||||||
Key methods:
|
Key methods:
|
||||||
|
|
||||||
- `New(VaultikParams)` → Constructor (fx DI)
|
- `New(VaultikParams)` → Constructor (fx DI)
|
||||||
- `CreateSnapshot(opts)` → Main backup operation
|
- `CreateSnapshot(opts)` → Main backup operation
|
||||||
- `ListSnapshots(jsonOutput)` → List available snapshots
|
- `ListSnapshots(jsonOutput)` → List available snapshots
|
||||||
@@ -238,27 +292,34 @@ Key methods:
|
|||||||
- `PurgeSnapshots(...)` → Remove old snapshots
|
- `PurgeSnapshots(...)` → Remove old snapshots
|
||||||
|
|
||||||
### `internal/chunker`
|
### `internal/chunker`
|
||||||
|
|
||||||
Content-defined chunking using FastCDC algorithm.
|
Content-defined chunking using FastCDC algorithm.
|
||||||
|
|
||||||
Key types:
|
Key types:
|
||||||
|
|
||||||
- `Chunk` → Hash, Data, Offset, Size
|
- `Chunk` → Hash, Data, Offset, Size
|
||||||
- `Chunker` → avgChunkSize, minChunkSize, maxChunkSize
|
- `Chunker` → avgChunkSize, minChunkSize, maxChunkSize
|
||||||
|
|
||||||
Key methods:
|
Key methods:
|
||||||
|
|
||||||
- `NewChunker(avgChunkSize)` → Constructor
|
- `NewChunker(avgChunkSize)` → Constructor
|
||||||
- `ChunkReaderStreaming(reader, callback)` → Stream chunks with callback (preferred)
|
- `ChunkReaderStreaming(reader, callback)` → Stream chunks with callback
|
||||||
|
(preferred)
|
||||||
- `ChunkReader(reader)` → Return all chunks at once (memory-intensive)
|
- `ChunkReader(reader)` → Return all chunks at once (memory-intensive)
|
||||||
|
|
||||||
### `internal/blob`
|
### `internal/blob`
|
||||||
|
|
||||||
Blob packing: accumulates chunks, compresses, encrypts, tracks metadata.
|
Blob packing: accumulates chunks, compresses, encrypts, tracks metadata.
|
||||||
|
|
||||||
Key types:
|
Key types:
|
||||||
|
|
||||||
- `Packer` → Thread-safe blob accumulator
|
- `Packer` → Thread-safe blob accumulator
|
||||||
- `ChunkRef` → Hash + Data for adding to packer
|
- `ChunkRef` → Hash + Data for adding to packer
|
||||||
- `FinishedBlob` → Completed blob ready for upload
|
- `FinishedBlob` → Completed blob ready for upload
|
||||||
- `BlobWithReader` → FinishedBlob + io.Reader for streaming upload
|
- `BlobWithReader` → FinishedBlob + io.Reader for streaming upload
|
||||||
|
|
||||||
Key methods:
|
Key methods:
|
||||||
|
|
||||||
- `NewPacker(PackerConfig)` → Constructor
|
- `NewPacker(PackerConfig)` → Constructor
|
||||||
- `AddChunk(ChunkRef)` → Add chunk to current blob
|
- `AddChunk(ChunkRef)` → Add chunk to current blob
|
||||||
- `FinalizeBlob()` → Compress, encrypt, hash current blob
|
- `FinalizeBlob()` → Compress, encrypt, hash current blob
|
||||||
@@ -268,35 +329,48 @@ Key methods:
|
|||||||
### `internal/snapshot`
|
### `internal/snapshot`
|
||||||
|
|
||||||
#### Scanner
|
#### Scanner
|
||||||
|
|
||||||
Orchestrates the backup process for a directory.
|
Orchestrates the backup process for a directory.
|
||||||
|
|
||||||
Key methods:
|
Key methods:
|
||||||
|
|
||||||
- `NewScanner(ScannerConfig)` → Constructor (creates Chunker + Packer)
|
- `NewScanner(ScannerConfig)` → Constructor (creates Chunker + Packer)
|
||||||
- `Scan(ctx, path, snapshotID)` → Main scan operation
|
- `Scan(ctx, path, snapshotID)` → Main scan operation
|
||||||
|
|
||||||
Scan phases:
|
Scan phases:
|
||||||
1. **Phase 0**: Detect deleted files from previous snapshots
|
|
||||||
2. **Phase 1**: Walk directory, identify files needing processing
|
1. **Phase 1**: Walk directory, identify files needing processing
|
||||||
|
2. **Phase 1b**: Count as deleted the files that the previous snapshot of the
|
||||||
|
same name lists, the walk did not find, and are gone from disk; a file that
|
||||||
|
is excluded, or inside an excluded directory, is not counted
|
||||||
3. **Phase 2**: Process files (chunk → pack → upload)
|
3. **Phase 2**: Process files (chunk → pack → upload)
|
||||||
|
|
||||||
#### SnapshotManager
|
#### SnapshotManager
|
||||||
|
|
||||||
Manages snapshot lifecycle and metadata export.
|
Manages snapshot lifecycle and metadata export.
|
||||||
|
|
||||||
Key methods:
|
Key methods:
|
||||||
|
|
||||||
- `CreateSnapshot(ctx, hostname, version, commit)` → Create snapshot record
|
- `CreateSnapshot(ctx, hostname, version, commit)` → Create snapshot record
|
||||||
- `PopulateSnapshotBlobs(ctx, snapshotID)` → Record every blob the snapshot references
|
- `PopulateSnapshotBlobs(ctx, snapshotID)` → Record every blob the snapshot
|
||||||
|
references
|
||||||
- `ExportSnapshotMetadata(ctx, dbPath, snapshotID)` → Export to S3
|
- `ExportSnapshotMetadata(ctx, dbPath, snapshotID)` → Export to S3
|
||||||
- `MarkSnapshotComplete(ctx, snapshotID)` → Record completion, only after a successful export
|
- `MarkSnapshotComplete(ctx, snapshotID)` → Record completion, only after a
|
||||||
- `CompleteSnapshot(ctx, snapshotID)` → Convenience: populate blobs, then mark complete (no export between)
|
successful export
|
||||||
|
- `CompleteSnapshot(ctx, snapshotID)` → Convenience: populate blobs, then mark
|
||||||
|
complete (no export between)
|
||||||
|
|
||||||
### `internal/database`
|
### `internal/database`
|
||||||
|
|
||||||
SQLite database for local index. Single-writer mode for thread safety.
|
SQLite database for local index. Single-writer mode for thread safety.
|
||||||
|
|
||||||
Key types:
|
Key types:
|
||||||
|
|
||||||
- `DB` → Database connection wrapper
|
- `DB` → Database connection wrapper
|
||||||
- `Repositories` → Collection of all repository interfaces
|
- `Repositories` → Collection of all repository interfaces
|
||||||
|
|
||||||
Repository interfaces:
|
Repository interfaces:
|
||||||
|
|
||||||
- `FilesRepository` → CRUD for File records
|
- `FilesRepository` → CRUD for File records
|
||||||
- `ChunksRepository` → CRUD for Chunk records
|
- `ChunksRepository` → CRUD for Chunk records
|
||||||
- `BlobsRepository` → CRUD for Blob records
|
- `BlobsRepository` → CRUD for Blob records
|
||||||
@@ -307,6 +381,8 @@ Repository interfaces:
|
|||||||
|
|
||||||
```
|
```
|
||||||
CreateSnapshot(opts)
|
CreateSnapshot(opts)
|
||||||
|
│
|
||||||
|
├─► markDestination() // Check the marker (see Storage Layout in S3), then write it
|
||||||
│
|
│
|
||||||
├─► PruneDatabase() // Critical: avoid dedup errors
|
├─► PruneDatabase() // Critical: avoid dedup errors
|
||||||
│
|
│
|
||||||
@@ -316,13 +392,13 @@ CreateSnapshot(opts)
|
|||||||
│ │
|
│ │
|
||||||
│ ├─► scanner.Scan(ctx, path, snapshotID)
|
│ ├─► scanner.Scan(ctx, path, snapshotID)
|
||||||
│ │ │
|
│ │ │
|
||||||
│ │ ├─► Phase 0: detectDeletedFiles()
|
|
||||||
│ │ │
|
|
||||||
│ │ ├─► Phase 1: scanPhase()
|
│ │ ├─► Phase 1: scanPhase()
|
||||||
│ │ │ Walk directory
|
│ │ │ Walk directory
|
||||||
│ │ │ Check file metadata changes
|
│ │ │ Check file metadata changes
|
||||||
│ │ │ Build list of files to process
|
│ │ │ Build list of files to process
|
||||||
│ │ │
|
│ │ │
|
||||||
|
│ │ ├─► Phase 1b: detectDeletedFiles()
|
||||||
|
│ │ │
|
||||||
│ │ └─► Phase 2: processPhase()
|
│ │ └─► Phase 2: processPhase()
|
||||||
│ │ For each file:
|
│ │ For each file:
|
||||||
│ │ chunker.ChunkReaderStreaming()
|
│ │ chunker.ChunkReaderStreaming()
|
||||||
@@ -335,10 +411,10 @@ CreateSnapshot(opts)
|
|||||||
│ │
|
│ │
|
||||||
│ └─► Accumulate statistics
|
│ └─► Accumulate statistics
|
||||||
│
|
│
|
||||||
├─► SnapshotManager.UpdateSnapshotStatsExtended()
|
|
||||||
│
|
|
||||||
├─► SnapshotManager.PopulateSnapshotBlobs() // record referenced blobs
|
├─► SnapshotManager.PopulateSnapshotBlobs() // record referenced blobs
|
||||||
│
|
│
|
||||||
|
├─► SnapshotManager.UpdateSnapshotStatsExtended()
|
||||||
|
│
|
||||||
├─► SnapshotManager.ExportSnapshotMetadata()
|
├─► SnapshotManager.ExportSnapshotMetadata()
|
||||||
│ │
|
│ │
|
||||||
│ ├─► Copy database to temp file
|
│ ├─► Copy database to temp file
|
||||||
@@ -353,16 +429,23 @@ CreateSnapshot(opts)
|
|||||||
|
|
||||||
## Deduplication Strategy
|
## Deduplication Strategy
|
||||||
|
|
||||||
1. **File-level**: Files unchanged since last backup are skipped (metadata comparison: size, mtime, mode, uid, gid), unless the file lists a chunk that no uploaded blob holds; such a file is re-chunked
|
1. **File-level**: Files and symlinks unchanged since last backup are skipped
|
||||||
|
(metadata comparison: size, mtime, mode, uid, gid, and a symlink's target),
|
||||||
|
unless the file lists a chunk that no uploaded blob holds; such a file is
|
||||||
|
re-chunked
|
||||||
|
|
||||||
2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash already exists in the database, the chunk data is not re-uploaded.
|
2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash
|
||||||
|
already exists in the database, the chunk data is not re-uploaded.
|
||||||
|
|
||||||
3. **Blob-level**: Blobs contain only unique chunks. Duplicate chunks within a blob are skipped.
|
3. **Blob-level**: Blobs contain only unique chunks. Duplicate chunks within a
|
||||||
|
blob are skipped.
|
||||||
|
|
||||||
## Storage Layout in S3
|
## Storage Layout in S3
|
||||||
|
|
||||||
```
|
```
|
||||||
bucket/
|
bucket/
|
||||||
|
├── vaultik-destination.txt # Marker written by every backup
|
||||||
|
│
|
||||||
├── blobs/
|
├── blobs/
|
||||||
│ └── {hash[0:2]}/
|
│ └── {hash[0:2]}/
|
||||||
│ └── {hash[2:4]}/
|
│ └── {hash[2:4]}/
|
||||||
@@ -374,15 +457,30 @@ bucket/
|
|||||||
└── manifest.json.zst # Blob list (for pruning/verification)
|
└── manifest.json.zst # Blob list (for pruning/verification)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
A destination that answers a look-up of `vaultik-destination.txt` with not found
|
||||||
|
is treated as not present while the local index holds snapshots stored there
|
||||||
|
(`checkDestinationMarker` in `internal/vaultik/destination_marker.go`):
|
||||||
|
`snapshot create` refuses to write to it, `prune`, `snapshot purge` and
|
||||||
|
`remote nuke` fail, and `snapshot list` and `snapshot remove` behave as for a
|
||||||
|
destination that cannot be listed. This keeps those commands from taking an
|
||||||
|
unplugged volume's empty mount point for a destination whose snapshots are all
|
||||||
|
gone. When the look-up fails for any reason other than not found, for example
|
||||||
|
when S3 refuses it to credentials that allow only PUT, the check is skipped, so
|
||||||
|
a host with such credentials does not notice an emptied destination; see
|
||||||
|
[docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#marker-file-vaultik-destinationtxt).
|
||||||
|
The `file://` backend never creates its destination directory, so a write to a
|
||||||
|
missing one fails.
|
||||||
|
|
||||||
The `{remote-key}` directory name is a one-way double SHA-256 hash of the human
|
The `{remote-key}` directory name is a one-way double SHA-256 hash of the human
|
||||||
snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never
|
snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never
|
||||||
written to the store as a directory name. See
|
written to the store as a directory name. See
|
||||||
[docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#remote-key-derivation) for the
|
[docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) for the
|
||||||
derivation and a worked example.
|
derivation and a worked example.
|
||||||
|
|
||||||
## Thread Safety
|
## Thread Safety
|
||||||
|
|
||||||
- `Packer`: Thread-safe via mutex. Multiple goroutines can call `AddChunk()`.
|
- `Packer`: Thread-safe via mutex. Multiple goroutines can call `AddChunk()`.
|
||||||
- `Scanner`: Uses `packerMu` mutex to coordinate blob finalization.
|
- `Scanner`: Uses `packerMu` mutex to coordinate blob finalization.
|
||||||
- `Database`: Single-writer mode (`MaxOpenConns=1`) ensures SQLite thread safety.
|
- `Database`: Single-writer mode (`MaxOpenConns=1`) ensures SQLite thread
|
||||||
|
safety.
|
||||||
- `Repositories.WithTx()`: Handles transaction lifecycle automatically.
|
- `Repositories.WithTx()`: Handles transaction lifecycle automatically.
|
||||||
+155
-56
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Vaultik uses a local SQLite database to track file metadata, chunk mappings, and blob associations during the backup process. This database serves as an index for incremental backups and enables efficient deduplication.
|
Vaultik uses a local SQLite database to track file metadata, chunk mappings, and
|
||||||
|
blob associations during the backup process. This database serves as an index
|
||||||
|
for incremental backups and enables efficient deduplication.
|
||||||
|
|
||||||
**Important Notes:**
|
**Important Notes:**
|
||||||
|
|
||||||
@@ -25,18 +27,23 @@ recorded `001.sql` as run, so it keeps the old schema and can become unusable;
|
|||||||
`vaultik database delete` followed by a full backup rebuilds it.
|
`vaultik database delete` followed by a full backup rebuilds it.
|
||||||
|
|
||||||
**After 1.0** each schema change is a new numbered file, so an existing local
|
**After 1.0** each schema change is a new numbered file, so an existing local
|
||||||
database is migrated the first time an updated vaultik opens it. A file that
|
database is migrated the first time an updated vaultik opens it. A file that has
|
||||||
has shipped in a release is never edited.
|
shipped in a release is never edited.
|
||||||
|
|
||||||
## Database Tables
|
## Database Tables
|
||||||
|
|
||||||
### 1. `files`
|
### 1. `files`
|
||||||
|
|
||||||
Stores metadata about files in the filesystem being backed up.
|
Stores metadata about files in the filesystem being backed up.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `id` (TEXT PRIMARY KEY) - UUID for the file record
|
- `id` (TEXT PRIMARY KEY) - UUID for the file record
|
||||||
- `path` (TEXT NOT NULL UNIQUE) - Absolute file path
|
- `path` (TEXT NOT NULL UNIQUE) - Absolute file path
|
||||||
- `mtime` (INTEGER NOT NULL) - Modification time as Unix timestamp
|
- `mtime` (INTEGER NOT NULL) - Modification time, whole seconds since the Unix
|
||||||
|
epoch
|
||||||
|
- `mtime_nsec` (INTEGER NOT NULL) - Nanoseconds within that second, 0 to
|
||||||
|
999999999
|
||||||
- `size` (INTEGER NOT NULL) - File size in bytes
|
- `size` (INTEGER NOT NULL) - File size in bytes
|
||||||
- `mode` (INTEGER NOT NULL) - Unix file permissions and type
|
- `mode` (INTEGER NOT NULL) - Unix file permissions and type
|
||||||
- `uid` (INTEGER NOT NULL) - User ID of file owner
|
- `uid` (INTEGER NOT NULL) - User ID of file owner
|
||||||
@@ -44,23 +51,30 @@ Stores metadata about files in the filesystem being backed up.
|
|||||||
- `link_target` (TEXT) - Symlink target path (NULL for regular files)
|
- `link_target` (TEXT) - Symlink target path (NULL for regular files)
|
||||||
|
|
||||||
**Indexes:**
|
**Indexes:**
|
||||||
|
|
||||||
- `idx_files_path` on `path` for efficient lookups
|
- `idx_files_path` on `path` for efficient lookups
|
||||||
|
|
||||||
**Purpose:** Tracks file metadata to detect changes between backup runs. Used for incremental backup decisions. The UUID primary key provides stable references that don't change if files are moved.
|
**Purpose:** Tracks file metadata to detect changes between backup runs. Used
|
||||||
|
for incremental backup decisions. The UUID primary key provides stable
|
||||||
|
references that don't change if files are moved.
|
||||||
|
|
||||||
### 2. `chunks`
|
### 2. `chunks`
|
||||||
|
|
||||||
Stores information about content-defined chunks created from files.
|
Stores information about content-defined chunks created from files.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `chunk_hash` (TEXT PRIMARY KEY) - SHA256 hash of chunk content
|
- `chunk_hash` (TEXT PRIMARY KEY) - SHA256 hash of chunk content
|
||||||
- `size` (INTEGER NOT NULL) - Chunk size in bytes
|
- `size` (INTEGER NOT NULL) - Chunk size in bytes
|
||||||
|
|
||||||
**Purpose:** Enables deduplication by tracking unique chunks across all files.
|
**Purpose:** Enables deduplication by tracking unique chunks across all files.
|
||||||
|
|
||||||
### 3. `file_chunks`
|
### 3. `file_chunks`
|
||||||
|
|
||||||
Maps files to their constituent chunks in order.
|
Maps files to their constituent chunks in order.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `file_id` (TEXT) - File ID (FK to files.id)
|
- `file_id` (TEXT) - File ID (FK to files.id)
|
||||||
- `idx` (INTEGER) - Chunk index within file (0-based)
|
- `idx` (INTEGER) - Chunk index within file (0-based)
|
||||||
- `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash)
|
- `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash)
|
||||||
@@ -69,35 +83,49 @@ Maps files to their constituent chunks in order.
|
|||||||
**Purpose:** Allows reconstruction of files from chunks during restore.
|
**Purpose:** Allows reconstruction of files from chunks during restore.
|
||||||
|
|
||||||
### 4. `chunk_files`
|
### 4. `chunk_files`
|
||||||
|
|
||||||
Reverse mapping showing which files contain each chunk.
|
Reverse mapping showing which files contain each chunk.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash)
|
- `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash)
|
||||||
- `file_id` (TEXT) - File ID (FK to files.id)
|
- `file_id` (TEXT) - File ID (FK to files.id)
|
||||||
- `file_offset` (INTEGER) - Byte offset of chunk within file
|
- `file_offset` (INTEGER) - Byte offset of chunk within file
|
||||||
- `length` (INTEGER) - Length of chunk in bytes
|
- `length` (INTEGER) - Length of chunk in bytes
|
||||||
- PRIMARY KEY (`chunk_hash`, `file_id`)
|
- PRIMARY KEY (`chunk_hash`, `file_id`)
|
||||||
|
|
||||||
**Purpose:** Supports efficient queries for chunk usage and deduplication statistics.
|
**Purpose:** Supports efficient queries for chunk usage and deduplication
|
||||||
|
statistics.
|
||||||
|
|
||||||
### 5. `blobs`
|
### 5. `blobs`
|
||||||
|
|
||||||
Stores information about packed, compressed, and encrypted blob files.
|
Stores information about packed, compressed, and encrypted blob files.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `id` (TEXT PRIMARY KEY) - UUID assigned when blob creation starts
|
- `id` (TEXT PRIMARY KEY) - UUID assigned when blob creation starts
|
||||||
- `blob_hash` (TEXT UNIQUE) - `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before compression and encryption (NULL until finalized); see [REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs)
|
- `blob_hash` (TEXT UNIQUE) - `hex(SHA256(SHA256(uncompressed blob contents)))`,
|
||||||
|
computed before compression and encryption (NULL until finalized); see
|
||||||
|
[REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs)
|
||||||
- `created_ts` (INTEGER NOT NULL) - Creation timestamp
|
- `created_ts` (INTEGER NOT NULL) - Creation timestamp
|
||||||
- `finished_ts` (INTEGER) - Finalization timestamp (NULL if in progress)
|
- `finished_ts` (INTEGER) - Finalization timestamp (NULL if in progress)
|
||||||
- `uncompressed_size` (INTEGER NOT NULL DEFAULT 0) - Total size of chunks before compression
|
- `uncompressed_size` (INTEGER NOT NULL DEFAULT 0) - Total size of chunks before
|
||||||
- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and encryption
|
compression
|
||||||
|
- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and
|
||||||
|
encryption. Once uploaded, the size of the object in storage: when the blob
|
||||||
|
was already stored, under another compression level or other recipients, this
|
||||||
|
can differ from the size of the local copy
|
||||||
- `uploaded_ts` (INTEGER) - Upload completion timestamp (NULL if not uploaded)
|
- `uploaded_ts` (INTEGER) - Upload completion timestamp (NULL if not uploaded)
|
||||||
|
|
||||||
**Purpose:** Tracks blob lifecycle from creation through upload. The UUID primary key allows immediate association of chunks with blobs.
|
**Purpose:** Tracks blob lifecycle from creation through upload. The UUID
|
||||||
|
primary key allows immediate association of chunks with blobs.
|
||||||
|
|
||||||
### 6. `blob_chunks`
|
### 6. `blob_chunks`
|
||||||
|
|
||||||
Maps chunks to the blobs that contain them.
|
Maps chunks to the blobs that contain them.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `blob_id` (TEXT) - Blob ID (FK to blobs.id)
|
- `blob_id` (TEXT) - Blob ID (FK to blobs.id)
|
||||||
- `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash)
|
- `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash)
|
||||||
- `offset` (INTEGER) - Byte offset of chunk within blob (before compression)
|
- `offset` (INTEGER) - Byte offset of chunk within blob (before compression)
|
||||||
@@ -107,32 +135,46 @@ Maps chunks to the blobs that contain them.
|
|||||||
**Purpose:** Enables chunk retrieval from blobs during restore operations.
|
**Purpose:** Enables chunk retrieval from blobs during restore operations.
|
||||||
|
|
||||||
### 7. `snapshots`
|
### 7. `snapshots`
|
||||||
|
|
||||||
Tracks backup snapshots.
|
Tracks backup snapshots.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: hostname-YYYYMMDD-HHMMSSZ)
|
|
||||||
|
- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: `hostname_name_timestamp`, e.g.
|
||||||
|
`server1_home_2025-06-01T12:00:00Z`: the hostname up to its first `.`, the
|
||||||
|
snapshot name, and an RFC 3339 UTC timestamp)
|
||||||
- `hostname` (TEXT) - Hostname where backup was created
|
- `hostname` (TEXT) - Hostname where backup was created
|
||||||
- `vaultik_version` (TEXT) - Version of Vaultik used
|
- `vaultik_version` (TEXT) - Version of Vaultik used
|
||||||
- `vaultik_git_revision` (TEXT) - Git revision of Vaultik used
|
- `vaultik_git_revision` (TEXT) - Git revision of Vaultik used
|
||||||
- `started_at` (INTEGER) - Start timestamp
|
- `started_at` (INTEGER) - Start timestamp
|
||||||
- `completed_at` (INTEGER) - Completion timestamp (NULL if in progress)
|
- `completed_at` (INTEGER) - Completion timestamp (NULL if in progress)
|
||||||
- `file_count` (INTEGER) - Number of files in snapshot
|
- `file_count` (INTEGER) - Number of files in snapshot
|
||||||
- `chunk_count` (INTEGER) - Number of unique chunks
|
- `chunk_count` (INTEGER) - Number of chunks this snapshot stored that were not
|
||||||
- `blob_count` (INTEGER) - Number of blobs referenced
|
stored before
|
||||||
|
- `new_chunk_size` (INTEGER) - Total size of those chunks before compression;
|
||||||
|
`snapshot list` shows it as NEW CHUNK SIZE
|
||||||
|
- `blob_count` (INTEGER) - Number of blobs this snapshot created
|
||||||
- `total_size` (INTEGER) - Total size of all files
|
- `total_size` (INTEGER) - Total size of all files
|
||||||
- `blob_size` (INTEGER) - Total size of all blobs (compressed)
|
- `uncompressed_chunk_size` (INTEGER) - Total size before compression of the
|
||||||
- `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced blobs
|
distinct chunks the snapshot's files reference, recorded when its backup ran;
|
||||||
|
`snapshot list` shows it as UNCOMPRESSED SIZE
|
||||||
|
- `blob_size` (INTEGER) - Total compressed size of all referenced blobs
|
||||||
|
- `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced
|
||||||
|
blobs
|
||||||
- `compression_ratio` (REAL) - Compression ratio achieved
|
- `compression_ratio` (REAL) - Compression ratio achieved
|
||||||
- `compression_level` (INTEGER) - Compression level used for this snapshot
|
- `compression_level` (INTEGER) - Compression level used for this snapshot
|
||||||
- `upload_bytes` (INTEGER) - Total bytes uploaded during this snapshot
|
- `upload_bytes` (INTEGER) - Total bytes uploaded during this snapshot
|
||||||
- `upload_duration_ms` (INTEGER) - Total milliseconds spent uploading to S3
|
- `upload_duration_ms` (INTEGER) - Total milliseconds spent uploading to S3
|
||||||
|
|
||||||
**Purpose:** Provides snapshot metadata and statistics including version tracking for compatibility.
|
**Purpose:** Provides snapshot metadata and statistics including version
|
||||||
|
tracking for compatibility.
|
||||||
|
|
||||||
### 8. `snapshot_files`
|
### 8. `snapshot_files`
|
||||||
|
|
||||||
Maps snapshots to the files they contain.
|
Maps snapshots to the files they contain.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id)
|
- `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id)
|
||||||
- `file_id` (TEXT) - File ID (FK to files.id)
|
- `file_id` (TEXT) - File ID (FK to files.id)
|
||||||
- PRIMARY KEY (`snapshot_id`, `file_id`)
|
- PRIMARY KEY (`snapshot_id`, `file_id`)
|
||||||
@@ -140,100 +182,147 @@ Maps snapshots to the files they contain.
|
|||||||
**Purpose:** Records which files are included in each snapshot.
|
**Purpose:** Records which files are included in each snapshot.
|
||||||
|
|
||||||
### 9. `snapshot_blobs`
|
### 9. `snapshot_blobs`
|
||||||
|
|
||||||
Maps snapshots to the blobs they reference.
|
Maps snapshots to the blobs they reference.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id)
|
- `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id)
|
||||||
- `blob_id` (TEXT) - Blob ID (FK to blobs.id)
|
- `blob_id` (TEXT) - Blob ID (FK to blobs.id)
|
||||||
- `blob_hash` (TEXT) - Denormalized blob hash for manifest generation
|
- `blob_hash` (TEXT) - Denormalized blob hash for manifest generation
|
||||||
- PRIMARY KEY (`snapshot_id`, `blob_id`)
|
- PRIMARY KEY (`snapshot_id`, `blob_id`)
|
||||||
|
|
||||||
**Purpose:** Tracks blob dependencies for snapshots and enables manifest generation.
|
**Purpose:** Tracks blob dependencies for snapshots and enables manifest
|
||||||
|
generation.
|
||||||
|
|
||||||
|
### 10. `snapshot_mount_points`
|
||||||
|
|
||||||
|
The directories at or below a configured path, the configured path itself
|
||||||
|
included, that a snapshot's backup found an entry in and, once it had listed
|
||||||
|
them, found on a different filesystem from their parent directory (a different
|
||||||
|
device number), as a mount point is. An automount point whose volume cannot be
|
||||||
|
mounted is not recorded, because the backup finds no entry in it.
|
||||||
|
|
||||||
|
**Columns:**
|
||||||
|
|
||||||
|
- `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id)
|
||||||
|
- `path` (TEXT) - Absolute path of the directory
|
||||||
|
- PRIMARY KEY (`snapshot_id`, `path`)
|
||||||
|
|
||||||
|
**Purpose:** Lets `snapshot create --prune` skip the prune when a backup does
|
||||||
|
not find a mount point that an earlier snapshot of the same name found, as when
|
||||||
|
the volume is not mounted.
|
||||||
|
|
||||||
|
### 11. `uploads`
|
||||||
|
|
||||||
### 10. `uploads`
|
|
||||||
Tracks blob upload metrics.
|
Tracks blob upload metrics.
|
||||||
|
|
||||||
**Columns:**
|
**Columns:**
|
||||||
|
|
||||||
- `blob_hash` (TEXT PRIMARY KEY) - Hash of uploaded blob
|
- `blob_hash` (TEXT PRIMARY KEY) - Hash of uploaded blob
|
||||||
- `snapshot_id` (TEXT NOT NULL) - The snapshot that triggered this upload (FK to snapshots.id)
|
- `snapshot_id` (TEXT NOT NULL) - The snapshot that triggered this upload (FK to
|
||||||
|
snapshots.id)
|
||||||
- `uploaded_at` (INTEGER) - Upload timestamp
|
- `uploaded_at` (INTEGER) - Upload timestamp
|
||||||
- `size` (INTEGER) - Size of uploaded blob
|
- `size` (INTEGER) - Size of uploaded blob
|
||||||
- `duration_ms` (INTEGER) - Upload duration in milliseconds
|
- `duration_ms` (INTEGER) - Upload duration in milliseconds
|
||||||
|
|
||||||
**Purpose:** Performance monitoring and tracking which blobs were newly created (uploaded) during each snapshot.
|
**Purpose:** Performance monitoring and tracking which blobs were newly created
|
||||||
|
(uploaded) during each snapshot.
|
||||||
|
|
||||||
## Data Flow and Operations
|
## Data Flow and Operations
|
||||||
|
|
||||||
### 1. Backup Process
|
### 1. Backup Process
|
||||||
|
|
||||||
1. **File Scanning**
|
1. **File Scanning**
|
||||||
- `INSERT OR REPLACE INTO files` - Update file metadata
|
- `INSERT OR REPLACE INTO files` - Update file metadata
|
||||||
- `SELECT * FROM files WHERE path = ?` - Check if file has changed
|
- `SELECT * FROM files WHERE path = ?` - Check if file has changed
|
||||||
- `INSERT INTO snapshot_files` - Add file to current snapshot
|
- `INSERT INTO snapshot_files` - Add file to current snapshot
|
||||||
|
- `INSERT OR IGNORE INTO snapshot_mount_points` - Record each directory on a
|
||||||
|
different filesystem from its parent that the walk found an entry in
|
||||||
|
|
||||||
2. **Chunking** (for changed files)
|
2. **Chunking** (for changed files)
|
||||||
- `INSERT OR IGNORE INTO chunks` - Store new chunks
|
- `INSERT OR IGNORE INTO chunks` - Store new chunks
|
||||||
- `INSERT INTO file_chunks` - Map chunks to file
|
- `INSERT INTO file_chunks` - Map chunks to file
|
||||||
- `INSERT INTO chunk_files` - Create reverse mapping
|
- `INSERT INTO chunk_files` - Create reverse mapping
|
||||||
|
|
||||||
3. **Blob Packing**
|
3. **Blob Packing**
|
||||||
- `INSERT INTO blobs` - Create blob record with UUID (blob_hash NULL)
|
- `INSERT INTO blobs` - Create blob record with UUID (blob_hash NULL)
|
||||||
- `INSERT INTO blob_chunks` - Associate chunks with blob immediately
|
- `INSERT INTO blob_chunks` - Associate chunks with blob immediately
|
||||||
- `UPDATE blobs SET blob_hash = ?, finished_ts = ?` - Finalize blob after packing
|
- `UPDATE blobs SET blob_hash = ?, finished_ts = ?` - Finalize blob after
|
||||||
|
packing
|
||||||
|
|
||||||
4. **Upload**
|
4. **Upload**
|
||||||
- `UPDATE blobs SET uploaded_ts = ?` - Mark blob as uploaded
|
- `UPDATE blobs SET uploaded_ts = ?, compressed_size = ?` - Mark blob as
|
||||||
- `INSERT INTO uploads` - Record upload metrics with snapshot_id
|
uploaded, with the size of the object in storage (the upload is skipped
|
||||||
- `INSERT INTO snapshot_blobs` - Associate blob with snapshot
|
when the blob is already stored)
|
||||||
|
- `INSERT INTO uploads` - Record upload metrics with snapshot_id
|
||||||
|
- `INSERT INTO snapshot_blobs` - Associate blob with snapshot
|
||||||
|
|
||||||
5. **Snapshot Completion**
|
5. **Snapshot Completion**
|
||||||
- `UPDATE snapshots SET completed_at = ?, stats...` - Finalize snapshot
|
- `UPDATE snapshots SET completed_at = ?, stats...` - Finalize snapshot
|
||||||
- Generate and upload blob manifest from `snapshot_blobs`
|
- Generate and upload blob manifest from `snapshot_blobs`
|
||||||
|
|
||||||
### 2. Incremental Backup
|
### 2. Incremental Backup
|
||||||
|
|
||||||
1. **Change Detection**
|
1. **Change Detection**
|
||||||
- `SELECT * FROM files WHERE path = ?` - Get previous file metadata
|
- `SELECT * FROM files WHERE path = ?` - Get previous file metadata
|
||||||
- Compare mtime, size, mode to detect changes
|
- Compare mtime, size, mode to detect changes
|
||||||
- Re-chunk a file that lists a chunk no uploaded blob holds, even when its metadata is unchanged
|
- Re-chunk a file that lists a chunk no uploaded blob holds, even when its
|
||||||
- Skip unchanged files but still add to `snapshot_files`
|
metadata is unchanged
|
||||||
|
- Skip unchanged files but still add to `snapshot_files`
|
||||||
|
|
||||||
2. **Chunk Reuse**
|
2. **Chunk Reuse**
|
||||||
- `SELECT * FROM blob_chunks WHERE chunk_hash = ?` - Find existing chunks
|
- `SELECT * FROM blob_chunks WHERE chunk_hash = ?` - Find existing chunks
|
||||||
- `INSERT INTO snapshot_blobs` - Reference existing blobs for unchanged files
|
- `INSERT INTO snapshot_blobs` - Reference existing blobs for unchanged
|
||||||
|
files
|
||||||
|
|
||||||
### 3. Snapshot Metadata Export
|
### 3. Snapshot Metadata Export
|
||||||
|
|
||||||
After a snapshot is completed:
|
After a snapshot is completed:
|
||||||
|
|
||||||
1. Copy database to temporary file
|
1. Copy database to temporary file
|
||||||
2. Clean temporary database to contain only current snapshot data
|
2. Clean temporary database to contain only current snapshot data
|
||||||
3. VACUUM the trimmed database so deleted rows leave no pages behind
|
3. VACUUM the trimmed database so deleted rows leave no pages behind
|
||||||
4. Compress with zstd and encrypt with age
|
4. Compress with zstd and encrypt with age
|
||||||
5. Upload to S3 as `metadata/{remote-key}/db.zst.age`
|
5. Upload to S3 as `metadata/{remote-key}/db.zst.age`
|
||||||
6. Generate blob manifest and upload as `metadata/{remote-key}/manifest.json.zst`
|
6. Generate blob manifest and upload as
|
||||||
|
`metadata/{remote-key}/manifest.json.zst`
|
||||||
|
|
||||||
The `{remote-key}` directory name is a one-way hash of the human snapshot ID, so the ID is never written to the store in plaintext. The hash uses no secret, so a guessed hostname and snapshot name can still be confirmed against a listing; see [REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) and its [Accepted Risks](REPOSTRUCTURE.md#accepted-risks).
|
The `{remote-key}` directory name is a one-way hash of the human snapshot ID, so
|
||||||
|
the ID is never written to the store in plaintext. The hash uses no secret, so a
|
||||||
|
guessed hostname and snapshot name can still be confirmed against a listing; see
|
||||||
|
[REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) and its
|
||||||
|
[Accepted Risks](REPOSTRUCTURE.md#accepted-risks).
|
||||||
|
|
||||||
### 4. Restore Process
|
### 4. Restore Process
|
||||||
|
|
||||||
The restore process doesn't use the local database. Instead:
|
The restore process doesn't use the local database. Instead:
|
||||||
1. Downloads snapshot metadata from S3
|
|
||||||
2. Downloads required blobs based on manifest
|
1. Downloads and decrypts the snapshot's metadata database (`db.zst.age`) from
|
||||||
|
S3
|
||||||
|
2. Downloads the blobs holding the chunks of the files being restored, found
|
||||||
|
through that database's `blob_chunks` table; the manifest is not read
|
||||||
3. Reconstructs files from decrypted and decompressed chunks
|
3. Reconstructs files from decrypted and decompressed chunks
|
||||||
|
|
||||||
### 5. Pruning
|
### 5. Pruning
|
||||||
|
|
||||||
1. **Identify Unreferenced Blobs**
|
1. **Identify Unreferenced Blobs**
|
||||||
- Query blobs not referenced by any remaining snapshot
|
- Query blobs not referenced by any remaining snapshot
|
||||||
- Delete from S3 and local database
|
- Delete from S3, once older than `prune_grace_period`, and from the local
|
||||||
|
database
|
||||||
|
2. **Delete Metadata Directories With No Manifest**
|
||||||
|
- Delete each directory under `metadata/` that has no `manifest.json.zst`
|
||||||
|
and no local snapshot record, once every object in it is older than
|
||||||
|
`prune_grace_period`
|
||||||
|
|
||||||
### 6. Incomplete Snapshot Cleanup
|
### 6. Incomplete Snapshot Cleanup
|
||||||
|
|
||||||
Before each backup:
|
Before each backup:
|
||||||
|
|
||||||
1. Query incomplete snapshots (where `completed_at IS NULL`)
|
1. Query incomplete snapshots (where `completed_at IS NULL`)
|
||||||
2. Check if metadata exists in S3
|
2. Delete each one and all its associations, without checking S3 for its
|
||||||
3. If no metadata, delete snapshot and all associations
|
metadata
|
||||||
4. Clean up orphaned files, chunks, and blobs
|
3. Clean up orphaned files, chunks, and blobs
|
||||||
|
|
||||||
## Repository Pattern
|
## Repository Pattern
|
||||||
|
|
||||||
@@ -249,11 +338,13 @@ Vaultik uses a repository pattern for database access:
|
|||||||
- `UploadRepository` - Track blob upload metrics
|
- `UploadRepository` - Track blob upload metrics
|
||||||
|
|
||||||
Each repository provides methods like:
|
Each repository provides methods like:
|
||||||
|
|
||||||
- `Create()` - Insert new record
|
- `Create()` - Insert new record
|
||||||
- `GetByID()` / `GetByPath()` / `GetByHash()` - Retrieve records
|
- `GetByID()` / `GetByPath()` / `GetByHash()` - Retrieve records
|
||||||
- `Update()` - Update existing records
|
- `Update()` - Update existing records
|
||||||
- `Delete()` - Remove records
|
- `Delete()` - Remove records
|
||||||
- Specialized queries for each entity type (e.g., `DeleteOrphaned()`, `GetIncompleteByHostname()`)
|
- Specialized queries for each entity type (e.g., `DeleteOrphaned()`,
|
||||||
|
`GetIncompleteByHostname()`)
|
||||||
|
|
||||||
## Transaction Management
|
## Transaction Management
|
||||||
|
|
||||||
@@ -266,6 +357,7 @@ err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
|||||||
```
|
```
|
||||||
|
|
||||||
This ensures consistency, especially important for operations like:
|
This ensures consistency, especially important for operations like:
|
||||||
|
|
||||||
- Creating file-chunk mappings
|
- Creating file-chunk mappings
|
||||||
- Associating chunks with blobs
|
- Associating chunks with blobs
|
||||||
- Updating snapshot statistics
|
- Updating snapshot statistics
|
||||||
@@ -273,18 +365,25 @@ This ensures consistency, especially important for operations like:
|
|||||||
## Performance Considerations
|
## Performance Considerations
|
||||||
|
|
||||||
1. **Indexes**:
|
1. **Indexes**:
|
||||||
- Primary keys are automatically indexed
|
- Primary keys are automatically indexed
|
||||||
- `idx_files_path` on `files(path)` for efficient file lookups
|
- `idx_files_path` on `files(path)` for efficient file lookups
|
||||||
|
|
||||||
2. **Prepared Statements**: All queries use prepared statements for performance and security
|
2. **Prepared Statements**: All queries use prepared statements for performance
|
||||||
|
and security
|
||||||
|
|
||||||
3. **Batch Operations**: Where possible, operations are batched within transactions
|
3. **Batch Operations**: Where possible, operations are batched within
|
||||||
|
transactions
|
||||||
|
|
||||||
4. **Write-Ahead Logging**: The local index runs in SQLite WAL mode with a 10-second busy timeout, so a read-only command such as `snapshot list` can read it while a backup writes to it. Committed rows can sit in the `-wal` file beside the index until a checkpoint, so the metadata export copies the index through SQLite (`VACUUM INTO`), not as a file
|
4. **Write-Ahead Logging**: The local index runs in SQLite WAL mode with a
|
||||||
|
10-second busy timeout, so a read-only command such as `snapshot list` can
|
||||||
|
read it while a backup writes to it. Committed rows can sit in the `-wal`
|
||||||
|
file beside the index until a checkpoint, so the metadata export copies the
|
||||||
|
index through SQLite (`VACUUM INTO`), not as a file
|
||||||
|
|
||||||
## Data Integrity
|
## Data Integrity
|
||||||
|
|
||||||
1. **Foreign Keys**: Enforced through CASCADE DELETE and application-level repository methods
|
1. **Foreign Keys**: Enforced through CASCADE DELETE and application-level
|
||||||
|
repository methods
|
||||||
2. **Unique Constraints**: Chunk hashes, file paths, and blob hashes are unique
|
2. **Unique Constraints**: Chunk hashes, file paths, and blob hashes are unique
|
||||||
3. **Null Handling**: Nullable fields clearly indicate in-progress operations
|
3. **Null Handling**: Nullable fields clearly indicate in-progress operations
|
||||||
4. **Timestamp Tracking**: All major operations record timestamps for auditing
|
4. **Timestamp Tracking**: All major operations record timestamps for auditing
|
||||||
+239
-54
@@ -1,10 +1,13 @@
|
|||||||
# Vaultik S3 Repository Structure
|
# Vaultik S3 Repository Structure
|
||||||
|
|
||||||
This document describes the structure and organization of data stored in the S3 bucket by Vaultik.
|
This document describes the structure and organization of data stored in the S3
|
||||||
|
bucket by Vaultik.
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components:
|
Vaultik stores all backup data in an S3-compatible object store. The repository
|
||||||
|
consists of two main components, plus a marker file:
|
||||||
|
|
||||||
1. **Blobs** - The actual backup data (content-addressed, encrypted)
|
1. **Blobs** - The actual backup data (content-addressed, encrypted)
|
||||||
2. **Metadata** - Snapshot information and manifests (partially encrypted)
|
2. **Metadata** - Snapshot information and manifests (partially encrypted)
|
||||||
|
|
||||||
@@ -12,6 +15,7 @@ Vaultik stores all backup data in an S3-compatible object store. The repository
|
|||||||
|
|
||||||
```
|
```
|
||||||
<bucket>/<prefix>/
|
<bucket>/<prefix>/
|
||||||
|
├── vaultik-destination.txt
|
||||||
├── blobs/
|
├── blobs/
|
||||||
│ └── <hash[0:2]>/
|
│ └── <hash[0:2]>/
|
||||||
│ └── <hash[2:4]>/
|
│ └── <hash[2:4]>/
|
||||||
@@ -22,114 +26,208 @@ Vaultik stores all backup data in an S3-compatible object store. The repository
|
|||||||
└── manifest.json.zst
|
└── manifest.json.zst
|
||||||
```
|
```
|
||||||
|
|
||||||
The metadata subdirectory is named with the **remote key**, a one-way hash of the snapshot ID, not with the human-readable snapshot ID itself. See [Remote Key Derivation](#remote-key-derivation).
|
The metadata subdirectory is named with the **remote key**, a one-way hash of
|
||||||
|
the snapshot ID, not with the human-readable snapshot ID itself. See
|
||||||
|
[Remote Key Derivation](#remote-key-derivation).
|
||||||
|
|
||||||
|
## Marker File (`vaultik-destination.txt`)
|
||||||
|
|
||||||
|
Every backup writes this file at the root before it uploads anything. It holds
|
||||||
|
one fixed line of plain text and names no host, path or time. While the local
|
||||||
|
index holds snapshots stored there, a destination that answers a look-up of the
|
||||||
|
marker with not found is treated as not present: `snapshot create` refuses to
|
||||||
|
write to it, and `prune`, `snapshot purge`, `snapshot remove`, `snapshot list`
|
||||||
|
and `remote nuke` behave as for a destination that cannot be listed. An
|
||||||
|
unplugged volume leaves an empty directory at its mount point, and without the
|
||||||
|
marker that directory would read as a destination whose snapshots are all gone.
|
||||||
|
`remote nuke` deletes the marker last.
|
||||||
|
|
||||||
|
When the look-up of the marker fails for any reason other than not found, the
|
||||||
|
check is skipped and the command goes on. S3 refuses it on every run to
|
||||||
|
credentials that allow only PUT, so a host with such credentials does not notice
|
||||||
|
a destination emptied since its last backup, and its next backup would leave out
|
||||||
|
the data its local index records as already stored. After the destination is
|
||||||
|
emptied, run `vaultik database delete` on such a host before it backs up again.
|
||||||
|
|
||||||
## Blobs Directory (`blobs/`)
|
## Blobs Directory (`blobs/`)
|
||||||
|
|
||||||
### Structure
|
### Structure
|
||||||
|
|
||||||
- **Path format**: `blobs/<first-2-chars>/<next-2-chars>/<full-hash>`
|
- **Path format**: `blobs/<first-2-chars>/<next-2-chars>/<full-hash>`
|
||||||
- **Example**: `blobs/ca/fe/cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678`
|
- **Example**:
|
||||||
- **Sharding**: The two-level directory structure (using the first 4 characters of the hash) prevents any single directory from containing too many objects
|
`blobs/ca/fe/cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678`
|
||||||
|
- **Sharding**: The two-level directory structure (using the first 4 characters
|
||||||
|
of the hash) prevents any single directory from containing too many objects
|
||||||
|
|
||||||
### Content
|
### Content
|
||||||
|
|
||||||
- **What it contains**: Packed collections of content-defined chunks from files
|
- **What it contains**: Packed collections of content-defined chunks from files
|
||||||
- **Format**: Zstandard compressed, then Age encrypted
|
- **Format**: Zstandard compressed, then Age encrypted
|
||||||
- **Encryption**: Always encrypted with Age using the configured recipients
|
- **Encryption**: Always encrypted with Age using the configured recipients
|
||||||
- **Naming**: Content-addressed. The blob's name is `hex(SHA256(SHA256(uncompressed blob contents)))` — the double SHA-256 of the concatenated chunk data, computed before compression and encryption, not a hash of the stored (compressed, encrypted) bytes. One consequence: only a holder of the age private key can check a stored blob's integrity, because matching a blob to its name means decrypting and decompressing it first — which is what `restore` and `verify --deep` do. Implemented in `internal/blobgen` (`DoubleSHA256`). This is the canonical description of blob naming; other documents and comments point here.
|
- **Naming**: Content-addressed. The blob's name is
|
||||||
|
`hex(SHA256(SHA256(uncompressed blob contents)))` — the double SHA-256 of the
|
||||||
|
concatenated chunk data, computed before compression and encryption, not a
|
||||||
|
hash of the stored (compressed, encrypted) bytes. One consequence: only a
|
||||||
|
holder of the age private key can check a stored blob's integrity, because
|
||||||
|
matching a blob to its name means decrypting and decompressing it first —
|
||||||
|
which is what `restore` and `verify --deep` do. Implemented in
|
||||||
|
`internal/blobgen` (`DoubleSHA256`). This is the canonical description of blob
|
||||||
|
naming; other documents and comments point here.
|
||||||
|
|
||||||
### Why Encrypted
|
### Why Encrypted
|
||||||
Blobs contain the actual file data from backups and must be encrypted for security. The content-addressing ensures deduplication while the encryption ensures privacy.
|
|
||||||
|
Blobs contain the actual file data from backups and must be encrypted for
|
||||||
|
security. The content-addressing ensures deduplication while the encryption
|
||||||
|
ensures privacy.
|
||||||
|
|
||||||
## Metadata Directory (`metadata/`)
|
## Metadata Directory (`metadata/`)
|
||||||
|
|
||||||
Each snapshot has its own subdirectory. The directory is **not** named with the human-readable snapshot ID; it is named with the remote key — a one-way hash of that ID. The human ID is never written to the destination store as a directory name (see [Remote Key Derivation](#remote-key-derivation)).
|
Each snapshot has its own subdirectory. The directory is **not** named with the
|
||||||
|
human-readable snapshot ID; it is named with the remote key — a one-way hash of
|
||||||
|
that ID. The human ID is never written to the destination store as a directory
|
||||||
|
name (see [Remote Key Derivation](#remote-key-derivation)).
|
||||||
|
|
||||||
### Snapshot ID Format
|
### Snapshot ID Format
|
||||||
|
|
||||||
The human-readable snapshot ID is used in CLI arguments, log lines, and the local database. It is not written to the destination store.
|
The human-readable snapshot ID is used in CLI arguments, log lines, and the
|
||||||
- **Format**: `<hostname>_<snapshot-name>_<RFC3339>` (or `<hostname>_<RFC3339>` if no
|
local database. It is not written to the destination store.
|
||||||
name was specified)
|
|
||||||
|
- **Format**: `<hostname>_<snapshot-name>_<RFC3339>` (or `<hostname>_<RFC3339>`
|
||||||
|
if no name was specified)
|
||||||
- **Example**: `laptop_home_2024-01-15T14:30:52Z`
|
- **Example**: `laptop_home_2024-01-15T14:30:52Z`
|
||||||
- **Components**:
|
- **Components**:
|
||||||
- Short hostname (everything before the first dot is stripped from the FQDN)
|
- Short hostname (everything before the first dot is stripped from the FQDN)
|
||||||
- Snapshot name from the configured `snapshots:` map (optional)
|
- Snapshot name from the configured `snapshots:` map (optional)
|
||||||
- RFC3339 UTC timestamp
|
- RFC3339 UTC timestamp
|
||||||
|
|
||||||
This ID reveals the hostname, the configured snapshot name, and the backup time, so it is never used as the on-disk directory name — the remote key is used instead.
|
This ID reveals the hostname, the configured snapshot name, and the backup time,
|
||||||
|
so it is never used as the on-disk directory name — the remote key is used
|
||||||
|
instead.
|
||||||
|
|
||||||
### Remote Key Derivation
|
### Remote Key Derivation
|
||||||
|
|
||||||
The remote key is `hex(SHA256(SHA256("vaultik|" + snapshot-id)))`: a double SHA-256 over the snapshot ID, with a `vaultik|` domain-separation prefix. The result is a 64-character hex string. The hash is not reversible, but it uses no secret: an observer who guesses a candidate hostname and snapshot name can hash it the same way and confirm whether that snapshot is present. The remote key keeps names out of a plain listing; it does not hide them from a guess. Implemented in `internal/snapshot/remotekey.go`.
|
The remote key is `hex(SHA256(SHA256("vaultik|" + snapshot-id)))`: a double
|
||||||
|
SHA-256 over the snapshot ID, with a `vaultik|` domain-separation prefix. The
|
||||||
|
result is a 64-character hex string. The hash is not reversible, but it uses no
|
||||||
|
secret: an observer who guesses a candidate hostname and snapshot name can hash
|
||||||
|
it the same way and confirm whether that snapshot is present. The remote key
|
||||||
|
keeps names out of a plain listing; it does not hide them from a guess.
|
||||||
|
Implemented in `internal/snapshot/remotekey.go`.
|
||||||
|
|
||||||
Worked example:
|
Worked example:
|
||||||
|
|
||||||
- Snapshot ID: `server1_home_2025-06-01T12:00:00Z`
|
- Snapshot ID: `server1_home_2025-06-01T12:00:00Z`
|
||||||
- Remote key: `17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa`
|
- Remote key: `17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa`
|
||||||
- Directory: `metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/`
|
- Directory:
|
||||||
|
`metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/`
|
||||||
|
|
||||||
A plain listing of the destination store therefore shows only these hashes, not the hostname or snapshot name of any backup — but because the hash uses no secret, a guessed hostname and snapshot name can be hashed and confirmed against the listing. The same remote key is stored in the manifest's `snapshot_id` field.
|
A plain listing of the destination store therefore shows only these hashes, not
|
||||||
|
the hostname or snapshot name of any backup — but because the hash uses no
|
||||||
|
secret, a guessed hostname and snapshot name can be hashed and confirmed against
|
||||||
|
the listing. The same remote key is stored in the manifest's `snapshot_id`
|
||||||
|
field.
|
||||||
|
|
||||||
### Files in Each Snapshot Directory
|
### Files in Each Snapshot Directory
|
||||||
|
|
||||||
#### `db.zst.age` - Encrypted Database
|
#### `db.zst.age` - Encrypted Database
|
||||||
|
|
||||||
- **What it contains**: Pruned binary SQLite database for this snapshot
|
- **What it contains**: Pruned binary SQLite database for this snapshot
|
||||||
- **Format**: Binary SQLite → Zstandard compressed → Age encrypted
|
- **Format**: Binary SQLite → Zstandard compressed → Age encrypted
|
||||||
- **Encryption**: Encrypted with Age
|
- **Encryption**: Encrypted with Age
|
||||||
- **Purpose**: Contains full file metadata, chunk mappings, and all relationships
|
- **Purpose**: Contains full file metadata, chunk mappings, and all
|
||||||
- **Why encrypted**: Contains sensitive metadata like file paths, permissions, and ownership
|
relationships
|
||||||
|
- **Why encrypted**: Contains sensitive metadata like file paths, permissions,
|
||||||
|
and ownership
|
||||||
|
|
||||||
#### `manifest.json.zst` - Unencrypted Blob Manifest
|
#### `manifest.json.zst` - Unencrypted Blob Manifest
|
||||||
|
|
||||||
- **What it contains**: JSON list of all blob hashes referenced by this snapshot
|
- **What it contains**: JSON list of all blob hashes referenced by this snapshot
|
||||||
- **Format**: JSON → Zstandard compressed (NOT encrypted)
|
- **Format**: JSON → Zstandard compressed (NOT encrypted)
|
||||||
- **Encryption**: NOT encrypted
|
- **Encryption**: NOT encrypted
|
||||||
- **Purpose**: Enables pruning operations without requiring decryption keys
|
- **Purpose**: Enables pruning operations without requiring decryption keys
|
||||||
- **Structure**:
|
- **Structure**:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"snapshot_id": "17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa",
|
"snapshot_id": "17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa",
|
||||||
"timestamp": "2025-06-01T12:00:00Z",
|
"timestamp": "2025-06-01T12:00:00Z",
|
||||||
"blob_count": 42,
|
"blob_count": 42,
|
||||||
"total_compressed_size": 1048576,
|
"total_compressed_size": 1048576,
|
||||||
"blobs": [
|
"blobs": [
|
||||||
{ "hash": "cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678", "compressed_size": 24576 },
|
{
|
||||||
{ "hash": "deadbeef1234567890abcdef1234567890abcdef1234567890abcdef12345678", "compressed_size": 32768 }
|
"hash": "cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678",
|
||||||
]
|
"compressed_size": 24576
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hash": "deadbeef1234567890abcdef1234567890abcdef1234567890abcdef12345678",
|
||||||
|
"compressed_size": 32768
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
`snapshot_id` is the remote key (a hash), not the human ID; `timestamp` is written in the clear.
|
|
||||||
|
`snapshot_id` is the remote key (a hash), not the human ID; `timestamp` is
|
||||||
|
written in the clear.
|
||||||
|
|
||||||
### Why Manifest is Unencrypted
|
### Why Manifest is Unencrypted
|
||||||
|
|
||||||
The manifest must be readable without the private key to enable:
|
The manifest must be readable without the private key to enable:
|
||||||
|
|
||||||
1. **Pruning operations** - Identifying unreferenced blobs for deletion
|
1. **Pruning operations** - Identifying unreferenced blobs for deletion
|
||||||
2. **Storage analysis** - Understanding space usage without decryption
|
2. **Storage analysis** - Understanding space usage without decryption
|
||||||
3. **Verification** - Checking blob existence without decryption
|
3. **Verification** - Checking blob existence without decryption
|
||||||
4. **Cross-snapshot deduplication analysis** - Finding shared blobs between snapshots
|
4. **Cross-snapshot deduplication analysis** - Finding shared blobs between
|
||||||
|
snapshots
|
||||||
|
|
||||||
The manifest contains the remote key, the backup timestamp, the blob count and total compressed size, and each blob's hash and compressed size. It contains no file names, paths, or other decrypted metadata.
|
The manifest contains the remote key, the backup timestamp, the blob count and
|
||||||
|
total compressed size, and each blob's hash and compressed size. It contains no
|
||||||
|
file names, paths, or other decrypted metadata.
|
||||||
|
|
||||||
## Security Considerations
|
## Security Considerations
|
||||||
|
|
||||||
### What's Encrypted
|
### What's Encrypted
|
||||||
|
|
||||||
- **All file content** (in blobs)
|
- **All file content** (in blobs)
|
||||||
- **All file metadata** (paths, permissions, timestamps, ownership in db.zst.age)
|
- **All file metadata** (paths, permissions, timestamps, ownership in
|
||||||
|
db.zst.age)
|
||||||
- **File-to-chunk mappings** (in db.zst.age)
|
- **File-to-chunk mappings** (in db.zst.age)
|
||||||
|
|
||||||
### What's Not Encrypted
|
### What's Not Encrypted
|
||||||
- **The remote key** — directory names and the manifest `snapshot_id`, a one-way hash of the snapshot ID (see [Remote Key Derivation](#remote-key-derivation))
|
|
||||||
|
- **The remote key** — directory names and the manifest `snapshot_id`, a one-way
|
||||||
|
hash of the snapshot ID (see [Remote Key Derivation](#remote-key-derivation))
|
||||||
- **The backup timestamp** (in manifest.json.zst)
|
- **The backup timestamp** (in manifest.json.zst)
|
||||||
- **Blob hashes and their compressed sizes** (in manifest.json.zst)
|
- **Blob hashes and their compressed sizes** (in manifest.json.zst)
|
||||||
- **Blob count and total compressed size per snapshot** (in manifest.json.zst)
|
- **Blob count and total compressed size per snapshot** (in manifest.json.zst)
|
||||||
|
|
||||||
### Privacy Implications
|
### Privacy Implications
|
||||||
From the unencrypted data, an observer of the destination store can determine:
|
|
||||||
- **When each backup was taken** — not from the directory name, which is a one-way hash, but from the plaintext `timestamp` field in manifest.json.zst, which is published in the clear
|
|
||||||
- How many blobs each snapshot references, and the total compressed size
|
|
||||||
- The compressed size of each blob, and which blobs are shared between snapshots (deduplication patterns)
|
|
||||||
- **Whether a guessed hostname and snapshot name are present** — the remote key is an unkeyed hash, so an observer holding candidate names can hash each one and match it against the directory listing. The human ID is never published, so it cannot be read off directly, but it can be confirmed by guessing.
|
|
||||||
|
|
||||||
Together these give an observer a timing-and-size profile of every snapshot. This is an accepted, documented property of the format, not a defect: the manifest is unencrypted so that pruning can run without the private key, and the timing channel could not be closed by encrypting it anyway — object creation times and per-object sizes stay visible at the storage layer on both `s3://` and `file://` destinations regardless.
|
From the unencrypted data, an observer of the destination store can determine:
|
||||||
|
|
||||||
|
- **When each backup was taken** — not from the directory name, which is a
|
||||||
|
one-way hash, but from the plaintext `timestamp` field in manifest.json.zst,
|
||||||
|
which is published in the clear
|
||||||
|
- How many blobs each snapshot references, and the total compressed size
|
||||||
|
- The compressed size of each blob, and which blobs are shared between snapshots
|
||||||
|
(deduplication patterns)
|
||||||
|
- **Whether a guessed hostname and snapshot name are present** — the remote key
|
||||||
|
is an unkeyed hash, so an observer holding candidate names can hash each one
|
||||||
|
and match it against the directory listing. The human ID is never published,
|
||||||
|
so it cannot be read off directly, but it can be confirmed by guessing.
|
||||||
|
|
||||||
|
Together these give an observer a timing-and-size profile of every snapshot.
|
||||||
|
This is an accepted, documented property of the format, not a defect: the
|
||||||
|
manifest is unencrypted so that pruning can run without the private key, and the
|
||||||
|
timing channel could not be closed by encrypting it anyway — object creation
|
||||||
|
times and per-object sizes stay visible at the storage layer on both `s3://` and
|
||||||
|
`file://` destinations regardless.
|
||||||
|
|
||||||
An observer cannot determine:
|
An observer cannot determine:
|
||||||
- The hostname or snapshot name of any backup by reading it off the store — the directory name and the manifest `snapshot_id` are unkeyed hashes of the human ID, so the text is never published (though a guessed name can be confirmed, as above)
|
|
||||||
|
- The hostname or snapshot name of any backup by reading it off the store — the
|
||||||
|
directory name and the manifest `snapshot_id` are unkeyed hashes of the human
|
||||||
|
ID, so the text is never published (though a guessed name can be confirmed, as
|
||||||
|
above)
|
||||||
- File names or paths
|
- File names or paths
|
||||||
- File contents
|
- File contents
|
||||||
- File permissions or ownership
|
- File permissions or ownership
|
||||||
@@ -138,39 +236,126 @@ An observer cannot determine:
|
|||||||
|
|
||||||
### Accepted Risks
|
### Accepted Risks
|
||||||
|
|
||||||
These are known, deliberate properties of the format and the tooling, recorded so an operator can weigh them rather than discover them.
|
These are known, deliberate properties of the format and the tooling, recorded
|
||||||
|
so an operator can weigh them rather than discover them.
|
||||||
|
|
||||||
1. **No proof of authorship.** Restore and `verify --deep` prove that data decrypts with the age private key and matches its unkeyed content hashes. They do not prove who wrote it: anyone who knows a recipient public key and can replace objects on the destination can substitute a snapshot they built. The recipient string is not stored at the destination, but a compromised backed-up host has it. Defences live on the destination side — bucket versioning or object lock, credentials for the source host that cannot delete or overwrite existing versions, and pruning from a trusted host. Note that S3 `PutObject` overwrites an existing key, so PUT permission alone is not append-only.
|
1. **No proof of authorship.** Restore and `verify --deep` prove that data
|
||||||
2. **Compression reveals sizes.** Blobs and `db.zst.age` are zstd-compressed then age-encrypted; the manifest is compressed only. age does not pad, so an object's size is the exact compressed length of its contents. All new chunks packed into one blob share a single zstd stream (8 MiB window, 4 MiB at compression levels 1-2), and a blob is closed at `blob_size_limit` and at the end of each configured path. Because a stored chunk is never packed again, someone who can write into a backed-up file and watch blob sizes learns something only when their controlled data and a secret land in the same chunk of a file that keeps changing. Advice: back up any outsider-writable directory as its own snapshot.
|
decrypts with the age private key and matches its unkeyed content hashes.
|
||||||
3. **Chunking uses no secret.** The FastCDC parameters are fixed and public. The default 10 MB average yields chunks between 2.5 MB and 40 MB, and any file of 2.5 MB or less is a single chunk. At the default 10 GB `blob_size_limit` a blob holds hundreds of chunks, so individual chunk lengths are not visible in the blob's size; lowering the limit toward the chunk size begins to expose them.
|
They do not prove who wrote it: anyone who knows a recipient public key and
|
||||||
4. **Decrypted data on local disk.** Several commands stage plaintext under `$TMPDIR`: `snapshot restore` writes decrypted blobs under `vaultik-blobcache-*/` (no size cap) and the decrypted metadata database at `vaultik-restore-*/snapshot.db`; `verify --deep` writes that database at `vaultik-verify-*/snapshot.db`; `snapshot create` keeps a plaintext copy of the index at `vaultik-snapshot-*/snapshot.db`. These files are created `0600` and removed on success, but a `kill -9` or a power loss leaves them behind — delete any leftover `vaultik-*` directory under `$TMPDIR` by hand. `$TMPDIR` should be trusted to the same degree as the restore target.
|
can replace objects on the destination can substitute a snapshot they built.
|
||||||
5. **Store permissions differ per command.** The backed-up host needs only PUT to run `snapshot create`: it writes blobs and metadata and neither reads nor deletes them. Other commands need more — `snapshot verify`, `snapshot restore`, and `prune` list and read; `prune`, `snapshot purge`, `snapshot remove`, and `remote nuke` also delete. The recommended cron line uses `--prune`, which runs `prune` on the backed-up host, so granting that host `--prune` gives it credentials that can delete its own backups. To keep the source host to PUT only, prune from a separate trusted host instead.
|
The recipient string is not stored at the destination, but a compromised
|
||||||
6. **Changing recipients does not re-encrypt existing data.** Deduplicated chunks and same-named blobs already on the destination stay encrypted to the recipients in force when they were written. A new snapshot that reuses them cannot be restored with a newly added recipient's key alone, because those reused objects were never encrypted to it. To make everything readable by a new key, run `vaultik database delete` and take a full backup to a fresh destination or prefix.
|
backed-up host has it. Defences live on the destination side — bucket
|
||||||
7. **X25519 recipients only.** vaultik rejects age ssh and plugin recipients. Long-lived ciphertext held by a third party (the destination operator) has no fallback if X25519 is ever broken: there is no second recipient type and no post-quantum option.
|
versioning or object lock, credentials for the source host that cannot delete
|
||||||
|
or overwrite existing versions, and pruning from a trusted host. Note that S3
|
||||||
|
`PutObject` overwrites an existing key, so PUT permission alone is not
|
||||||
|
append-only.
|
||||||
|
2. **Compression reveals sizes.** Blobs and `db.zst.age` are zstd-compressed
|
||||||
|
then age-encrypted; the manifest is compressed only. age does not pad, so an
|
||||||
|
object's size is the exact compressed length of its contents. All new chunks
|
||||||
|
packed into one blob share a single zstd stream (8 MiB window, 4 MiB at
|
||||||
|
compression levels 1-2), and a blob is closed at `blob_size_limit` and at the
|
||||||
|
end of each configured path. Because a stored chunk is never packed again,
|
||||||
|
someone who can write into a backed-up file and watch blob sizes learns
|
||||||
|
something only when their controlled data and a secret land in the same chunk
|
||||||
|
of a file that keeps changing. Advice: back up any outsider-writable
|
||||||
|
directory as its own snapshot.
|
||||||
|
3. **Chunking uses no secret.** The FastCDC parameters are fixed and public. The
|
||||||
|
default 10 MB average yields chunks between 2.5 MB and 40 MB, and any file of
|
||||||
|
2.5 MB or less is a single chunk. At the default 10 GB `blob_size_limit` a
|
||||||
|
blob holds hundreds of chunks, so individual chunk lengths are not visible in
|
||||||
|
the blob's size; lowering the limit toward the chunk size begins to expose
|
||||||
|
them.
|
||||||
|
4. **Decrypted data on local disk.** These commands stage plaintext under
|
||||||
|
`$TMPDIR`:
|
||||||
|
- `snapshot restore`: decrypted blobs under `vaultik-blobcache-*/`, with no
|
||||||
|
size cap, and the decrypted metadata database at
|
||||||
|
`vaultik-restore-*/snapshot.db`.
|
||||||
|
- `snapshot files`: the decrypted metadata database at
|
||||||
|
`vaultik-restore-*/snapshot.db`.
|
||||||
|
- `verify --deep`: the decrypted metadata database at
|
||||||
|
`vaultik-verify-*/snapshot.db`.
|
||||||
|
- `snapshot create`: a plaintext copy of the index at
|
||||||
|
`vaultik-snapshot-*/snapshot.db`.
|
||||||
|
|
||||||
|
These files are created `0600` and removed on success, but a `kill -9` or a
|
||||||
|
power loss leaves them behind — delete any leftover `vaultik-*` directory
|
||||||
|
under `$TMPDIR` by hand. `$TMPDIR` should be trusted to the same degree as
|
||||||
|
the restore target.
|
||||||
|
|
||||||
|
5. **Store permissions differ per command.** The backed-up host needs only PUT
|
||||||
|
to run `snapshot create`: it writes blobs and metadata and neither reads nor
|
||||||
|
deletes them. Other commands need more — `snapshot verify`,
|
||||||
|
`snapshot restore`, and `prune` list and read; `prune`, `snapshot purge`,
|
||||||
|
`snapshot remove`, and `remote nuke` also delete. The recommended cron line
|
||||||
|
uses `--prune`, which runs `prune` on the backed-up host, so granting that
|
||||||
|
host `--prune` gives it credentials that can delete its own backups. To keep
|
||||||
|
the source host to PUT only, prune from a separate trusted host instead.
|
||||||
|
6. **Changing recipients does not re-encrypt existing data.** Deduplicated
|
||||||
|
chunks and same-named blobs already on the destination stay encrypted to the
|
||||||
|
recipients in force when they were written. A new snapshot that reuses them
|
||||||
|
cannot be restored with a newly added recipient's key alone, because those
|
||||||
|
reused objects were never encrypted to it. To make everything readable by a
|
||||||
|
new key, run `vaultik database delete` and take a full backup to a fresh
|
||||||
|
destination or prefix.
|
||||||
|
7. **X25519 recipients only.** vaultik rejects age ssh and plugin recipients.
|
||||||
|
Long-lived ciphertext held by a third party (the destination operator) has no
|
||||||
|
fallback if X25519 is ever broken: there is no second recipient type and no
|
||||||
|
post-quantum option.
|
||||||
|
|
||||||
## Consistency Guarantees
|
## Consistency Guarantees
|
||||||
|
|
||||||
1. **Blobs are immutable** - Once written, a blob is never modified
|
1. **Blobs are immutable** - Once written, a blob is never modified
|
||||||
2. **Blobs are written before metadata** - A snapshot's metadata is only written after all its blobs are successfully uploaded
|
2. **Blobs are written before metadata** - A snapshot's metadata is only written
|
||||||
3. **Metadata is written atomically** - Both db.zst.age and manifest.json.zst are written as complete files
|
after all its blobs are successfully uploaded
|
||||||
4. **A snapshot is marked complete in the local DB only after its metadata is uploaded** - `finalizeSnapshotMetadata` runs `ExportSnapshotMetadata` first and records completion (`MarkSnapshotComplete`) only once the export succeeds (see the backup data flow in [ARCHITECTURE.md](../ARCHITECTURE.md)). A crash during the export therefore leaves the snapshot incomplete, so the next backup's `PruneDatabase` drops it and re-backs-up its data, rather than leaving a completed-looking row in the local index with no matching metadata on the destination store. (A crash in the brief moment after the export succeeds but before completion is recorded leaves a fully-restorable snapshot on the destination that the local index drops as incomplete on the next run; `snapshot list` then reports it honestly as remote-only, which is the safe direction: the destination copy stays restorable.)
|
3. **Metadata is written atomically** - Both db.zst.age and manifest.json.zst
|
||||||
|
are written as complete files
|
||||||
|
4. **A snapshot is marked complete in the local DB only after its metadata is
|
||||||
|
uploaded** - `finalizeSnapshotMetadata` runs `ExportSnapshotMetadata` first
|
||||||
|
and records completion (`MarkSnapshotComplete`) only once the export succeeds
|
||||||
|
(see the backup data flow in [ARCHITECTURE.md](ARCHITECTURE.md)). A crash
|
||||||
|
during the export therefore leaves the snapshot incomplete, so the next
|
||||||
|
backup's `PruneDatabase` drops it and re-backs-up its data, rather than
|
||||||
|
leaving a completed-looking row in the local index with no matching metadata
|
||||||
|
on the destination store. (A crash in the brief moment after the export
|
||||||
|
succeeds but before completion is recorded leaves a fully-restorable snapshot
|
||||||
|
on the destination that the local index drops as incomplete on the next run;
|
||||||
|
`snapshot list` then reports it honestly as remote-only, which is the safe
|
||||||
|
direction: the destination copy stays restorable.)
|
||||||
|
|
||||||
## Pruning Safety
|
## Pruning Safety
|
||||||
|
|
||||||
The prune operation is safe because:
|
The prune operation is safe because:
|
||||||
1. It keeps every blob listed in any snapshot's manifest and deletes only blobs that no manifest references
|
|
||||||
|
1. It keeps every blob listed in any snapshot's manifest and deletes only blobs
|
||||||
|
that no manifest references. Under `metadata/` it deletes only a directory
|
||||||
|
that has no `manifest.json.zst`, whose name is a remote key, and that no
|
||||||
|
local snapshot record claims
|
||||||
2. Manifests are unencrypted and can be read without keys
|
2. Manifests are unencrypted and can be read without keys
|
||||||
3. If any manifest cannot be downloaded or decoded, prune deletes nothing and exits with an error, rather than treating that snapshot's blobs as unreferenced
|
3. If any manifest cannot be downloaded or decoded, prune deletes nothing and
|
||||||
4. Prune requires exclusive access to the destination: running it during a concurrent backup can race a snapshot whose manifest is not yet written, so do not prune while a backup is in progress
|
exits with an error, rather than treating that snapshot's blobs as
|
||||||
|
unreferenced
|
||||||
|
4. It deletes an unreferenced blob only once the blob is older than
|
||||||
|
`prune_grace_period` (default `24h`), and a directory under `metadata/` with
|
||||||
|
no manifest only once every object in it is. A backup uploads its blobs and
|
||||||
|
its `db.zst.age` before its manifest, so a prune running meanwhile, on this
|
||||||
|
host or another sharing the destination, leaves them as long as no backup run
|
||||||
|
takes longer than the grace period. The grace period does not protect a blob
|
||||||
|
a backup reuses from an earlier run that stopped before its manifest: the
|
||||||
|
backup skips the upload of a blob already on the destination, so that blob
|
||||||
|
keeps the time of its first upload, and a prune before the backup's manifest
|
||||||
|
is written can delete it; the new snapshot then cannot be restored.
|
||||||
|
`remote nuke` has no such check
|
||||||
|
|
||||||
## Restoration Requirements
|
## Restoration Requirements
|
||||||
|
|
||||||
To restore from a backup, you need:
|
To restore from a backup, you need:
|
||||||
|
|
||||||
1. **The Age private key** - To decrypt blobs and database
|
1. **The Age private key** - To decrypt blobs and database
|
||||||
2. **The snapshot metadata** - Both files from the snapshot's metadata directory
|
2. **The snapshot metadata** - Both files from the snapshot's metadata directory
|
||||||
3. **All referenced blobs** - As listed in the manifest
|
3. **All referenced blobs** - As listed in the manifest
|
||||||
|
|
||||||
The restoration process:
|
The restoration process:
|
||||||
|
|
||||||
1. Download and decrypt the database dump to understand file structure
|
1. Download and decrypt the database dump to understand file structure
|
||||||
2. Download and decrypt the required blobs
|
2. Download and decrypt the required blobs
|
||||||
3. Reconstruct files from their chunks
|
3. Reconstruct files from their chunks
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Workflow
|
||||||
|
|
||||||
|
- branch (from `main`)
|
||||||
|
- do the work in Next Step
|
||||||
|
- delete Next Step from `TODO.md`
|
||||||
|
- move the top item of Future Steps into Next Step
|
||||||
|
- commit (`TODO.md` changes in the same commit as the work)
|
||||||
|
- merge to `main` if the branch is not protected, otherwise open a PR
|
||||||
|
- push
|
||||||
|
|
||||||
|
# Status
|
||||||
|
|
||||||
|
pre-1.0
|
||||||
|
|
||||||
|
# Next Step
|
||||||
|
|
||||||
|
Fix the open bugs on the issue tracker that block the release. Merging `next`
|
||||||
|
into `main` is the owner's.
|
||||||
|
|
||||||
|
# Future Steps
|
||||||
|
|
||||||
|
Work planned after 1.0 is listed in the README [roadmap](../README.md#roadmap).
|
||||||
@@ -22,8 +22,11 @@ require (
|
|||||||
github.com/spf13/cobra v1.10.1
|
github.com/spf13/cobra v1.10.1
|
||||||
github.com/spf13/pflag v1.0.10
|
github.com/spf13/pflag v1.0.10
|
||||||
github.com/stretchr/testify v1.11.1
|
github.com/stretchr/testify v1.11.1
|
||||||
|
go.uber.org/dig v1.19.0
|
||||||
go.uber.org/fx v1.24.0
|
go.uber.org/fx v1.24.0
|
||||||
|
golang.org/x/mod v0.29.0
|
||||||
golang.org/x/sync v0.18.0
|
golang.org/x/sync v0.18.0
|
||||||
|
golang.org/x/sys v0.38.0
|
||||||
golang.org/x/term v0.37.0
|
golang.org/x/term v0.37.0
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
modernc.org/sqlite v1.38.0
|
modernc.org/sqlite v1.38.0
|
||||||
@@ -255,7 +258,6 @@ require (
|
|||||||
go.opentelemetry.io/otel/metric v1.38.0 // indirect
|
go.opentelemetry.io/otel/metric v1.38.0 // indirect
|
||||||
go.opentelemetry.io/otel/trace v1.38.0 // indirect
|
go.opentelemetry.io/otel/trace v1.38.0 // indirect
|
||||||
go.shabbyrobe.org/gocovmerge v0.0.0-20230507111327-fa4f82cfbf4d // indirect
|
go.shabbyrobe.org/gocovmerge v0.0.0-20230507111327-fa4f82cfbf4d // indirect
|
||||||
go.uber.org/dig v1.19.0 // indirect
|
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
go.uber.org/zap v1.27.0 // indirect
|
go.uber.org/zap v1.27.0 // indirect
|
||||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||||
@@ -263,7 +265,6 @@ require (
|
|||||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||||
golang.org/x/net v0.47.0 // indirect
|
golang.org/x/net v0.47.0 // indirect
|
||||||
golang.org/x/oauth2 v0.33.0 // indirect
|
golang.org/x/oauth2 v0.33.0 // indirect
|
||||||
golang.org/x/sys v0.38.0 // indirect
|
|
||||||
golang.org/x/text v0.31.0 // indirect
|
golang.org/x/text v0.31.0 // indirect
|
||||||
golang.org/x/time v0.14.0 // indirect
|
golang.org/x/time v0.14.0 // indirect
|
||||||
golang.org/x/tools v0.38.0 // indirect
|
golang.org/x/tools v0.38.0 // indirect
|
||||||
|
|||||||
@@ -245,6 +245,17 @@ func (p *Packer) Flush(ctx context.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DiscardCurrentBlob closes and removes the temp file of the blob being
|
||||||
|
// packed, if any, and drops that blob. A caller that stops before Flush
|
||||||
|
// must call it, or the temp file is left behind. Thread-safe.
|
||||||
|
func (p *Packer) DiscardCurrentBlob() {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
p.cleanupTempFile()
|
||||||
|
p.currentBlob = nil
|
||||||
|
}
|
||||||
|
|
||||||
// FinalizeBlob finalizes the current blob being assembled.
|
// FinalizeBlob finalizes the current blob being assembled.
|
||||||
// This compresses the accumulated chunks, encrypts the result, and computes
|
// This compresses the accumulated chunks, encrypts the result, and computes
|
||||||
// the content-addressed hash. The finalized blob is either passed to the
|
// the content-addressed hash. The finalized blob is either passed to the
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package blobgen_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
"testing/iotest"
|
||||||
|
|
||||||
"filippo.io/age"
|
"filippo.io/age"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -120,6 +122,38 @@ func TestNewReaderTrailingAndGarbage(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestNewReaderGarbageErrorQuotesNoBytes checks that lines of text in
|
||||||
|
// place of a blob fail with ErrNotAgeStream, and that the error carries
|
||||||
|
// none of their bytes. The lines end in a newline because age's own error
|
||||||
|
// quotes the data's first line only when it reads a whole line.
|
||||||
|
func TestNewReaderGarbageErrorQuotesNoBytes(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
id, _ := makeIdentity(t)
|
||||||
|
garbage := bytes.Repeat([]byte("garbage-bytes-\n"), 100)
|
||||||
|
|
||||||
|
_, err := blobgen.NewReader(bytes.NewReader(garbage), id)
|
||||||
|
|
||||||
|
require.ErrorIs(t, err, blobgen.ErrNotAgeStream)
|
||||||
|
assert.NotContains(t, err.Error(), "garbage-bytes-")
|
||||||
|
}
|
||||||
|
|
||||||
|
// errConnectionReset stands for a storage read that fails.
|
||||||
|
var errConnectionReset = errors.New("connection reset")
|
||||||
|
|
||||||
|
// TestNewReaderReadFailure checks that a failed read of the age header is
|
||||||
|
// returned as that read error, not as ErrNotAgeStream.
|
||||||
|
func TestNewReaderReadFailure(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
id, _ := makeIdentity(t)
|
||||||
|
|
||||||
|
_, err := blobgen.NewReader(iotest.ErrReader(errConnectionReset), id)
|
||||||
|
|
||||||
|
require.ErrorIs(t, err, errConnectionReset)
|
||||||
|
assert.NotErrorIs(t, err, blobgen.ErrNotAgeStream)
|
||||||
|
}
|
||||||
|
|
||||||
// TestNewWriterInvalidLevel covers the rejected end of issue case 9: an
|
// TestNewWriterInvalidLevel covers the rejected end of issue case 9: an
|
||||||
// out-of-range compression level errors and writes nothing to the destination.
|
// out-of-range compression level errors and writes nothing to the destination.
|
||||||
func TestNewWriterInvalidLevel(t *testing.T) {
|
func TestNewWriterInvalidLevel(t *testing.T) {
|
||||||
|
|||||||
@@ -11,6 +11,11 @@ import (
|
|||||||
"github.com/klauspost/compress/zstd"
|
"github.com/klauspost/compress/zstd"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrNotAgeStream is returned by NewReader when the data cannot be opened
|
||||||
|
// as an age stream, for example because its header is malformed. It
|
||||||
|
// replaces age's own error, which can quote the data's first bytes.
|
||||||
|
var ErrNotAgeStream = errors.New("not a valid age stream")
|
||||||
|
|
||||||
// Reader wraps decompression and decryption with SHA256 verification
|
// Reader wraps decompression and decryption with SHA256 verification
|
||||||
type Reader struct {
|
type Reader struct {
|
||||||
reader io.Reader
|
reader io.Reader
|
||||||
@@ -24,11 +29,25 @@ type Reader struct {
|
|||||||
// NewReader creates a new Reader that decrypts, decompresses, and verifies
|
// NewReader creates a new Reader that decrypts, decompresses, and verifies
|
||||||
// data. Every supplied identity is offered to age.Decrypt, so a blob
|
// data. Every supplied identity is offered to age.Decrypt, so a blob
|
||||||
// encrypted to any one of them can be read.
|
// encrypted to any one of them can be read.
|
||||||
|
//
|
||||||
|
// A failure to read r is returned as that error, and a blob encrypted to
|
||||||
|
// none of the identities as age.NoIdentityMatchError. Any other failure
|
||||||
|
// to open the age stream is ErrNotAgeStream.
|
||||||
func NewReader(r io.Reader, identities ...age.Identity) (*Reader, error) {
|
func NewReader(r io.Reader, identities ...age.Identity) (*Reader, error) {
|
||||||
// Create decryption reader
|
src := &readErrorRecorder{reader: r}
|
||||||
decReader, err := age.Decrypt(r, identities...)
|
|
||||||
|
decReader, err := age.Decrypt(src, identities...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("creating decryption reader: %w", err)
|
var noMatch *age.NoIdentityMatchError
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case src.err != nil:
|
||||||
|
return nil, fmt.Errorf("reading age header: %w", src.err)
|
||||||
|
case errors.As(err, &noMatch):
|
||||||
|
return nil, fmt.Errorf("creating decryption reader: %w", err)
|
||||||
|
default:
|
||||||
|
return nil, ErrNotAgeStream
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create decompression reader
|
// Create decompression reader
|
||||||
@@ -52,6 +71,23 @@ func NewReader(r io.Reader, identities ...age.Identity) (*Reader, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readErrorRecorder passes reads through to reader and keeps the first
|
||||||
|
// error other than io.EOF, so NewReader can tell a failed read from bad
|
||||||
|
// data.
|
||||||
|
type readErrorRecorder struct {
|
||||||
|
reader io.Reader
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *readErrorRecorder) Read(p []byte) (int, error) {
|
||||||
|
n, err := r.reader.Read(p)
|
||||||
|
if err != nil && !errors.Is(err, io.EOF) && r.err == nil {
|
||||||
|
r.err = err
|
||||||
|
}
|
||||||
|
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
// Read implements io.Reader
|
// Read implements io.Reader
|
||||||
func (r *Reader) Read(p []byte) (int, error) {
|
func (r *Reader) Read(p []byte) (int, error) {
|
||||||
n, err := r.teeReader.Read(p)
|
n, err := r.teeReader.Read(p)
|
||||||
|
|||||||
+63
-49
@@ -7,13 +7,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/adrg/xdg"
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
"go.uber.org/dig"
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
"sneak.berlin/go/vaultik/internal/config"
|
"sneak.berlin/go/vaultik/internal/config"
|
||||||
"sneak.berlin/go/vaultik/internal/database"
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
@@ -40,10 +38,11 @@ const (
|
|||||||
// prune, remote nuke) write the local index or the remote store. They
|
// prune, remote nuke) write the local index or the remote store. They
|
||||||
// hold the PID lock so that at most one runs at a time.
|
// hold the PID lock so that at most one runs at a time.
|
||||||
mutating lockMode = iota
|
mutating lockMode = iota
|
||||||
// readOnly commands (info, snapshot list, snapshot verify, remote info,
|
// readOnly commands (info, snapshot list, snapshot files, snapshot
|
||||||
// snapshot restore) do not write the local index or the remote store,
|
// verify, remote info, snapshot restore) do not write the local index
|
||||||
// so they run without the lock and are never blocked by a running
|
// or the remote store, so they run without the lock and are never
|
||||||
// mutator. restore writes only to the target directory it is given.
|
// blocked by a running mutator. restore writes only to the target
|
||||||
|
// directory it is given.
|
||||||
readOnly
|
readOnly
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -90,7 +89,7 @@ func setupGlobals(
|
|||||||
// blank line. Used both from the fx hook (for subcommand invocations) and
|
// blank line. Used both from the fx hook (for subcommand invocations) and
|
||||||
// from the root cobra Run handler (for `vaultik` with no subcommand).
|
// from the root cobra Run handler (for `vaultik` with no subcommand).
|
||||||
func writeStartupBanner(w *ui.Writer, startTime time.Time, shortCommit string) {
|
func writeStartupBanner(w *ui.Writer, startTime time.Time, shortCommit string) {
|
||||||
w.Bannerf("%s %s by %s (commit %s, built on %s) starting up at %s.",
|
w.Bannerf("%s %s by %s (commit %s, commit date %s) starting up at %s.",
|
||||||
globals.Appname, globals.Version, globals.Author,
|
globals.Appname, globals.Version, globals.Author,
|
||||||
shortCommit, globals.CommitDate,
|
shortCommit, globals.CommitDate,
|
||||||
startTime.Format(time.RFC3339))
|
startTime.Format(time.RFC3339))
|
||||||
@@ -146,16 +145,12 @@ func (e *startupError) Error() string {
|
|||||||
// could not build arguments for function "Y" (file:line): failed to build U:
|
// could not build arguments for function "Y" (file:line): failed to build U:
|
||||||
// received non-nil error from function "Z" (file:line): <real error>
|
// received non-nil error from function "Z" (file:line): <real error>
|
||||||
//
|
//
|
||||||
// Users care about the real error, not the DI plumbing. We strip everything
|
// Users care about the real error, not the DI plumbing. dig.RootCause,
|
||||||
// up through the last "): " (which is always the close-paren of an fx
|
// from the library fx is built on, unwraps those layers and returns the
|
||||||
// function-location annotation followed by the wrapped error).
|
// real error whole. Cutting the text at "): " instead would also cut a
|
||||||
|
// real error that contains it, such as the blob_size_limit one.
|
||||||
func cleanStartupError(err error) error {
|
func cleanStartupError(err error) error {
|
||||||
msg := err.Error()
|
return &startupError{msg: dig.RootCause(err).Error()}
|
||||||
if idx := strings.LastIndex(msg, "): "); idx >= 0 {
|
|
||||||
msg = msg[idx+3:]
|
|
||||||
}
|
|
||||||
|
|
||||||
return &startupError{msg: msg}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RunApp starts the fx application, blocks until it is asked to stop, and
|
// RunApp starts the fx application, blocks until it is asked to stop, and
|
||||||
@@ -200,12 +195,16 @@ func RunApp(ctx context.Context, app *fx.App) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// errReported marks a failure the operation has already shown the user
|
// errReported marks a failure the operation has already shown the user
|
||||||
// (and deliberately withheld under --json). Entry turns it into a
|
// (or, under `snapshot verify --json`, put in its document). Entry
|
||||||
// non-zero exit status without printing anything further, so the error
|
// turns it into a non-zero exit status without printing anything
|
||||||
// line is not doubled. It flows up from RunOperation through cobra to
|
// further, so the error line is not doubled. It flows up from
|
||||||
// Entry.
|
// RunOperation through cobra to Entry.
|
||||||
var errReported = errors.New("operation failed")
|
var errReported = errors.New("operation failed")
|
||||||
|
|
||||||
|
// errInterrupted marks an operation that SIGINT or SIGTERM stopped
|
||||||
|
// before it finished. Entry shows it and returns exitCodeInterrupted.
|
||||||
|
var errInterrupted = errors.New("interrupted before the command finished")
|
||||||
|
|
||||||
// RunOperation runs op against the Vaultik instance inside the fx app
|
// RunOperation runs op against the Vaultik instance inside the fx app
|
||||||
// and turns a failure into a returned error rather than an os.Exit from
|
// and turns a failure into a returned error rather than an os.Exit from
|
||||||
// within the goroutine. An os.Exit there skipped main's deferred
|
// within the goroutine. An os.Exit there skipped main's deferred
|
||||||
@@ -220,17 +219,21 @@ var errReported = errors.New("operation failed")
|
|||||||
// interrupt OnStop cancels op and waits for the goroutine to return, so
|
// interrupt OnStop cancels op and waits for the goroutine to return, so
|
||||||
// op's cleanup (removing decrypted scratch files) runs before the
|
// op's cleanup (removing decrypted scratch files) runs before the
|
||||||
// process exits; the wait is bounded by shutdownTimeout. report is
|
// process exits; the wait is bounded by shutdownTimeout. report is
|
||||||
// called with a non-canceled failure so the caller can log it (and
|
// called with a failure so the caller can show it to the user before
|
||||||
// suppress it under --json) before it becomes errReported. A context
|
// it becomes errReported.
|
||||||
// cancellation is the interrupt path, not a failure: it is neither
|
//
|
||||||
// reported nor counted as one.
|
// The run counts as interrupted unless op returned, without an
|
||||||
|
// interrupt having cancelled it, before RunWithApp returned. An
|
||||||
|
// interrupted op is not reported, whatever it returned; RunOperation
|
||||||
|
// returns errInterrupted instead.
|
||||||
func RunOperation(
|
func RunOperation(
|
||||||
ctx context.Context, opts AppOptions,
|
ctx context.Context, opts AppOptions,
|
||||||
op func(v *vaultik.Vaultik) error, report func(err error),
|
op func(v *vaultik.Vaultik) error, report func(err error),
|
||||||
) error {
|
) error {
|
||||||
var (
|
var (
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
failed bool
|
finished bool // op returned before any interrupt cancelled it
|
||||||
|
failed bool // op finished with an error
|
||||||
)
|
)
|
||||||
|
|
||||||
opts.Invokes = append(opts.Invokes,
|
opts.Invokes = append(opts.Invokes,
|
||||||
@@ -241,11 +244,21 @@ func RunOperation(
|
|||||||
OnStart: func(_ context.Context) error {
|
OnStart: func(_ context.Context) error {
|
||||||
stop = v.StartOperation(func() {
|
stop = v.StartOperation(func() {
|
||||||
err := op(v)
|
err := op(v)
|
||||||
if err != nil && !errors.Is(err, context.Canceled) {
|
|
||||||
report(err)
|
// Only stop, called from OnStop below, cancels the
|
||||||
|
// Vaultik context, so a live context means no
|
||||||
|
// interrupt cancelled op. Check the context, not
|
||||||
|
// err: an interrupted op need not return
|
||||||
|
// context.Canceled (`snapshot verify --json`
|
||||||
|
// returns a verification failure).
|
||||||
|
if v.Context().Err() == nil {
|
||||||
|
if err != nil {
|
||||||
|
report(err)
|
||||||
|
}
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
failed = true
|
finished = true
|
||||||
|
failed = err != nil
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,28 +291,34 @@ func RunOperation(
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// The goroutine sets failed before triggering the shutdown that lets
|
// RunWithApp returns only after the app was asked to stop, either by
|
||||||
// RunWithApp return, so the write is in place by the time we read it.
|
// an interrupt or by the goroutine's Shutdown call. When op finished
|
||||||
|
// without being cancelled, the goroutine set finished before that
|
||||||
|
// call. So if finished is unset here, an interrupt stopped the app,
|
||||||
|
// and op either returned after it was cancelled or is still running
|
||||||
|
// because the shutdown timed out.
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
|
|
||||||
if failed {
|
switch {
|
||||||
|
case !finished:
|
||||||
|
return errInterrupted
|
||||||
|
case failed:
|
||||||
return errReported
|
return errReported
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// runVaultikApp runs the standard single-operation command lifecycle
|
// runVaultikApp runs the standard single-operation command lifecycle
|
||||||
// shared by the snapshot list/purge/remove and remote nuke subcommands:
|
// shared by the snapshot list/files/purge/remove and remote nuke subcommands:
|
||||||
// resolve the config, then run op against the Vaultik instance through
|
// resolve the config, then run op against the Vaultik instance through
|
||||||
// RunOperation, reporting a failure prefixed with failMsg (suppressed
|
// RunOperation, reporting a failure prefixed with failMsg on stderr. mode
|
||||||
// while suppressErrors is true, e.g. under --json). mode says whether the
|
// says whether the command takes the PID lock. jsonOutput marks a command
|
||||||
// command takes the PID lock. jsonOutput marks a command whose stdout is a
|
// whose stdout is a JSON document: it quiets the UI but, unlike Quiet,
|
||||||
// JSON document: it quiets the UI but, unlike Quiet, leaves the stderr log
|
// leaves the stderr log level alone.
|
||||||
// level alone.
|
|
||||||
func runVaultikApp(
|
func runVaultikApp(
|
||||||
cmd *cobra.Command, mode lockMode, jsonOutput, suppressErrors bool,
|
cmd *cobra.Command, mode lockMode, jsonOutput bool,
|
||||||
failMsg string, op func(v *vaultik.Vaultik) error,
|
failMsg string, op func(v *vaultik.Vaultik) error,
|
||||||
) error {
|
) error {
|
||||||
configPath, err := ResolveConfigPath()
|
configPath, err := ResolveConfigPath()
|
||||||
@@ -319,11 +338,7 @@ func runVaultikApp(
|
|||||||
},
|
},
|
||||||
Mode: mode,
|
Mode: mode,
|
||||||
}, op, func(err error) {
|
}, op, func(err error) {
|
||||||
if suppressErrors {
|
log.Info(failMsg, "error", err)
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Error(failMsg, "error", err)
|
|
||||||
ReportErrorf("%s: %v", failMsg, err)
|
ReportErrorf("%s: %v", failMsg, err)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -335,8 +350,7 @@ func runVaultikApp(
|
|||||||
// only one runs at a time; a read-only command runs without it and is not
|
// only one runs at a time; a read-only command runs without it and is not
|
||||||
// blocked while a mutator holds the lock (opts.Mode).
|
// blocked while a mutator holds the lock (opts.Mode).
|
||||||
func RunWithApp(ctx context.Context, opts AppOptions) error {
|
func RunWithApp(ctx context.Context, opts AppOptions) error {
|
||||||
release, err := acquireLockIfMutating(opts.Mode,
|
release, err := acquireLockIfMutating(opts.Mode, pidlock.Dir())
|
||||||
filepath.Join(xdg.DataHome, "vaultik"))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
+47
-40
@@ -2,58 +2,65 @@ package cli //nolint:testpackage // needs access to unexported cleanStartupError
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"go.uber.org/fx"
|
||||||
|
"sneak.berlin/go/vaultik/internal/config"
|
||||||
"sneak.berlin/go/vaultik/internal/pidlock"
|
"sneak.berlin/go/vaultik/internal/pidlock"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestCleanStartupError starts a real fx app whose config has a
|
||||||
|
// blob_size_limit below the minimum. fx puts annotations naming the
|
||||||
|
// functions it was building in front of the config error; only those
|
||||||
|
// may be removed, although the config error itself contains "): ".
|
||||||
func TestCleanStartupError(t *testing.T) {
|
func TestCleanStartupError(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
tests := []struct {
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
name string
|
|
||||||
in string
|
err := os.WriteFile(path, []byte("snapshots:\n"+
|
||||||
want string
|
" test:\n"+
|
||||||
}{
|
" paths: [/tmp/vaultik-test-source]\n"+
|
||||||
{
|
"storage_url: file:///tmp/vaultik-test-storage\n"+
|
||||||
name: "real fx error chain",
|
"chunk_size: 10MB\n"+
|
||||||
in: `could not build arguments for function ` +
|
"blob_size_limit: 30MB\n"), 0o600)
|
||||||
`"sneak.berlin/go/vaultik/internal/cli".newSnapshotCreateCommand.func1.1 ` +
|
if err != nil {
|
||||||
`(/Users/user/dev/vaultik/internal/cli/snapshot.go:71): ` +
|
t.Fatalf("write config: %v", err)
|
||||||
`failed to build *vaultik.Vaultik: ` +
|
|
||||||
`could not build arguments for function ` +
|
|
||||||
`"sneak.berlin/go/vaultik/internal/vaultik".New ` +
|
|
||||||
`(/Users/user/dev/vaultik/internal/vaultik/vaultik.go:59): ` +
|
|
||||||
`failed to build storage.Storer: ` +
|
|
||||||
`received non-nil error from function ` +
|
|
||||||
`"sneak.berlin/go/vaultik/internal/storage".NewStorer ` +
|
|
||||||
`(/Users/user/dev/vaultik/internal/storage/module.go:23): ` +
|
|
||||||
`creating base path: mkdir /Volumes/BACKUPS: permission denied`,
|
|
||||||
want: `creating base path: mkdir /Volumes/BACKUPS: permission denied`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "no fx wrapping",
|
|
||||||
in: "plain error",
|
|
||||||
want: "plain error",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "single fx wrapping",
|
|
||||||
in: `received non-nil error from function "foo" (file.go:1): underlying problem`,
|
|
||||||
want: "underlying problem",
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
app := fx.New(
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
fx.NopLogger,
|
||||||
t.Parallel()
|
fx.Supply(config.Path(path)),
|
||||||
|
config.Module,
|
||||||
|
fx.Invoke(func(*config.Config) {}),
|
||||||
|
)
|
||||||
|
|
||||||
//nolint:err113 // test constructs errors from table input
|
err = app.Start(t.Context())
|
||||||
got := cleanStartupError(errors.New(tt.in)).Error()
|
if err == nil {
|
||||||
if got != tt.want {
|
t.Fatal("app started; want a blob_size_limit error")
|
||||||
t.Errorf("got %q, want %q", got, tt.want)
|
}
|
||||||
}
|
|
||||||
})
|
want := "failed to load config: invalid config: blob_size_limit must " +
|
||||||
|
"be at least the largest chunk the chunker can emit (chunk_size " +
|
||||||
|
"times the FastCDC size spread): need at least 40000000 bytes"
|
||||||
|
|
||||||
|
got := cleanStartupError(err).Error()
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("got %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCleanStartupErrorNotFromFx checks that an error fx did not wrap is
|
||||||
|
// shown unchanged.
|
||||||
|
func TestCleanStartupErrorNotFromFx(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
//nolint:err113 // a one-off error standing in for a startup failure
|
||||||
|
got := cleanStartupError(errors.New("plain error")).Error()
|
||||||
|
if got != "plain error" {
|
||||||
|
t.Errorf("got %q, want %q", got, "plain error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+229
-33
@@ -7,11 +7,16 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"runtime"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
|
"sneak.berlin/go/vaultik/internal/config"
|
||||||
"sneak.berlin/go/vaultik/internal/ui"
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,11 +31,14 @@ const configSetArgs = 2
|
|||||||
// parent config dirs (e.g. ~/.config) are conventionally traversable.
|
// parent config dirs (e.g. ~/.config) are conventionally traversable.
|
||||||
const configDirMode = 0o755
|
const configDirMode = 0o755
|
||||||
|
|
||||||
// configYAMLIndent matches the 2-space indentation of defaultConfigTemplate,
|
// configYAMLIndent matches the 2-space indentation of the default config,
|
||||||
// so `config set` writes the file back with the same indentation rather than
|
// so `config set` writes the file back with the same indentation rather than
|
||||||
// yaml.Marshal's 4-space default.
|
// yaml.Marshal's 4-space default.
|
||||||
const configYAMLIndent = 2
|
const configYAMLIndent = 2
|
||||||
|
|
||||||
|
// yamlStringTag is YAML's tag for a string scalar.
|
||||||
|
const yamlStringTag = "!!str"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errConfigExists = errors.New("config file already exists")
|
errConfigExists = errors.New("config file already exists")
|
||||||
errEmptyConfig = errors.New("empty config file")
|
errEmptyConfig = errors.New("empty config file")
|
||||||
@@ -38,9 +46,33 @@ 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")
|
||||||
|
errSetS3KeysFirst = errors.New(
|
||||||
|
"set s3.access_key_id and s3.secret_access_key first, " +
|
||||||
|
"then storage_url")
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultConfigTemplate = `# vaultik configuration
|
// storageURLKey is the config key that selects the storage backend.
|
||||||
|
const storageURLKey = "storage_url"
|
||||||
|
|
||||||
|
// macOS is the value of runtime.GOOS on macOS.
|
||||||
|
const macOS = "darwin"
|
||||||
|
|
||||||
|
// defaultConfigText returns the file `config init` writes on the operating
|
||||||
|
// system goos, named as runtime.GOOS names it. Only macOS gets the apps
|
||||||
|
// snapshot, since /Applications exists nowhere else.
|
||||||
|
func defaultConfigText(goos string) string {
|
||||||
|
if goos == macOS {
|
||||||
|
return defaultConfigHead + appsSnapshotConfig + defaultConfigTail
|
||||||
|
}
|
||||||
|
|
||||||
|
return defaultConfigHead + defaultConfigTail
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaultConfigHead is the default config up to the end of the home snapshot.
|
||||||
|
const defaultConfigHead = `# vaultik configuration
|
||||||
# Documentation: https://sneak.berlin/go/vaultik
|
# Documentation: https://sneak.berlin/go/vaultik
|
||||||
|
|
||||||
# ─── REQUIRED ────────────────────────────────────────────────────────────────
|
# ─── REQUIRED ────────────────────────────────────────────────────────────────
|
||||||
@@ -158,7 +190,10 @@ snapshots:
|
|||||||
- "/Movies/ProxyMedia"
|
- "/Movies/ProxyMedia"
|
||||||
- "/Music/iTunes/Album Artwork"
|
- "/Music/iTunes/Album Artwork"
|
||||||
- "/Pictures/iPod Photo Cache"
|
- "/Pictures/iPod Photo Cache"
|
||||||
|
`
|
||||||
|
|
||||||
|
// appsSnapshotConfig is the apps snapshot of the default config.
|
||||||
|
const appsSnapshotConfig = `
|
||||||
# Third-party applications. OS-provided apps live in /System/Applications
|
# Third-party applications. OS-provided apps live in /System/Applications
|
||||||
# on modern macOS and are never in /Applications, but Apple-installed
|
# on modern macOS and are never in /Applications, but Apple-installed
|
||||||
# App Store apps (Safari, GarageBand, iWork, iMovie) are excluded since
|
# App Store apps (Safari, GarageBand, iWork, iMovie) are excluded since
|
||||||
@@ -179,7 +214,10 @@ snapshots:
|
|||||||
- "/Steam.app"
|
- "/Steam.app"
|
||||||
- "/VirtualBox.app"
|
- "/VirtualBox.app"
|
||||||
- "/Utilities/Adobe Installers"
|
- "/Utilities/Adobe Installers"
|
||||||
|
`
|
||||||
|
|
||||||
|
// defaultConfigTail is the default config after the snapshots.
|
||||||
|
const defaultConfigTail = `
|
||||||
# Storage backend (pick ONE of the three forms below).
|
# Storage backend (pick ONE of the three forms below).
|
||||||
#
|
#
|
||||||
# S3-compatible:
|
# S3-compatible:
|
||||||
@@ -199,7 +237,7 @@ storage_url: ""
|
|||||||
# access_key_id: YOUR_ACCESS_KEY
|
# access_key_id: YOUR_ACCESS_KEY
|
||||||
# secret_access_key: YOUR_SECRET_KEY
|
# secret_access_key: YOUR_SECRET_KEY
|
||||||
# # region: us-east-1 # Default: us-east-1
|
# # region: us-east-1 # Default: us-east-1
|
||||||
# # part_size: 5MB # Multipart upload part size. Default: 5MB
|
# # part_size: 5MiB # Upload part size, 5MiB to 5GiB. Default: 5MiB
|
||||||
# # For the s3:// form, disable TLS with ?ssl=false in the URL, not use_ssl.
|
# # For the s3:// form, disable TLS with ?ssl=false in the URL, not use_ssl.
|
||||||
|
|
||||||
# ─── OPTIONAL ────────────────────────────────────────────────────────────────
|
# ─── OPTIONAL ────────────────────────────────────────────────────────────────
|
||||||
@@ -214,7 +252,7 @@ storage_url: ""
|
|||||||
|
|
||||||
# Average chunk size for content-defined chunking (FastCDC).
|
# Average chunk size for content-defined chunking (FastCDC).
|
||||||
# Smaller = better deduplication but more metadata overhead.
|
# Smaller = better deduplication but more metadata overhead.
|
||||||
# Accepts: 1MB, 10M, 64KB, etc.
|
# Minimum 1MB. Accepts: 1MB, 10M, 64MiB, etc.
|
||||||
# Default: 10MB
|
# Default: 10MB
|
||||||
# chunk_size: 10MB
|
# chunk_size: 10MB
|
||||||
|
|
||||||
@@ -229,10 +267,23 @@ storage_url: ""
|
|||||||
# Default: 3
|
# Default: 3
|
||||||
# compression_level: 3
|
# compression_level: 3
|
||||||
|
|
||||||
|
# How old a blob that no snapshot lists must be before prune deletes it,
|
||||||
|
# and how old every object in a directory under metadata/ with no manifest
|
||||||
|
# must be before prune deletes that directory. A backup uploads its blobs
|
||||||
|
# and its db.zst.age before its manifest, so on a destination shared
|
||||||
|
# between hosts or users this must be longer than the longest backup run.
|
||||||
|
# It does not protect a blob a backup reuses from an earlier run that
|
||||||
|
# stopped before its manifest: that blob keeps the time of its first
|
||||||
|
# upload, so a prune can delete it.
|
||||||
|
# Accepts: 36h, 90m, etc. 0s deletes such blobs and directories at once.
|
||||||
|
# Default: 24h
|
||||||
|
# prune_grace_period: 24h
|
||||||
|
|
||||||
# Hostname used in snapshot IDs. Default: system hostname.
|
# Hostname used in snapshot IDs. Default: system hostname.
|
||||||
# hostname: myserver
|
# hostname: myserver
|
||||||
|
|
||||||
# Path to the local SQLite index database.
|
# Path to the local SQLite index database. It must be an absolute path;
|
||||||
|
# ~ is expanded.
|
||||||
# Default: the platform data directory, e.g.
|
# Default: the platform data directory, e.g.
|
||||||
# macOS: ~/Library/Application Support/vaultik/index.sqlite
|
# macOS: ~/Library/Application Support/vaultik/index.sqlite
|
||||||
# Linux: ~/.local/share/vaultik/index.sqlite
|
# Linux: ~/.local/share/vaultik/index.sqlite
|
||||||
@@ -245,6 +296,12 @@ func NewConfigCommand() *cobra.Command {
|
|||||||
Use: "config",
|
Use: "config",
|
||||||
Short: "Manage the configuration file",
|
Short: "Manage the configuration file",
|
||||||
Long: "Commands for creating, editing, and querying the vaultik config file.",
|
Long: "Commands for creating, editing, and querying the vaultik config file.",
|
||||||
|
// cobra checks Args only on a command that has a Run: without
|
||||||
|
// one, a mistyped subcommand printed help and exited 0.
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
Run: func(cmd *cobra.Command, _ []string) {
|
||||||
|
_ = cmd.Help()
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd.AddCommand(newConfigInitCommand())
|
cmd.AddCommand(newConfigInitCommand())
|
||||||
@@ -283,7 +340,8 @@ on macOS, ~/.config/ on Linux, /etc/vaultik/ as root).`,
|
|||||||
return fmt.Errorf("creating config directory %s: %w", dir, err)
|
return fmt.Errorf("creating config directory %s: %w", dir, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode)
|
err = os.WriteFile(path, []byte(defaultConfigText(runtime.GOOS)),
|
||||||
|
configFileMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("writing config file: %w", err)
|
return fmt.Errorf("writing config file: %w", err)
|
||||||
}
|
}
|
||||||
@@ -317,8 +375,15 @@ func newConfigEditCommand() *cobra.Command {
|
|||||||
editor = "vi"
|
editor = "vi"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Run $EDITOR through the shell, as git does, so a value
|
||||||
|
// with arguments such as "code --wait" works. The path
|
||||||
|
// goes in as an argument ("$@"), not into the command
|
||||||
|
// text, so a path with spaces or quotes arrives whole.
|
||||||
|
// sh -c takes the word after the command as $0, which
|
||||||
|
// is why editor appears twice.
|
||||||
//nolint:gosec // G204: launching the operator's own $EDITOR is the point
|
//nolint:gosec // G204: launching the operator's own $EDITOR is the point
|
||||||
ed := exec.CommandContext(cmd.Context(), editor, path)
|
ed := exec.CommandContext(cmd.Context(),
|
||||||
|
"sh", "-c", editor+` "$@"`, editor, path)
|
||||||
ed.Stdin = os.Stdin
|
ed.Stdin = os.Stdin
|
||||||
ed.Stdout = os.Stdout
|
ed.Stdout = os.Stdout
|
||||||
ed.Stderr = os.Stderr
|
ed.Stderr = os.Stderr
|
||||||
@@ -379,8 +444,16 @@ 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. Intermediate maps
|
the file back, preserving comments and formatting. Missing keys along
|
||||||
are created as needed.
|
the path are created: as a list when the next path element is a
|
||||||
|
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 is checked one setting at a time. Examples
|
||||||
|
are the file config init writes before storage_url is set, and one
|
||||||
|
with a ${ENV:...} reference to a variable not set in this shell. In
|
||||||
|
such a config, an unknown key or a value of the wrong type is refused.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
vaultik config set storage_url "file:///mnt/backups"
|
vaultik config set storage_url "file:///mnt/backups"
|
||||||
@@ -410,7 +483,21 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = yamlPathSet(root, strings.Split(key, "."), value)
|
oldData, err := marshalConfigYAML(root)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("marshaling config: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
keys := strings.Split(key, ".")
|
||||||
|
|
||||||
|
if keys[0] != config.EnvSection {
|
||||||
|
_, err = config.SettingType(keys)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err = yamlPathSet(root, keys, value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -420,6 +507,21 @@ 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 wouldNotLoadError(key, 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)
|
||||||
@@ -441,8 +543,75 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// wouldNotLoadError returns the refusal of a change to key that vaultik
|
||||||
|
// would not load for reason. When storage_url moves to s3:// before the S3
|
||||||
|
// credentials are set, it says to set them first: they can be set while
|
||||||
|
// the old storage_url is still in place.
|
||||||
|
func wouldNotLoadError(key string, reason error) error {
|
||||||
|
if key == storageURLKey &&
|
||||||
|
(errors.Is(reason, config.ErrS3KeyIDRequired) ||
|
||||||
|
errors.Is(reason, config.ErrS3SecretRequired)) {
|
||||||
|
return fmt.Errorf("%w: %w; %w", errWouldNotLoad, reason,
|
||||||
|
errSetS3KeysFirst)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("%w: %w", errWouldNotLoad, reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 the default config. 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
|
||||||
// to preserve formatting.
|
// to preserve formatting.
|
||||||
func marshalConfigYAML(root *yaml.Node) ([]byte, error) {
|
func marshalConfigYAML(root *yaml.Node) ([]byte, error) {
|
||||||
@@ -547,8 +716,8 @@ func yamlPathGet(root *yaml.Node, keys []string) (*yaml.Node, error) {
|
|||||||
return node, nil
|
return node, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// yamlPathSet navigates a dotted key path, creating intermediate maps as
|
// yamlPathSet navigates a dotted key path, creating missing keys as needed,
|
||||||
// needed, and sets the final key to the given scalar value. Numeric path
|
// 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 {
|
||||||
@@ -561,12 +730,12 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error {
|
|||||||
node = node.Content[0]
|
node = node.Content[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
for i, key := range keys {
|
for i := 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, key, value, last)
|
node = yamlSetInMapping(node, keys, i, 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 {
|
||||||
@@ -583,17 +752,38 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// config.Load reads the file through untyped YAML, which turns an
|
||||||
|
// unquoted 00112233 into the number 38043 and 1e5 into 100000. Tagging
|
||||||
|
// a string setting as a string makes the encoder quote such a value.
|
||||||
|
// Other settings stay unquoted, so compression_level 9 is a number.
|
||||||
|
// The encoder refuses to write a value that is not valid UTF-8 as a
|
||||||
|
// string. Left untagged, such a value is written as base64 !!binary and
|
||||||
|
// loads back unchanged.
|
||||||
|
if configKeyIsString(keys) && utf8.ValidString(value) {
|
||||||
|
node.Tag = yamlStringTag
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// yamlSetInMapping resolves (creating if needed) the value node for key
|
// configKeyIsString reports whether the dotted key names a string in
|
||||||
// within a mapping node, setting it to value when it is the final path
|
// config.Config, as s3.access_key_id and snapshots.home.exclude.0 do.
|
||||||
// element, and returns the node to descend into.
|
func configKeyIsString(keys []string) bool {
|
||||||
func yamlSetInMapping(node *yaml.Node, key, value string, last bool) *yaml.Node {
|
typ, err := config.SettingType(keys)
|
||||||
|
|
||||||
|
return err == nil && typ.Kind() == reflect.String
|
||||||
|
}
|
||||||
|
|
||||||
|
// yamlSetInMapping resolves (creating if needed) the value node for the
|
||||||
|
// path element keys[i] within a mapping node, setting it to value when it
|
||||||
|
// is the final path element, and returns the node to descend into.
|
||||||
|
func yamlSetInMapping(
|
||||||
|
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 == key {
|
if node.Content[j].Value == keys[i] {
|
||||||
valueNode = node.Content[j+1]
|
valueNode = node.Content[j+1]
|
||||||
|
|
||||||
break
|
break
|
||||||
@@ -601,13 +791,8 @@ func yamlSetInMapping(node *yaml.Node, key, value string, last bool) *yaml.Node
|
|||||||
}
|
}
|
||||||
|
|
||||||
if valueNode == nil {
|
if valueNode == nil {
|
||||||
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key}
|
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: keys[i]}
|
||||||
|
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)
|
||||||
@@ -635,12 +820,7 @@ func yamlSetInSequence(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if idx == len(node.Content) {
|
if idx == len(node.Content) {
|
||||||
newNode := &yaml.Node{Kind: yaml.MappingNode}
|
node.Content = append(node.Content, newPathNode(keys, i, value))
|
||||||
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)
|
||||||
}
|
}
|
||||||
@@ -648,6 +828,22 @@ 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
|
||||||
|
|||||||
+518
-14
@@ -2,8 +2,10 @@ package cli //nolint:testpackage // exercises unexported yamlPathGet/yamlPathSet
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -12,14 +14,15 @@ import (
|
|||||||
"sneak.berlin/go/vaultik/internal/ui"
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestDefaultConfigTemplateParses ensures the init template is valid YAML
|
// TestDefaultConfigParsesOnMacOS ensures the config `config init` writes on
|
||||||
// that unmarshals into the Config struct with the expected snapshots.
|
// macOS is valid YAML that unmarshals into the Config struct with the
|
||||||
func TestDefaultConfigTemplateParses(t *testing.T) {
|
// expected snapshots.
|
||||||
|
func TestDefaultConfigParsesOnMacOS(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
var cfg config.Config
|
var cfg config.Config
|
||||||
|
|
||||||
err := yaml.Unmarshal([]byte(defaultConfigTemplate), &cfg)
|
err := yaml.Unmarshal([]byte(defaultConfigText("darwin")), &cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("default config template is not valid YAML: %v", err)
|
t.Fatalf("default config template is not valid YAML: %v", err)
|
||||||
}
|
}
|
||||||
@@ -57,24 +60,60 @@ func TestDefaultConfigTemplateParses(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestConfigSetRecipientOnFreshConfig follows the README quickstart: on the
|
// TestDefaultConfigOnLinux checks that the config `config init` writes on
|
||||||
// file `config init` writes, `config set age_recipients.0` and
|
// Linux loads with its home snapshot and without the apps snapshot, whose
|
||||||
// `config set storage_url` give a config that loads with that recipient.
|
// /Applications exists only on macOS.
|
||||||
func TestConfigSetRecipientOnFreshConfig(t *testing.T) {
|
func TestDefaultConfigOnLinux(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(defaultConfigText("linux")), configFileMode)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false),
|
||||||
|
path, "storage_url", "file:///mnt/backups")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config set storage_url: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config.Load: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := cfg.Snapshots["home"]; !ok {
|
||||||
|
t.Error("expected 'home' snapshot in the Linux default config")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := cfg.Snapshots["apps"]; ok {
|
||||||
|
t.Error("the Linux default config should have no 'apps' snapshot")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// testRecipient is a valid age public key.
|
||||||
|
const testRecipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj"
|
||||||
|
|
||||||
|
// TestConfigSetRecipientOnFreshConfig follows the README quickstart: on the
|
||||||
|
// file `config init` writes, `config set age_recipients.0` and
|
||||||
|
// `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) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(defaultConfigText(macOS)), configFileMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("write config: %v", err)
|
t.Fatalf("write config: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
out := ui.NewWithColor(&bytes.Buffer{}, false)
|
out := ui.NewWithColor(&bytes.Buffer{}, false)
|
||||||
|
|
||||||
err = writeConfigSet(out, path, "age_recipients.0", recipient)
|
err = writeConfigSet(out, path, "age_recipients.0", testRecipient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("config set age_recipients.0: %v", err)
|
t.Fatalf("config set age_recipients.0: %v", err)
|
||||||
}
|
}
|
||||||
@@ -89,9 +128,450 @@ 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] != recipient {
|
if len(cfg.AgeRecipients) != 1 || cfg.AgeRecipients[0] != testRecipient {
|
||||||
t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, recipient)
|
t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, testRecipient)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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:
|
||||||
|
- "~"
|
||||||
|
`
|
||||||
|
|
||||||
|
// testS3URL is an S3 storage_url, which needs credentials to load.
|
||||||
|
const testS3URL = "s3://bucket/prefix?endpoint=https://s3.example.com"
|
||||||
|
|
||||||
|
// configWithS3Keys loads: its storage_url is testS3URL and both S3 keys are
|
||||||
|
// set.
|
||||||
|
const configWithS3Keys = storageURLKey + ": " + testS3URL + `
|
||||||
|
s3:
|
||||||
|
access_key_id: AKIAEXAMPLE
|
||||||
|
secret_access_key: example-secret
|
||||||
|
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 an unknown key or 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
|
||||||
|
}{
|
||||||
|
// Keys that no setting has, on a config that loads and on one
|
||||||
|
// that does not.
|
||||||
|
{configWithoutRecipients, "nosuchkey", "1",
|
||||||
|
`unknown config key "nosuchkey"`},
|
||||||
|
{configWithoutRecipients, "snapshots.home.exlude", "/tmp",
|
||||||
|
`unknown config key "snapshots.home.exlude"`},
|
||||||
|
{defaultConfigText(macOS), "compression_lvl", "9",
|
||||||
|
`unknown config key "compression_lvl"`},
|
||||||
|
// 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",
|
||||||
|
`chunk_size: "fast" is not a size`},
|
||||||
|
// 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"},
|
||||||
|
// An s3:// URL before its credentials names them.
|
||||||
|
{configWithoutRecipients, storageURLKey, testS3URL,
|
||||||
|
"s3.access_key_id is required for s3:// URLs; " +
|
||||||
|
"set s3.access_key_id and s3.secret_access_key first"},
|
||||||
|
{configWithoutRecipients + "s3:\n access_key_id: AKIAEXAMPLE\n",
|
||||||
|
storageURLKey, testS3URL,
|
||||||
|
"s3.secret_access_key is required for s3:// URLs; " +
|
||||||
|
"set s3.access_key_id and s3.secret_access_key first"},
|
||||||
|
// 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.
|
||||||
|
{defaultConfigText(macOS), "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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConfigSetS3KeysBeforeStorageURL checks that the order the refusal
|
||||||
|
// gives works on a config that loads with a file:// storage_url.
|
||||||
|
func TestConfigSetS3KeysBeforeStorageURL(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)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, set := range [][2]string{
|
||||||
|
{"s3.access_key_id", "AKIAEXAMPLE"},
|
||||||
|
{"s3.secret_access_key", "example-secret"},
|
||||||
|
{storageURLKey, testS3URL},
|
||||||
|
} {
|
||||||
|
err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false),
|
||||||
|
path, set[0], set[1])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config set %s: %v", set[0], 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), storageURLKey+": "+testS3URL) {
|
||||||
|
t.Errorf("config set storage_url wrote:\n%s", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConfigSetRefusesClearingS3Key checks that clearing s3.access_key_id on
|
||||||
|
// a config with an s3:// storage_url is refused without saying to set the
|
||||||
|
// S3 keys first. That advice is only for a change to storage_url.
|
||||||
|
func TestConfigSetRefusesClearingS3Key(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const key = "s3.access_key_id"
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(configWithS3Keys), configFileMode)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), path, key, "")
|
||||||
|
if !errors.Is(err, errWouldNotLoad) {
|
||||||
|
t.Errorf("clearing %s gives error %v, want one saying %q",
|
||||||
|
key, err, errWouldNotLoad)
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, errSetS3KeysFirst) {
|
||||||
|
t.Errorf("clearing %s gives error %v, want one not saying %q",
|
||||||
|
key, err, errSetS3KeysFirst)
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if string(data) != configWithS3Keys {
|
||||||
|
t.Errorf("clearing %s changed the file to:\n%s", key, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConfigSetWritesEnvSection checks that config set writes a key under
|
||||||
|
// the top-level env section, whose keys are not settings, on a config that
|
||||||
|
// loads.
|
||||||
|
func TestConfigSetWritesEnvSection(t *testing.T) {
|
||||||
|
const name = "VAULTIK_TEST_CONFIG_SET_ENV"
|
||||||
|
|
||||||
|
// Loading the changed config sets the variable; t.Setenv restores it
|
||||||
|
// after the test.
|
||||||
|
t.Setenv(name, "")
|
||||||
|
|
||||||
|
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, "env."+name, "value")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config set env.%s: %v", name, 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), "env:\n "+name+": value\n") {
|
||||||
|
t.Errorf("config set env.%s wrote:\n%s", name, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConfigSetStringLooksLikeNumber sets string settings to values that
|
||||||
|
// YAML reads as numbers or booleans when they are unquoted, and checks that
|
||||||
|
// config.Load returns each one unchanged.
|
||||||
|
func TestConfigSetStringLooksLikeNumber(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
key string
|
||||||
|
value string
|
||||||
|
field func(cfg *config.Config) string
|
||||||
|
}{
|
||||||
|
{"s3.access_key_id", "00112233",
|
||||||
|
func(cfg *config.Config) string { return cfg.S3.AccessKeyID }},
|
||||||
|
{"s3.secret_access_key", "12345678901234567890123456789012",
|
||||||
|
func(cfg *config.Config) string { return cfg.S3.SecretAccessKey }},
|
||||||
|
{"hostname", "007",
|
||||||
|
func(cfg *config.Config) string { return cfg.Hostname }},
|
||||||
|
{"s3.prefix", "1e5",
|
||||||
|
func(cfg *config.Config) string { return cfg.S3.Prefix }},
|
||||||
|
{"s3.bucket", "true",
|
||||||
|
func(cfg *config.Config) string { return cfg.S3.Bucket }},
|
||||||
|
{"s3.region", "FALSE",
|
||||||
|
func(cfg *config.Config) string { return cfg.S3.Region }},
|
||||||
|
{"snapshots.home.exclude.0", "1.10",
|
||||||
|
func(cfg *config.Config) string { return cfg.Snapshots["home"].Exclude[0] }},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.key+"="+tt.value, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := loadAfterConfigSet(t, tt.key, tt.value)
|
||||||
|
|
||||||
|
got := tt.field(cfg)
|
||||||
|
if got != tt.value {
|
||||||
|
t.Errorf("%s = %q after config set %q", tt.key, got, tt.value)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConfigSetNonUTF8Path checks that config set still accepts a value that
|
||||||
|
// is not valid UTF-8, such as a path with a Latin-1 file name, and that
|
||||||
|
// config.Load returns it unchanged.
|
||||||
|
func TestConfigSetNonUTF8Path(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const dir = "/srv/caf\xe9"
|
||||||
|
|
||||||
|
cfg := loadAfterConfigSet(t, "snapshots.home.paths.0", dir)
|
||||||
|
|
||||||
|
got := cfg.Snapshots["home"].Paths[0]
|
||||||
|
if got != dir {
|
||||||
|
t.Errorf("snapshots.home.paths.0 = %q, want %q", got, dir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConfigSetNumberStaysNumber checks that a number set for an integer
|
||||||
|
// setting is still read as a number, not as a quoted string.
|
||||||
|
func TestConfigSetNumberStaysNumber(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const level = 9
|
||||||
|
|
||||||
|
cfg := loadAfterConfigSet(t, "compression_level", strconv.Itoa(level))
|
||||||
|
|
||||||
|
if cfg.CompressionLevel != level {
|
||||||
|
t.Errorf("compression_level = %d, want %d", cfg.CompressionLevel, level)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadAfterConfigSet writes the file `config init` writes, sets storage_url
|
||||||
|
// to a local directory so that the file passes validation, applies
|
||||||
|
// `config set key value` and returns what config.Load reads back.
|
||||||
|
func loadAfterConfigSet(t *testing.T, key, value string) *config.Config {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(defaultConfigText(macOS)), configFileMode)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
out := ui.NewWithColor(&bytes.Buffer{}, false)
|
||||||
|
|
||||||
|
err = writeConfigSet(out, path, "storage_url", "file:///mnt/backups")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config set storage_url: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = writeConfigSet(out, path, key, value)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config set %s: %v", key, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("config.Load: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg
|
||||||
}
|
}
|
||||||
|
|
||||||
const testYAML = `# top comment
|
const testYAML = `# top comment
|
||||||
@@ -336,6 +816,30 @@ func TestWriteConfigSetTightensMode(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestConfigEditEditorWithArgument checks that an $EDITOR carrying an
|
||||||
|
// argument works and that a config path with a space reaches it whole.
|
||||||
|
// The "editor" is cp with the replacement file as its argument, so the
|
||||||
|
// config ends up with the replacement's content only if both arrived.
|
||||||
|
func TestConfigEditEditorWithArgument(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
path := seedFile(t, dir, "my config.yml", "compression_level: 3\n")
|
||||||
|
edited := seedFile(t, dir, "edited.yml", "compression_level: 9\n")
|
||||||
|
|
||||||
|
setRootFlags(t, RootFlags{ConfigPath: path})
|
||||||
|
t.Setenv("EDITOR", "cp '"+edited+"'")
|
||||||
|
|
||||||
|
mustExecute(t, newConfigEditCommand())
|
||||||
|
|
||||||
|
data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading config back: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if string(data) != "compression_level: 9\n" {
|
||||||
|
t.Errorf("config after edit = %q, want the edited content", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func splitPath(s string) []string {
|
func splitPath(s string) []string {
|
||||||
return strings.Split(s, ".")
|
return strings.Split(s, ".")
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-13
@@ -6,7 +6,9 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"sneak.berlin/go/vaultik/internal/config"
|
"sneak.berlin/go/vaultik/internal/config"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
"sneak.berlin/go/vaultik/internal/log"
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewDatabaseCommand creates the database command group
|
// NewDatabaseCommand creates the database command group
|
||||||
@@ -15,6 +17,12 @@ func NewDatabaseCommand() *cobra.Command {
|
|||||||
Use: "database",
|
Use: "database",
|
||||||
Short: "Manage the local state database",
|
Short: "Manage the local state database",
|
||||||
Long: `Commands for managing the local SQLite state database.`,
|
Long: `Commands for managing the local SQLite state database.`,
|
||||||
|
// cobra checks Args only on a command that has a Run: without
|
||||||
|
// one, a mistyped subcommand printed help and exited 0.
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
Run: func(cmd *cobra.Command, _ []string) {
|
||||||
|
_ = cmd.Help()
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd.AddCommand(
|
cmd.AddCommand(
|
||||||
@@ -84,27 +92,25 @@ Use --force to skip the confirmation prompt.`,
|
|||||||
|
|
||||||
var confirm string
|
var confirm string
|
||||||
|
|
||||||
_, err = fmt.Scanln(&confirm)
|
// A failure to read the answer means no confirmation.
|
||||||
|
_, err = fmt.Fscanln(cmd.InOrStdin(), &confirm)
|
||||||
if err != nil || confirm != "yes" {
|
if err != nil || confirm != "yes" {
|
||||||
_, _ = fmt.Fprintln(w, "Aborted.")
|
_, _ = fmt.Fprintln(w, "Aborted.")
|
||||||
|
|
||||||
//nolint:nilerr // a failed/aborted confirmation is a clean abort
|
return vaultik.ErrNotConfirmed
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete the database file
|
// Delete the database file and its side files. A side file
|
||||||
err = os.Remove(dbPath)
|
// may not exist, so only failing to delete the database file
|
||||||
if err != nil {
|
// is an error.
|
||||||
return fmt.Errorf("failed to delete database: %w", err)
|
for _, indexFile := range database.IndexFiles(dbPath) {
|
||||||
|
err = os.Remove(indexFile)
|
||||||
|
if err != nil && indexFile == dbPath {
|
||||||
|
return fmt.Errorf("failed to delete database: %w", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Also delete WAL and SHM files if they exist
|
|
||||||
walPath := dbPath + "-wal"
|
|
||||||
shmPath := dbPath + "-shm"
|
|
||||||
_ = os.Remove(walPath) // Ignore errors - files may not exist
|
|
||||||
_ = os.Remove(shmPath)
|
|
||||||
|
|
||||||
out.Infof("Local state database deleted: %s.", dbPath)
|
out.Infof("Local state database deleted: %s.", dbPath)
|
||||||
log.Info("Local state database deleted", "path", dbPath)
|
log.Info("Local state database deleted", "path", dbPath)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package cli //nolint:testpackage // sets the unexported rootFlags directly
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestDatabaseDeleteDeclinedIsError checks that answering anything but
|
||||||
|
// "yes" keeps the database and returns ErrNotConfirmed, so the command
|
||||||
|
// exits non-zero.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // mutates the process-global rootFlags
|
||||||
|
func TestDatabaseDeleteDeclinedIsError(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
dbPath, cfgPath := seedDatabaseDeleteConfig(t, dir)
|
||||||
|
|
||||||
|
setRootFlags(t, RootFlags{ConfigPath: cfgPath})
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
|
||||||
|
cmd := newDatabaseDeleteCommand()
|
||||||
|
cmd.SetOut(&out)
|
||||||
|
cmd.SetErr(io.Discard)
|
||||||
|
cmd.SetIn(strings.NewReader("no\n"))
|
||||||
|
cmd.SetArgs(nil)
|
||||||
|
|
||||||
|
err := cmd.Execute()
|
||||||
|
if !errors.Is(err, vaultik.ErrNotConfirmed) {
|
||||||
|
t.Errorf("declined database delete returned %v, want %v",
|
||||||
|
err, vaultik.ErrNotConfirmed)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = os.Stat(dbPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("declined database delete removed the file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(out.String(), "Aborted.") {
|
||||||
|
t.Errorf("declined database delete printed %q, want Aborted.",
|
||||||
|
out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDatabaseDeleteRemovesSideFiles checks that the side files SQLite
|
||||||
|
// keeps beside the database file are deleted with it.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // mutates the process-global rootFlags
|
||||||
|
func TestDatabaseDeleteRemovesSideFiles(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
dbPath, cfgPath := seedDatabaseDeleteConfig(t, dir)
|
||||||
|
|
||||||
|
indexFiles := database.IndexFiles(dbPath)
|
||||||
|
for _, indexFile := range indexFiles {
|
||||||
|
seedFile(t, dir, filepath.Base(indexFile), "data")
|
||||||
|
}
|
||||||
|
|
||||||
|
setRootFlags(t, RootFlags{ConfigPath: cfgPath})
|
||||||
|
|
||||||
|
mustExecute(t, newDatabaseDeleteCommand(), "--force")
|
||||||
|
|
||||||
|
for _, indexFile := range indexFiles {
|
||||||
|
_, err := os.Stat(indexFile)
|
||||||
|
if !os.IsNotExist(err) {
|
||||||
|
t.Errorf("database delete left %s: stat err = %v", indexFile, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+32
-13
@@ -15,17 +15,28 @@ import (
|
|||||||
// the startup banner.
|
// the startup banner.
|
||||||
const shortCommitLen = 12
|
const shortCommitLen = 12
|
||||||
|
|
||||||
|
// exitCodeInterrupted is the exit status of a command that SIGINT or
|
||||||
|
// SIGTERM stopped. It is 128 plus SIGINT's number, 2, which is what a
|
||||||
|
// shell reports for a command stopped by Ctrl-C.
|
||||||
|
const exitCodeInterrupted = 130
|
||||||
|
|
||||||
// Entry is the main entry point for the CLI application.
|
// Entry is the main entry point for the CLI application.
|
||||||
// It prints the startup banner to stdout (unless a banner-suppressing
|
// It first calls globals.FillUnsetFromBuildInfo, which fills in the
|
||||||
|
// version, commit and commit date that the linker flags did not set.
|
||||||
|
// It prints the startup banner to stderr (unless a banner-suppressing
|
||||||
// flag is present in os.Args — see bannerSuppressedInArgs), executes the
|
// flag is present in os.Args — see bannerSuppressedInArgs), executes the
|
||||||
// root cobra command, and routes any returned error through the
|
// root cobra command, and routes any returned error through the
|
||||||
// ui.Writer so the user sees a properly formatted "🛑 ERROR:" line.
|
// ui.Writer so the user sees a properly formatted "🛑 ERROR:" line.
|
||||||
|
// The banner goes to stderr because stdout carries only the output the
|
||||||
|
// user asked for, such as a completion script or a `config get` value.
|
||||||
//
|
//
|
||||||
// It returns the process exit code (0 on success, 1 on error) rather
|
// It returns the process exit code (0 on success, 130 when interrupted,
|
||||||
// than calling os.Exit, so that main's deferred profile writers run
|
// 1 on any other error) rather than calling os.Exit, so that main's
|
||||||
// before the process ends. See run in cmd/vaultik/main.go.
|
// deferred profile writers run before the process ends. See run in
|
||||||
|
// cmd/vaultik/main.go.
|
||||||
func Entry() int {
|
func Entry() int {
|
||||||
emitStartupBanner(os.Args[1:], os.Stdout)
|
globals.FillUnsetFromBuildInfo()
|
||||||
|
emitStartupBanner(os.Args[1:], os.Stderr)
|
||||||
|
|
||||||
rootCmd := NewRootCommand()
|
rootCmd := NewRootCommand()
|
||||||
rootCmd.SilenceErrors = true
|
rootCmd.SilenceErrors = true
|
||||||
@@ -33,14 +44,20 @@ func Entry() int {
|
|||||||
err := rootCmd.Execute()
|
err := rootCmd.Execute()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// An operation that ran inside the fx app has already reported
|
// An operation that ran inside the fx app has already reported
|
||||||
// its own failure (and suppressed it under --json); errReported
|
// its own failure (`snapshot verify --json` puts it in the
|
||||||
// says so. Printing it again here would double the error line.
|
// document instead); errReported says so. Printing it again
|
||||||
|
// here would double the error line.
|
||||||
// Every other error — bad arguments, a config that would not
|
// Every other error — bad arguments, a config that would not
|
||||||
// load — reaches Entry unreported, so it is shown here.
|
// load, an interrupt — reaches Entry unreported, so it is shown
|
||||||
|
// here.
|
||||||
if !errors.Is(err, errReported) {
|
if !errors.Is(err, errReported) {
|
||||||
ReportErrorf("%s", err.Error())
|
ReportErrorf("%s", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, errInterrupted) {
|
||||||
|
return exitCodeInterrupted
|
||||||
|
}
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,9 +66,8 @@ func Entry() int {
|
|||||||
|
|
||||||
// emitStartupBanner writes the startup banner to w unless args (the
|
// emitStartupBanner writes the startup banner to w unless args (the
|
||||||
// argument vector with the program name already stripped) contains a
|
// argument vector with the program name already stripped) contains a
|
||||||
// flag that suppresses it. Split out of Entry so that the decision — the
|
// flag that suppresses it. Split out of Entry so that the decision is
|
||||||
// only thing standing between a --json invocation and a parseable
|
// reachable from a test without running the whole CLI.
|
||||||
// stdout — is reachable from a test without running the whole CLI.
|
|
||||||
func emitStartupBanner(args []string, w io.Writer) {
|
func emitStartupBanner(args []string, w io.Writer) {
|
||||||
if bannerSuppressedInArgs(args) {
|
if bannerSuppressedInArgs(args) {
|
||||||
return
|
return
|
||||||
@@ -69,6 +85,10 @@ func emitStartupBanner(args []string, w io.Writer) {
|
|||||||
// 🛑 ERROR: format. Use it from goroutine error paths (where returning
|
// 🛑 ERROR: format. Use it from goroutine error paths (where returning
|
||||||
// an error to cobra isn't an option) and anywhere else a CLI command
|
// an error to cobra isn't an option) and anywhere else a CLI command
|
||||||
// must surface a failure outside the normal RunE return path.
|
// must surface a failure outside the normal RunE return path.
|
||||||
|
//
|
||||||
|
// This line is the one report of the failure. A caller that also logs
|
||||||
|
// the failure logs it at info level, so the record appears only under
|
||||||
|
// --verbose or --debug and the error is not printed twice.
|
||||||
func ReportErrorf(format string, args ...any) {
|
func ReportErrorf(format string, args ...any) {
|
||||||
ui.New(os.Stderr).Errorf(format, args...)
|
ui.New(os.Stderr).Errorf(format, args...)
|
||||||
}
|
}
|
||||||
@@ -86,8 +106,7 @@ func ReportErrorf(format string, args ...any) {
|
|||||||
// --json is a subcommand flag rather than a persistent one, but so is
|
// --json is a subcommand flag rather than a persistent one, but so is
|
||||||
// --cron (it exists only on `snapshot create`), so this adds no new
|
// --cron (it exists only on `snapshot create`), so this adds no new
|
||||||
// class of imprecision. The only cost of a false positive is a missing
|
// class of imprecision. The only cost of a false positive is a missing
|
||||||
// decorative banner; the cost of a false negative is a corrupt document
|
// decorative banner.
|
||||||
// on stdout, so the scan errs deliberately in that direction.
|
|
||||||
func bannerSuppressedInArgs(args []string) bool {
|
func bannerSuppressedInArgs(args []string) bool {
|
||||||
for _, a := range args {
|
for _, a := range args {
|
||||||
if a == "--" {
|
if a == "--" {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"github.com/adrg/xdg"
|
"github.com/adrg/xdg"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/globals"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Command words and flags used to build argument vectors below. They are
|
// Command words and flags used to build argument vectors below. They are
|
||||||
@@ -36,23 +37,14 @@ const (
|
|||||||
// strips it before scanning, so it has to be present.
|
// strips it before scanning, so it has to be present.
|
||||||
programName = "vaultik"
|
programName = "vaultik"
|
||||||
|
|
||||||
// someSnapshotID is any snapshot identifier: these tests never run
|
// someSnapshotID only fills the positional argument; no test needs
|
||||||
// the command, so it only has to occupy the positional argument.
|
// the snapshot to exist.
|
||||||
someSnapshotID = "host_2026-01-01T00:00:00Z"
|
someSnapshotID = "host_2026-01-01T00:00:00Z"
|
||||||
)
|
)
|
||||||
|
|
||||||
// placeholderJSONDocument stands in for whatever document a --json
|
|
||||||
// command writes to stdout. `snapshot list --json` with no snapshots
|
|
||||||
// prints exactly this; the other --json commands print an object rather
|
|
||||||
// than an array, but this test is not about their shape. It is about
|
|
||||||
// what is on stdout *before* them, which is the same for all of them
|
|
||||||
// because Entry prints the banner before cobra has parsed anything and
|
|
||||||
// therefore before it can know which command is running.
|
|
||||||
const placeholderJSONDocument = "[]\n"
|
|
||||||
|
|
||||||
// jsonArgumentVectors are the argument vectors of every --json
|
// jsonArgumentVectors are the argument vectors of every --json
|
||||||
// invocation the CLI accepts, with the program name stripped exactly as
|
// invocation the CLI accepts, with the program name stripped exactly as
|
||||||
// Entry strips it. Each one must leave stdout untouched by the banner.
|
// Entry strips it. Each one must suppress the banner.
|
||||||
//
|
//
|
||||||
//nolint:gochecknoglobals // read-only test fixture shared by two tests
|
//nolint:gochecknoglobals // read-only test fixture shared by two tests
|
||||||
var jsonArgumentVectors = map[string][]string{
|
var jsonArgumentVectors = map[string][]string{
|
||||||
@@ -74,39 +66,23 @@ var jsonArgumentVectors = map[string][]string{
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestJSONInvocationStdoutIsExactlyOneDocument is the CLI-layer
|
// TestJSONInvocationSuppressesBanner checks that every --json
|
||||||
// regression guard for issue #106: `vaultik snapshot list --json | jq`
|
// invocation suppresses the startup banner, as the README says --json
|
||||||
// must work with no other flags.
|
// does along with --quiet and --cron. The scan is over the raw argument
|
||||||
//
|
// vector, so each position and spelling of --json is listed.
|
||||||
// internal/vaultik's TestListSnapshots_JSONStdoutIsOnlyTheDocument
|
func TestJSONInvocationSuppressesBanner(t *testing.T) {
|
||||||
// guards the same contract one layer down, but it calls the library
|
|
||||||
// function directly and so cannot see Entry, which is where the
|
|
||||||
// contamination was: the startup banner is written to stdout before
|
|
||||||
// cobra parses anything, and the suppression scan did not know about
|
|
||||||
// --json. The two banner lines and the blank line landed ahead of the
|
|
||||||
// document and `jq` refused the result.
|
|
||||||
//
|
|
||||||
// The document is a constant here because this test is about the
|
|
||||||
// argument vectors, one per --json command; the one that runs a real
|
|
||||||
// command end to end is TestEntryJSONStdoutIsExactlyOneDocument below.
|
|
||||||
func TestJSONInvocationStdoutIsExactlyOneDocument(t *testing.T) {
|
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
for name, argv := range jsonArgumentVectors {
|
for name, argv := range jsonArgumentVectors {
|
||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
var stdout bytes.Buffer
|
var banner bytes.Buffer
|
||||||
|
|
||||||
emitStartupBanner(argv, &stdout)
|
emitStartupBanner(argv, &banner)
|
||||||
|
|
||||||
require.Empty(t, stdout.String(),
|
assert.Empty(t, banner.String(),
|
||||||
"nothing may reach stdout ahead of a --json document")
|
"--json suppresses the banner")
|
||||||
|
|
||||||
_, err := stdout.WriteString(placeholderJSONDocument)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
requireExactlyOneJSONDocument(t, stdout.String())
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -127,16 +103,45 @@ func TestBannerStillPrintedWithoutSuppressingFlag(t *testing.T) {
|
|||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
var stdout bytes.Buffer
|
var banner bytes.Buffer
|
||||||
|
|
||||||
emitStartupBanner(argv, &stdout)
|
emitStartupBanner(argv, &banner)
|
||||||
|
|
||||||
assert.Contains(t, stdout.String(), "starting up at",
|
assert.Contains(t, banner.String(), "starting up at",
|
||||||
"the banner belongs on invocations that did not opt out")
|
"the banner belongs on invocations that did not opt out")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestBannerLabelsCommitDate checks that the banner prints the commit
|
||||||
|
// and the commit date, each after its own label. Commit and CommitDate
|
||||||
|
// get different values, so printing the wrong one fails.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // sets globals.Commit and globals.CommitDate
|
||||||
|
func TestBannerLabelsCommitDate(t *testing.T) {
|
||||||
|
const (
|
||||||
|
commit = "abc1234"
|
||||||
|
commitDate = "2026-11-09"
|
||||||
|
)
|
||||||
|
|
||||||
|
previousCommit, previousCommitDate := globals.Commit, globals.CommitDate
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
globals.Commit = previousCommit
|
||||||
|
globals.CommitDate = previousCommitDate
|
||||||
|
})
|
||||||
|
|
||||||
|
globals.Commit = commit
|
||||||
|
globals.CommitDate = commitDate
|
||||||
|
|
||||||
|
var banner bytes.Buffer
|
||||||
|
|
||||||
|
emitStartupBanner(nil, &banner)
|
||||||
|
|
||||||
|
assert.Contains(t, banner.String(),
|
||||||
|
"(commit "+commit+", commit date "+commitDate+")")
|
||||||
|
}
|
||||||
|
|
||||||
// TestBannerSuppressedInArgs covers the suppression scan directly,
|
// TestBannerSuppressedInArgs covers the suppression scan directly,
|
||||||
// including the flags that suppressed the banner before --json joined
|
// including the flags that suppressed the banner before --json joined
|
||||||
// them, so that adding --json cannot regress them.
|
// them, so that adding --json cannot regress them.
|
||||||
@@ -247,9 +252,7 @@ func TestEntryJSONStdoutIsExactlyOneDocument(t *testing.T) {
|
|||||||
// captureProcessStdout redirects the process's own stdout to a pipe for
|
// captureProcessStdout redirects the process's own stdout to a pipe for
|
||||||
// the duration of fn and returns what was written to it. The redirection
|
// the duration of fn and returns what was written to it. The redirection
|
||||||
// has to be at the file-descriptor level rather than through an injected
|
// has to be at the file-descriptor level rather than through an injected
|
||||||
// writer, because the banner and the JSON encoder reach os.Stdout
|
// writer, because the commands Entry runs reach os.Stdout directly.
|
||||||
// independently and the point of the test is that both land in the same
|
|
||||||
// place.
|
|
||||||
//
|
//
|
||||||
// Not parallel-safe: os.Stdout is process-global.
|
// Not parallel-safe: os.Stdout is process-global.
|
||||||
func captureProcessStdout(t *testing.T, fn func()) string {
|
func captureProcessStdout(t *testing.T, fn func()) string {
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
package cli //nolint:testpackage // shares the fixtures and capture helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"filippo.io/age"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// errorLinePrefix starts the final line that reports a failed command.
|
||||||
|
errorLinePrefix = "ERROR: "
|
||||||
|
|
||||||
|
flagVerbose = "--verbose"
|
||||||
|
cmdRestore = "restore"
|
||||||
|
|
||||||
|
// blobsDir is the directory of a destination store that holds the
|
||||||
|
// blobs.
|
||||||
|
blobsDir = "blobs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntryFailureIsPrintedOnce runs commands that fail after startup
|
||||||
|
// against a destination they cannot use. `info` is not among them: it
|
||||||
|
// cannot fail after startup.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntryFailureIsPrintedOnce(t *testing.T) {
|
||||||
|
for _, command := range [][]string{
|
||||||
|
{cmdSnapshot, cmdCreate},
|
||||||
|
{cmdSnapshot, cmdRemove, someSnapshotID},
|
||||||
|
{cmdSnapshot, cmdVerify, someSnapshotID},
|
||||||
|
{cmdRemote, cmdInfo},
|
||||||
|
{cmdPrune, flagJSON},
|
||||||
|
} {
|
||||||
|
for _, verbose := range []bool{false, true} {
|
||||||
|
name := fmt.Sprintf("%s verbose=%t", strings.Join(command, " "), verbose)
|
||||||
|
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
requireErrorPrintedOnce(t, verbose, append([]string{flagConfig,
|
||||||
|
writeUnusableDestinationConfig(t)}, command...)...)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntryBlobUploadFailureIsPrintedOnce backs up to a destination
|
||||||
|
// whose blobs directory is a file, so the blob upload fails.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntryBlobUploadFailureIsPrintedOnce(t *testing.T) {
|
||||||
|
for _, verbose := range []bool{false, true} {
|
||||||
|
t.Run(fmt.Sprintf("verbose=%t", verbose), func(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(storeDir, blobsDir), nil, 0o600))
|
||||||
|
|
||||||
|
requireErrorPrintedOnce(t, verbose,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntryBlobDownloadFailureIsPrintedOnce backs up, deletes the blobs
|
||||||
|
// from the destination, and restores, so the blob download fails.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntryBlobDownloadFailureIsPrintedOnce(t *testing.T) {
|
||||||
|
for _, verbose := range []bool{false, true} {
|
||||||
|
t.Run(fmt.Sprintf("verbose=%t", verbose), func(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfigWithPrivateKey(t)
|
||||||
|
|
||||||
|
code, _, _ := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate)
|
||||||
|
require.Equal(t, 0, code)
|
||||||
|
|
||||||
|
require.NoError(t, os.RemoveAll(filepath.Join(storeDir, blobsDir)))
|
||||||
|
|
||||||
|
requireErrorPrintedOnce(t, verbose, flagConfig, configPath,
|
||||||
|
cmdSnapshot, cmdRestore, onlySnapshotID(t, configPath), t.TempDir())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// requireErrorPrintedOnce runs Entry with args, adding --verbose when
|
||||||
|
// verbose is set. The command must fail, and stderr must carry its error
|
||||||
|
// once, as the final ERROR: line. A log record carrying the same error
|
||||||
|
// appears only under --verbose.
|
||||||
|
func requireErrorPrintedOnce(t *testing.T, verbose bool, args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
if verbose {
|
||||||
|
args = append(args, flagVerbose)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t, args...)
|
||||||
|
require.Equal(t, 1, code)
|
||||||
|
|
||||||
|
errorLine, records := failureOutput(t, stderr)
|
||||||
|
|
||||||
|
if !verbose {
|
||||||
|
assert.Zero(t, records,
|
||||||
|
"without --verbose no log record repeats the error:\n%s", stderr)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.NotZero(t, records,
|
||||||
|
"--verbose must keep the log record of %q", errorLine)
|
||||||
|
}
|
||||||
|
|
||||||
|
// failureOutput requires stderr to hold exactly one ERROR: line and
|
||||||
|
// returns it, with the number of log records whose error attribute is
|
||||||
|
// the error that line reports. stderr is a pipe here, so every log
|
||||||
|
// record is a JSON object on its own line.
|
||||||
|
func failureOutput(t *testing.T, stderr string) (string, int) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
var (
|
||||||
|
errorLines []string
|
||||||
|
records []map[string]any
|
||||||
|
)
|
||||||
|
|
||||||
|
for line := range strings.Lines(stderr) {
|
||||||
|
var record map[string]any
|
||||||
|
if json.Unmarshal([]byte(line), &record) == nil {
|
||||||
|
records = append(records, record)
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(line, errorLinePrefix) {
|
||||||
|
errorLines = append(errorLines, strings.TrimSpace(line))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
require.Len(t, errorLines, 1,
|
||||||
|
"the error must be printed once as an ERROR: line:\n%s", stderr)
|
||||||
|
|
||||||
|
// An error can run over several lines; the ERROR: line holds the
|
||||||
|
// first of them.
|
||||||
|
repeats := 0
|
||||||
|
|
||||||
|
for _, record := range records {
|
||||||
|
failure, ok := record["error"].(string)
|
||||||
|
firstLine, _, _ := strings.Cut(failure, "\n")
|
||||||
|
|
||||||
|
if ok && strings.Contains(errorLines[0], firstLine) {
|
||||||
|
repeats++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return errorLines[0], repeats
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeBackupConfigWithPrivateKey builds what writeBackupConfig builds,
|
||||||
|
// with a generated key pair in place of its recipient. The config also
|
||||||
|
// holds the private key, so that restore can decrypt the backup. Returns
|
||||||
|
// the config path and the store directory.
|
||||||
|
func writeBackupConfigWithPrivateKey(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
identity, err := age.GenerateX25519Identity()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
out := ui.NewWithColor(io.Discard, false)
|
||||||
|
|
||||||
|
require.NoError(t, writeConfigSet(out, configPath,
|
||||||
|
"age_recipients.0", identity.Recipient().String()))
|
||||||
|
require.NoError(t, writeConfigSet(out, configPath,
|
||||||
|
"age_secret_key", identity.String()))
|
||||||
|
|
||||||
|
return configPath, storeDir
|
||||||
|
}
|
||||||
|
|
||||||
|
// onlySnapshotID returns the ID of the one snapshot in the local index
|
||||||
|
// that writeBackupConfig puts beside the config file.
|
||||||
|
func onlySnapshotID(t *testing.T, configPath string) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
db, err := database.New(ctx,
|
||||||
|
filepath.Join(filepath.Dir(configPath), "index.sqlite"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
defer func() { require.NoError(t, db.Close()) }()
|
||||||
|
|
||||||
|
backedUp, err := database.NewRepositories(db).Snapshots.GetOnlySnapshot(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
return backedUp.ID.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the argument constants
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/adrg/xdg"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// stalledStoreConfig is hermeticConfig with an s3:// destination store
|
||||||
|
// in place of the file:// one. The server behind it accepts any
|
||||||
|
// credentials.
|
||||||
|
const stalledStoreConfig = `age_recipients:
|
||||||
|
- age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj
|
||||||
|
snapshots:
|
||||||
|
test:
|
||||||
|
paths:
|
||||||
|
- %s
|
||||||
|
storage_url: s3://bucket?endpoint=%s&ssl=false
|
||||||
|
s3:
|
||||||
|
access_key_id: key
|
||||||
|
secret_access_key: secret
|
||||||
|
index_path: %s
|
||||||
|
hostname: test-host
|
||||||
|
`
|
||||||
|
|
||||||
|
// interruptRepeat is how often interruptOnFirstRequest sends SIGINT.
|
||||||
|
const interruptRepeat = 50 * time.Millisecond
|
||||||
|
|
||||||
|
// TestEntryInterruptedRun sends SIGINT to the test process while a
|
||||||
|
// command waits on the destination store, and checks that Entry returns
|
||||||
|
// 130 and prints one line on stderr saying the run was interrupted. The
|
||||||
|
// store is a local HTTP server that holds every request open, so the
|
||||||
|
// command is always mid-operation when the signal arrives. The two
|
||||||
|
// cases cover --cron and --json, which silence other output.
|
||||||
|
//
|
||||||
|
// Not parallel: it signals the process and replaces os.Args, os.Stdout,
|
||||||
|
// os.Stderr and the xdg globals.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // signals the process and replaces process globals
|
||||||
|
func TestEntryInterruptedRun(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "snapshot create --cron",
|
||||||
|
args: []string{cmdSnapshot, cmdCreate, "--cron"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "snapshot verify --json",
|
||||||
|
args: []string{cmdSnapshot, cmdVerify, someSnapshotID, flagJSON},
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
endpoint, requestArrived := startStalledStore(t)
|
||||||
|
configPath := writeStalledStoreConfig(t, endpoint)
|
||||||
|
interruptOnFirstRequest(t, requestArrived)
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t,
|
||||||
|
append([]string{flagConfig, configPath}, testCase.args...)...)
|
||||||
|
|
||||||
|
assert.Equal(t, 130, code)
|
||||||
|
assert.Equal(t, 1,
|
||||||
|
strings.Count(stderr, errInterrupted.Error()), stderr)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// interruptOnFirstRequest sends SIGINT to the test process every
|
||||||
|
// interruptRepeat, from the first request to the destination store until
|
||||||
|
// the test ends. One signal is not enough: the command can reach the
|
||||||
|
// store before fx has started catching signals. The test catches SIGINT
|
||||||
|
// too, so that a signal fx is not catching does not kill the test
|
||||||
|
// binary.
|
||||||
|
func interruptOnFirstRequest(t *testing.T, requestArrived <-chan struct{}) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
self, err := os.FindProcess(os.Getpid())
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
caught := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(caught, os.Interrupt)
|
||||||
|
|
||||||
|
testEnded := make(chan struct{})
|
||||||
|
senderDone := make(chan struct{})
|
||||||
|
|
||||||
|
// Stop catching SIGINT only after the sender has returned. The sender
|
||||||
|
// waits for each SIGINT it sends to arrive on caught; one still on
|
||||||
|
// its way after signal.Stop would kill the test binary.
|
||||||
|
t.Cleanup(func() {
|
||||||
|
close(testEnded)
|
||||||
|
<-senderDone
|
||||||
|
signal.Stop(caught)
|
||||||
|
})
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer close(senderDone)
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-requestArrived:
|
||||||
|
case <-testEnded:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ticker := time.NewTicker(interruptRepeat)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Empty caught, so that the receive below waits for this
|
||||||
|
// SIGINT rather than an earlier one.
|
||||||
|
select {
|
||||||
|
case <-caught:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
sendErr := self.Signal(os.Interrupt)
|
||||||
|
if sendErr != nil {
|
||||||
|
t.Errorf("sending SIGINT: %v", sendErr)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
<-caught
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-testEnded:
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// startStalledStore starts an HTTP server that never answers: each
|
||||||
|
// request is held until the client gives up on it or the test ends.
|
||||||
|
// It returns the server's host:port and a channel that receives a value
|
||||||
|
// when the first request arrives.
|
||||||
|
func startStalledStore(t *testing.T) (string, <-chan struct{}) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
requestArrived := make(chan struct{}, 1)
|
||||||
|
release := make(chan struct{})
|
||||||
|
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(
|
||||||
|
func(_ http.ResponseWriter, r *http.Request) {
|
||||||
|
select {
|
||||||
|
case requestArrived <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-r.Context().Done():
|
||||||
|
case <-release:
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Cleanups run last-registered first, so release lets any held
|
||||||
|
// request return before Close waits for it.
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
t.Cleanup(func() { close(release) })
|
||||||
|
|
||||||
|
return server.Listener.Addr().String(), requestArrived
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeStalledStoreConfig writes a config whose destination store is the
|
||||||
|
// server at endpoint and whose snapshot source holds one small file, so
|
||||||
|
// that `snapshot create` has a blob to upload. Returns the config path.
|
||||||
|
func writeStalledStoreConfig(t *testing.T, endpoint string) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
configPath := filepath.Join(dir, "config.yml")
|
||||||
|
sourceDir := filepath.Join(dir, "source")
|
||||||
|
|
||||||
|
require.NoError(t, os.Mkdir(sourceDir, 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(filepath.Join(sourceDir, "file.txt"),
|
||||||
|
[]byte("contents"), 0o600))
|
||||||
|
|
||||||
|
contents := fmt.Sprintf(stalledStoreConfig,
|
||||||
|
sourceDir, endpoint, filepath.Join(dir, "index.sqlite"))
|
||||||
|
|
||||||
|
require.NoError(t,
|
||||||
|
os.WriteFile(configPath, []byte(contents), configFileMode))
|
||||||
|
|
||||||
|
// The PID lock lives under xdg.DataHome, which xdg resolves at
|
||||||
|
// package init; point it at the temp dir so the test neither
|
||||||
|
// touches nor collides with the real one.
|
||||||
|
t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data"))
|
||||||
|
xdg.Reload()
|
||||||
|
t.Cleanup(xdg.Reload)
|
||||||
|
|
||||||
|
return configPath
|
||||||
|
}
|
||||||
@@ -101,7 +101,8 @@ func TestEntryPruneJSONStdoutIsExactlyOneDocument(t *testing.T) {
|
|||||||
// writeHermeticPruneConfig builds a config over a temp directory with an
|
// writeHermeticPruneConfig builds a config over a temp directory with an
|
||||||
// empty destination directory and, if seedStale is set, creates the
|
// empty destination directory and, if seedStale is set, creates the
|
||||||
// index database up front with one snapshot record that has no
|
// index database up front with one snapshot record that has no
|
||||||
// counterpart on the destination store. Returns the config path.
|
// counterpart on the destination store, and gives the destination the
|
||||||
|
// marker a backup writes. Returns the config path.
|
||||||
func writeHermeticPruneConfig(t *testing.T, seedStale bool) string {
|
func writeHermeticPruneConfig(t *testing.T, seedStale bool) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
@@ -131,6 +132,11 @@ func writeHermeticPruneConfig(t *testing.T, seedStale bool) string {
|
|||||||
|
|
||||||
if seedStale {
|
if seedStale {
|
||||||
seedStaleSnapshotRecord(t, indexPath)
|
seedStaleSnapshotRecord(t, indexPath)
|
||||||
|
|
||||||
|
// While the local index holds a snapshot, prune fails on a
|
||||||
|
// destination that answers that it has no marker.
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(storeDir, "vaultik-destination.txt"), nil, 0o600))
|
||||||
}
|
}
|
||||||
|
|
||||||
return configPath
|
return configPath
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// flagCron is used to build the argument vectors below.
|
||||||
|
const flagCron = "--cron"
|
||||||
|
|
||||||
|
// plantUnreferencedBlob writes a blob that no snapshot references to the
|
||||||
|
// destination store at storeDir, dated long before any prune grace period,
|
||||||
|
// 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))
|
||||||
|
|
||||||
|
longAgo := time.Unix(0, 0)
|
||||||
|
require.NoError(t, os.Chtimes(path, longAgo, longAgo))
|
||||||
|
|
||||||
|
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,69 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/adrg/xdg"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreateSkipsIndexAndLockFiles backs up a directory
|
||||||
|
// that holds vaultik's index and PID file beside one other file, with no
|
||||||
|
// exclude pattern set. The summary counts only the other file. See
|
||||||
|
// https://git.eeqj.de/sneak/vaultik/issues/421.
|
||||||
|
//
|
||||||
|
// Not parallel: it replaces os.Args, os.Stdout, os.Stderr and the xdg
|
||||||
|
// globals.
|
||||||
|
func TestEntrySnapshotCreateSkipsIndexAndLockFiles(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
// linked sets index_path to a symlink outside the backed-up
|
||||||
|
// directory that points to the index inside it.
|
||||||
|
linked bool
|
||||||
|
}{
|
||||||
|
{name: "index in the backed-up directory"},
|
||||||
|
{name: "index_path links into the backed-up directory", linked: true},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
configPath := filepath.Join(dir, "config.yml")
|
||||||
|
sourceDir := filepath.Join(dir, "source")
|
||||||
|
storeDir := filepath.Join(dir, "store")
|
||||||
|
|
||||||
|
indexPath := filepath.Join(sourceDir, "index.sqlite")
|
||||||
|
|
||||||
|
if testCase.linked {
|
||||||
|
link := filepath.Join(dir, "index.sqlite")
|
||||||
|
require.NoError(t, os.Symlink(indexPath, link))
|
||||||
|
|
||||||
|
indexPath = link
|
||||||
|
}
|
||||||
|
|
||||||
|
contents := fmt.Sprintf(hermeticConfig,
|
||||||
|
sourceDir, storeDir, indexPath)
|
||||||
|
require.NoError(t,
|
||||||
|
os.WriteFile(configPath, []byte(contents), configFileMode))
|
||||||
|
require.NoError(t, os.Mkdir(storeDir, 0o750))
|
||||||
|
require.NoError(t, os.Mkdir(sourceDir, 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(sourceDir, "file.txt"), []byte("hello"), 0o600))
|
||||||
|
|
||||||
|
// The PID file goes in a directory under XDG_DATA_HOME, which
|
||||||
|
// xdg reads at package init.
|
||||||
|
t.Setenv("XDG_DATA_HOME", filepath.Join(sourceDir, "data"))
|
||||||
|
xdg.Reload()
|
||||||
|
t.Cleanup(xdg.Reload)
|
||||||
|
|
||||||
|
code, stdout, _ := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate)
|
||||||
|
|
||||||
|
require.Equal(t, 0, code)
|
||||||
|
assert.Contains(t, stdout,
|
||||||
|
"Files: 1 examined, 1 backed up, 0 unchanged.")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Flags of `snapshot create` used to build argument vectors below.
|
||||||
|
const (
|
||||||
|
flagPrune = "--prune"
|
||||||
|
flagKeepNewerThan = "--keep-newer-than"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup checks that a
|
||||||
|
// --keep-newer-than the post-backup prune could not use stops `snapshot
|
||||||
|
// create` before the backup: the command fails and the destination
|
||||||
|
// store stays empty. It used to be read only by the prune, after the
|
||||||
|
// snapshot was uploaded, and without --prune it was ignored.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "decimal in a day count",
|
||||||
|
args: []string{flagPrune, flagKeepNewerThan, "1.5d"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown unit",
|
||||||
|
args: []string{flagPrune, flagKeepNewerThan, "4x"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "without --prune",
|
||||||
|
args: []string{flagKeepNewerThan, "4w"},
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
code, _, _ := runEntry(t, append(
|
||||||
|
[]string{flagConfig, configPath, cmdSnapshot, cmdCreate},
|
||||||
|
testCase.args...)...)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
|
||||||
|
stored, err := os.ReadDir(storeDir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, stored, "nothing may be uploaded")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreateReportsPostBackupPruneFailure makes the
|
||||||
|
// post-backup prune fail after a good backup, by planting a manifest
|
||||||
|
// that cannot be decoded, and checks that the failure is reported once,
|
||||||
|
// as the prune's and not as a failed snapshot creation.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
// A remote key is 64 lowercase hex characters. The prune reads every
|
||||||
|
// manifest on the store and fails on one it cannot decode.
|
||||||
|
plantedDir := filepath.Join(storeDir, "metadata", strings.Repeat("a", 64))
|
||||||
|
require.NoError(t, os.MkdirAll(plantedDir, 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(plantedDir, "manifest.json.zst"),
|
||||||
|
[]byte("not a valid manifest"), 0o600))
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Contains(t, stderr, "Backup completed, but post-backup prune failed")
|
||||||
|
assert.NotContains(t, stderr, "Snapshot creation failed")
|
||||||
|
|
||||||
|
_, repeats := failureOutput(t, stderr)
|
||||||
|
assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr)
|
||||||
|
|
||||||
|
snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Len(t, snapshots, 2,
|
||||||
|
"the new snapshot is on the store beside the planted one")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty backs up,
|
||||||
|
// empties the source directory, as a volume that is not mounted leaves
|
||||||
|
// its mount point, and runs `snapshot create --prune`. The command exits
|
||||||
|
// non-zero and reports the backup as completed, not as a failed snapshot
|
||||||
|
// creation. The error is printed once. See
|
||||||
|
// https://git.eeqj.de/sneak/vaultik/issues/388.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty(t *testing.T) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
code, _, _ := runEntry(t, flagConfig, configPath, cmdSnapshot, cmdCreate)
|
||||||
|
require.Equal(t, 0, code)
|
||||||
|
|
||||||
|
// writeBackupConfig puts the source directory beside the config file.
|
||||||
|
require.NoError(t, os.Remove(
|
||||||
|
filepath.Join(filepath.Dir(configPath), "source", "file.txt")))
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Contains(t, stderr,
|
||||||
|
"Backup completed, but 1 source path(s) were empty")
|
||||||
|
assert.NotContains(t, stderr, "Snapshot creation failed")
|
||||||
|
|
||||||
|
_, repeats := failureOutput(t, stderr)
|
||||||
|
assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr)
|
||||||
|
|
||||||
|
snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Len(t, snapshots, 2, "the older snapshot is kept")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing backs
|
||||||
|
// up, records in the local index that this backup found the source
|
||||||
|
// directory as a mount point, and runs `snapshot create --prune`, which
|
||||||
|
// does not find it as one. The command exits non-zero, reports the
|
||||||
|
// backup as completed, not as a failed snapshot creation, and keeps the
|
||||||
|
// older snapshot. The error is printed once. See
|
||||||
|
// https://git.eeqj.de/sneak/vaultik/issues/395.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing(
|
||||||
|
t *testing.T,
|
||||||
|
) {
|
||||||
|
configPath, storeDir := writeBackupConfig(t)
|
||||||
|
|
||||||
|
code, _, _ := runEntry(t, flagConfig, configPath, cmdSnapshot, cmdCreate)
|
||||||
|
require.Equal(t, 0, code)
|
||||||
|
|
||||||
|
// writeBackupConfig puts the source directory and the local index
|
||||||
|
// beside the config file.
|
||||||
|
dir := filepath.Dir(configPath)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
db, err := database.New(ctx, filepath.Join(dir, "index.sqlite"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
backedUp, err := repos.Snapshots.GetOnlySnapshot(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, repos.Snapshots.AddMountPoint(ctx, nil,
|
||||||
|
backedUp.ID.String(), filepath.Join(dir, "source")))
|
||||||
|
require.NoError(t, db.Close())
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Contains(t, stderr, "Backup completed, but 1 mount point(s) "+
|
||||||
|
"an earlier snapshot recorded were not found")
|
||||||
|
assert.NotContains(t, stderr, "Snapshot creation failed")
|
||||||
|
|
||||||
|
_, repeats := failureOutput(t, stderr)
|
||||||
|
assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr)
|
||||||
|
|
||||||
|
snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata"))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Len(t, snapshots, 2, "the older snapshot is kept")
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeBackupConfig builds a hermetic config with one small file in its
|
||||||
|
// source directory and an empty destination store directory. Returns the
|
||||||
|
// config path and the store directory.
|
||||||
|
func writeBackupConfig(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
configPath := writeHermeticPruneConfig(t, false)
|
||||||
|
|
||||||
|
// writeHermeticPruneConfig puts the source and store directories
|
||||||
|
// beside the config file.
|
||||||
|
dir := filepath.Dir(configPath)
|
||||||
|
sourceDir := filepath.Join(dir, "source")
|
||||||
|
|
||||||
|
require.NoError(t, os.Mkdir(sourceDir, 0o750))
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(sourceDir, "file.txt"), []byte("hello"), 0o600))
|
||||||
|
|
||||||
|
return configPath, filepath.Join(dir, "store")
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntrySnapshotCreateSkipErrorsExitsNonZeroWhenItSkips backs up,
|
||||||
|
// under --skip-errors, a source directory that does not exist, which the
|
||||||
|
// walk skips. The command exits non-zero and reports the backup as
|
||||||
|
// completed, not as a failed snapshot creation. See
|
||||||
|
// https://git.eeqj.de/sneak/vaultik/issues/310.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotCreateSkipErrorsExitsNonZeroWhenItSkips(t *testing.T) {
|
||||||
|
// writeBackupConfig would create the source directory.
|
||||||
|
configPath := writeHermeticPruneConfig(t, false)
|
||||||
|
|
||||||
|
code, stdout, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, "--skip-errors", cmdSnapshot, cmdCreate)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Contains(t, stdout,
|
||||||
|
"Files: 1 examined, 0 backed up, 0 unchanged, 1 failed.")
|
||||||
|
assert.NotContains(t, stdout, "Finished successfully.")
|
||||||
|
assert.Contains(t, stderr,
|
||||||
|
"Backup completed, but 1 file(s) could not be read")
|
||||||
|
assert.NotContains(t, stderr, "Snapshot creation failed")
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the backup config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
|
)
|
||||||
|
|
||||||
|
// cmdFiles is the word of `snapshot files`, used to build argument
|
||||||
|
// vectors below.
|
||||||
|
const cmdFiles = "files"
|
||||||
|
|
||||||
|
// TestEntrySnapshotFilesListsOnlyThePath backs up two files and runs
|
||||||
|
// `snapshot files` with the snapshot ID and the path of one of them,
|
||||||
|
// which must be the only file listed.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotFilesListsOnlyThePath(t *testing.T) {
|
||||||
|
configPath, _ := writeBackupConfigWithPrivateKey(t)
|
||||||
|
|
||||||
|
// writeBackupConfig puts file.txt in the source directory beside the
|
||||||
|
// config file.
|
||||||
|
sourceDir := filepath.Join(filepath.Dir(configPath), "source")
|
||||||
|
listed := filepath.Join(sourceDir, "file.txt")
|
||||||
|
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(sourceDir, "other.txt"), []byte("other"), 0o600))
|
||||||
|
|
||||||
|
code, _, stderr := runEntry(t,
|
||||||
|
flagConfig, configPath, cmdSnapshot, cmdCreate)
|
||||||
|
require.Equal(t, 0, code, stderr)
|
||||||
|
|
||||||
|
code, stdout, stderr := runEntry(t, flagConfig, configPath, cmdSnapshot,
|
||||||
|
cmdFiles, onlySnapshotID(t, configPath), listed, flagJSON)
|
||||||
|
require.Equal(t, 0, code, stderr)
|
||||||
|
|
||||||
|
var entries []vaultik.ListedFile
|
||||||
|
|
||||||
|
require.NoError(t, json.Unmarshal([]byte(stdout), &entries))
|
||||||
|
require.Len(t, entries, 1, "only the path given may be listed")
|
||||||
|
assert.Equal(t, listed, entries[0].Path)
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the hermetic config helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Words and flags of `snapshot purge` used to build argument vectors
|
||||||
|
// below.
|
||||||
|
const (
|
||||||
|
cmdPurge = "purge"
|
||||||
|
flagOlderThan = "--older-than"
|
||||||
|
flagForce = "--force"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails makes
|
||||||
|
// the local index refuse to delete an old snapshot 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
|
||||||
|
// and exit 0.
|
||||||
|
//
|
||||||
|
// `snapshot create --prune` runs the same purge, but cannot be driven
|
||||||
|
// this way: the refusal also breaks the backup's metadata export, which
|
||||||
|
// deletes the other snapshots from its copy of the local index.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T) {
|
||||||
|
configPath := writeHermeticPruneConfig(t, false)
|
||||||
|
dir := filepath.Dir(configPath)
|
||||||
|
indexPath := filepath.Join(dir, "index.sqlite")
|
||||||
|
|
||||||
|
// seedStaleSnapshotRecord writes an old snapshot to the local index
|
||||||
|
// only; the manifest planted here puts it on the destination store
|
||||||
|
// too, so the purge selects it rather than dropping it as stale.
|
||||||
|
seedStaleSnapshotRecord(t, indexPath)
|
||||||
|
|
||||||
|
// While the local index holds a snapshot, purge fails on a
|
||||||
|
// destination that answers that it has no marker.
|
||||||
|
require.NoError(t, os.WriteFile(
|
||||||
|
filepath.Join(dir, "store", "vaultik-destination.txt"), nil, 0o600))
|
||||||
|
|
||||||
|
manifestDir := filepath.Join(dir, "store", "metadata",
|
||||||
|
snapshot.RemoteSnapshotKey(stalePruneSnapshotID))
|
||||||
|
require.NoError(t, os.MkdirAll(manifestDir, 0o750))
|
||||||
|
|
||||||
|
manifestPath := filepath.Join(manifestDir, "manifest.json.zst")
|
||||||
|
require.NoError(t, os.WriteFile(manifestPath, []byte("stub"), 0o600))
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
db, err := database.New(ctx, indexPath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
_, 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, flagOlderThan, "30d", flagForce)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Contains(t, stderr, "simulated index error",
|
||||||
|
"the purge must fail at the local-index delete")
|
||||||
|
assert.FileExists(t, manifestPath,
|
||||||
|
"the snapshot is still in the local index, so its metadata must stay")
|
||||||
|
}
|
||||||
@@ -15,8 +15,8 @@ import (
|
|||||||
// run, so a failing command must come back with a non-zero code rather
|
// run, so a failing command must come back with a non-zero code rather
|
||||||
// than ending the process here.
|
// than ending the process here.
|
||||||
//
|
//
|
||||||
// Stdout is captured only to keep the banner and command output off the
|
// Stdout and stderr are captured only to keep the banner and command
|
||||||
// test log; the assertion is on the returned code.
|
// output off the test log; the assertion is on the returned code.
|
||||||
//
|
//
|
||||||
//nolint:paralleltest // replaces os.Args and rootFlags
|
//nolint:paralleltest // replaces os.Args and rootFlags
|
||||||
func TestEntryReturnsStatusCode(t *testing.T) {
|
func TestEntryReturnsStatusCode(t *testing.T) {
|
||||||
@@ -50,7 +50,7 @@ func TestEntryReturnsStatusCode(t *testing.T) {
|
|||||||
|
|
||||||
var code int
|
var code int
|
||||||
|
|
||||||
_ = captureProcessStdout(t, func() { code = Entry() })
|
_, _ = captureProcessStdoutAndStderr(t, func() { code = Entry() })
|
||||||
|
|
||||||
assert.Equal(t, testCase.want, code)
|
assert.Equal(t, testCase.want, code)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
package cli //nolint:testpackage // shares hermeticConfig and the capture helpers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/adrg/xdg"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntryCompletionStdoutIsTheScript runs `vaultik completion bash`,
|
||||||
|
// whose stdout the README tells the user to source. The script has to
|
||||||
|
// start on the first line.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr
|
||||||
|
func TestEntryCompletionStdoutIsTheScript(t *testing.T) {
|
||||||
|
code, stdout, _ := runEntry(t, "completion", "bash")
|
||||||
|
|
||||||
|
require.Equal(t, 0, code)
|
||||||
|
|
||||||
|
firstLine, _, _ := strings.Cut(stdout, "\n")
|
||||||
|
assert.True(t, strings.HasPrefix(firstLine, "# bash completion"),
|
||||||
|
"the first line of stdout must be the script's, got %q", firstLine)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntryConfigGetStdoutIsTheValue runs `vaultik config get`, whose
|
||||||
|
// stdout a script reads as the value and nothing else.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr
|
||||||
|
func TestEntryConfigGetStdoutIsTheValue(t *testing.T) {
|
||||||
|
configPath := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
require.NoError(t, os.WriteFile(configPath,
|
||||||
|
[]byte("hostname: test-host\n"), configFileMode))
|
||||||
|
|
||||||
|
code, stdout, _ := runEntry(t,
|
||||||
|
flagConfig, configPath, "config", "get", "hostname")
|
||||||
|
|
||||||
|
require.Equal(t, 0, code)
|
||||||
|
assert.Equal(t, "test-host\n", stdout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntryJSONFailureIsReportedOnStderr runs each --json command that
|
||||||
|
// writes no document when it fails, against a destination it cannot
|
||||||
|
// use. The error must reach stderr, and stdout must stay empty.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntryJSONFailureIsReportedOnStderr(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
wantOnStderr string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "remote info",
|
||||||
|
args: []string{cmdRemote, cmdInfo, flagJSON},
|
||||||
|
wantOnStderr: "Failed to get remote info",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "prune",
|
||||||
|
args: []string{cmdPrune, flagJSON},
|
||||||
|
wantOnStderr: "Prune failed",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "snapshot remove",
|
||||||
|
args: []string{cmdSnapshot, cmdRemove, someSnapshotID, flagJSON},
|
||||||
|
wantOnStderr: "Failed to remove snapshot",
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
configPath := writeUnusableDestinationConfig(t)
|
||||||
|
|
||||||
|
code, stdout, stderr := runEntry(t,
|
||||||
|
append([]string{flagConfig, configPath}, testCase.args...)...)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Empty(t, stdout,
|
||||||
|
"a failed --json command has no document to write")
|
||||||
|
assert.Contains(t, stderr, testCase.wantOnStderr,
|
||||||
|
"the failure must be reported on stderr")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEntrySnapshotRemoveJSONWarningIsOnStderr runs `snapshot remove
|
||||||
|
// --json` on a snapshot in the local index, against a destination
|
||||||
|
// directory that does not exist. The command removes the snapshot from
|
||||||
|
// the local index and still exits 0. Its stdout must hold the document
|
||||||
|
// alone, with the warning about the destination store on stderr: the
|
||||||
|
// command to run again once it is reachable, and the snapshot's ID in
|
||||||
|
// the record's snapshot_id field.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals
|
||||||
|
func TestEntrySnapshotRemoveJSONWarningIsOnStderr(t *testing.T) {
|
||||||
|
configPath, indexPath := writeMissingDestinationConfig(t)
|
||||||
|
seedStaleSnapshotRecord(t, indexPath)
|
||||||
|
|
||||||
|
code, stdout, stderr := runEntry(t, flagConfig, configPath,
|
||||||
|
cmdSnapshot, cmdRemove, stalePruneSnapshotID, flagJSON)
|
||||||
|
|
||||||
|
require.Equal(t, 0, code)
|
||||||
|
requireExactlyOneJSONDocument(t, stdout)
|
||||||
|
|
||||||
|
// stderr is a pipe here, so the logger writes one JSON record a line.
|
||||||
|
var warning map[string]any
|
||||||
|
|
||||||
|
for line := range strings.Lines(stderr) {
|
||||||
|
if strings.Contains(line,
|
||||||
|
"Could not remove snapshot metadata from remote storage") {
|
||||||
|
require.NoError(t, json.Unmarshal([]byte(line), &warning))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
require.NotNil(t, warning, "the warning must reach stderr")
|
||||||
|
assert.Contains(t, warning[slog.MessageKey],
|
||||||
|
"run 'vaultik snapshot remove' with the snapshot's ID again")
|
||||||
|
assert.Equal(t, stalePruneSnapshotID, warning["snapshot_id"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeMissingDestinationConfig builds a config whose destination
|
||||||
|
// directory does not exist. Returns the config path and the path of
|
||||||
|
// its local index, which is not created here.
|
||||||
|
func writeMissingDestinationConfig(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
configPath := filepath.Join(dir, "config.yml")
|
||||||
|
indexPath := filepath.Join(dir, "index.sqlite")
|
||||||
|
|
||||||
|
contents := fmt.Sprintf(hermeticConfig,
|
||||||
|
filepath.Join(dir, "source"),
|
||||||
|
filepath.Join(dir, "missing-store"),
|
||||||
|
indexPath)
|
||||||
|
|
||||||
|
require.NoError(t,
|
||||||
|
os.WriteFile(configPath, []byte(contents), configFileMode))
|
||||||
|
|
||||||
|
// The PID lock lives under xdg.DataHome, which xdg resolves at
|
||||||
|
// package init; point it at the temp dir so the test neither
|
||||||
|
// touches nor collides with the real one.
|
||||||
|
t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data"))
|
||||||
|
xdg.Reload()
|
||||||
|
t.Cleanup(xdg.Reload)
|
||||||
|
|
||||||
|
return configPath, indexPath
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeUnusableDestinationConfig builds a config whose destination
|
||||||
|
// directory does not exist, which fails `remote info`, and whose local
|
||||||
|
// index is bound to another destination, which fails `prune` and
|
||||||
|
// `snapshot remove` (a missing destination alone only makes `snapshot
|
||||||
|
// remove` warn). Returns the config path.
|
||||||
|
func writeUnusableDestinationConfig(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
configPath, indexPath := writeMissingDestinationConfig(t)
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
db, err := database.New(ctx, indexPath)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
defer func() { require.NoError(t, db.Close()) }()
|
||||||
|
|
||||||
|
require.NoError(t, database.NewRepositories(db).LocalMeta.Set(ctx,
|
||||||
|
database.LocalMetaKeyStorageURL, "file://"+t.TempDir()))
|
||||||
|
|
||||||
|
return configPath
|
||||||
|
}
|
||||||
|
|
||||||
|
// runEntry runs Entry with args after the program name and returns its
|
||||||
|
// exit code and what it wrote to stdout and stderr.
|
||||||
|
//
|
||||||
|
// Not parallel-safe: it replaces os.Args, os.Stdout and os.Stderr.
|
||||||
|
func runEntry(t *testing.T, args ...string) (int, string, string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
previousArgs := os.Args
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
os.Args = previousArgs
|
||||||
|
rootFlags = RootFlags{}
|
||||||
|
})
|
||||||
|
|
||||||
|
os.Args = append([]string{programName}, args...)
|
||||||
|
|
||||||
|
var code int
|
||||||
|
|
||||||
|
stdout, stderr := captureProcessStdoutAndStderr(t,
|
||||||
|
func() { code = Entry() })
|
||||||
|
|
||||||
|
return code, stdout, stderr
|
||||||
|
}
|
||||||
@@ -48,7 +48,7 @@ func TestCLIEntry(t *testing.T) {
|
|||||||
} else {
|
} else {
|
||||||
// Check snapshot subcommands
|
// Check snapshot subcommands
|
||||||
expectedSubCommands := []string{
|
expectedSubCommands := []string{
|
||||||
"create", "list", "purge", "verify", "remove", "restore",
|
"create", "list", "files", "purge", "verify", "remove", "restore",
|
||||||
}
|
}
|
||||||
for _, expected := range expectedSubCommands {
|
for _, expected := range expectedSubCommands {
|
||||||
found := false
|
found := false
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package cli //nolint:testpackage // shares runEntry and the command-word constants
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestEntryGroupRejectsUnknownSubcommand runs each group command with a
|
||||||
|
// mistyped subcommand, as a crontab line might carry one. It must fail
|
||||||
|
// with exit 1 and name the word, as `vaultik bogus` does at the top
|
||||||
|
// level, instead of printing the group's help and exiting 0 having done
|
||||||
|
// nothing. The group name alone still prints its help.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr
|
||||||
|
func TestEntryGroupRejectsUnknownSubcommand(t *testing.T) {
|
||||||
|
for _, testCase := range []struct {
|
||||||
|
group string
|
||||||
|
mistyped string
|
||||||
|
}{
|
||||||
|
{group: cmdSnapshot, mistyped: "craete"},
|
||||||
|
{group: "config", mistyped: "inti"},
|
||||||
|
{group: cmdRemote, mistyped: "ifno"},
|
||||||
|
{group: "database", mistyped: "delte"},
|
||||||
|
{group: "completion", mistyped: "nosuchshell"},
|
||||||
|
} {
|
||||||
|
t.Run(testCase.group, func(t *testing.T) {
|
||||||
|
code, stdout, stderr := runEntry(t,
|
||||||
|
testCase.group, testCase.mistyped)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, code)
|
||||||
|
assert.Empty(t, stdout)
|
||||||
|
assert.Contains(t, stderr,
|
||||||
|
`unknown command "`+testCase.mistyped+`"`)
|
||||||
|
|
||||||
|
code, stdout, _ = runEntry(t, testCase.group)
|
||||||
|
|
||||||
|
assert.Equal(t, 0, code)
|
||||||
|
assert.Contains(t, stdout,
|
||||||
|
programName+" "+testCase.group+" [command]")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,7 +39,7 @@ func NewInfoCommand() *cobra.Command {
|
|||||||
}, func(v *vaultik.Vaultik) error {
|
}, func(v *vaultik.Vaultik) error {
|
||||||
return v.ShowInfo()
|
return v.ShowInfo()
|
||||||
}, func(err error) {
|
}, func(err error) {
|
||||||
log.Error("Failed to show info", "error", err)
|
log.Info("Failed to show info", "error", err)
|
||||||
ReportErrorf("Failed to show info: %v", err)
|
ReportErrorf("Failed to show info: %v", err)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package cli //nolint:testpackage // exercises the unexported command constructor
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestJSONHelpSaysConfirmationPromptIsSkipped checks that the --json help
|
||||||
|
// of `snapshot remove` and `prune` says the flag skips the confirmation
|
||||||
|
// prompt. Both delete without asking under --json, since a prompt on
|
||||||
|
// stdout would break the JSON document.
|
||||||
|
func TestJSONHelpSaysConfirmationPromptIsSkipped(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
for _, cmd := range []*cobra.Command{
|
||||||
|
newSnapshotRemoveCommand(),
|
||||||
|
NewPruneCommand(),
|
||||||
|
} {
|
||||||
|
assert.Contains(t, cmd.Flags().Lookup("json").Usage,
|
||||||
|
"skips the confirmation prompt", cmd.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
-12
@@ -13,18 +13,30 @@ func NewPruneCommand() *cobra.Command {
|
|||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "prune",
|
Use: "prune",
|
||||||
Short: "Tidy local database and remote storage",
|
Short: "Tidy local database and remote storage",
|
||||||
Long: `Removes orphaned data from both the local index database and
|
Long: `Removes orphaned data from the local index database, and
|
||||||
unreferenced blobs from the backup destination store.
|
unreferenced blobs and directories under metadata/ with no manifest
|
||||||
|
from the backup destination store.
|
||||||
|
|
||||||
Local cleanup drops incomplete snapshots and any files, chunks, or
|
Local cleanup drops incomplete snapshots and any files, chunks, or
|
||||||
blobs no longer referenced by a completed snapshot. Remote cleanup
|
blobs no longer referenced by a completed snapshot. Remote cleanup
|
||||||
scans every snapshot manifest in the destination store, builds the
|
scans every snapshot manifest in the destination store, builds the
|
||||||
set of still-referenced blob hashes, and deletes any blob not in that
|
set of still-referenced blob hashes, and deletes any blob not in that
|
||||||
set.
|
set that is older than prune_grace_period (default 24h). A newer one
|
||||||
|
is kept: it may belong to a backup still running, on this host or
|
||||||
|
another sharing the destination store, that has not yet uploaded its
|
||||||
|
manifest. The grace period does not protect a blob such a backup
|
||||||
|
reuses from an earlier run that stopped before its manifest: that
|
||||||
|
blob keeps the time of its first upload, so it can be deleted.
|
||||||
|
Remote cleanup also deletes each directory under metadata/ with no
|
||||||
|
manifest, as a backup that stopped before its manifest leaves, once
|
||||||
|
all its objects are older than prune_grace_period and its snapshot is
|
||||||
|
not in the local index.
|
||||||
|
|
||||||
Snapshot create --prune and snapshot remove run the same cleanup
|
Snapshot create --prune runs the same cleanup automatically; this
|
||||||
automatically; this command is the manual entry point for the same
|
command is the manual entry point for the same work (e.g. after a
|
||||||
work (e.g. after a crashed backup or to reclaim storage).`,
|
crashed backup or to reclaim storage). Snapshot remove leaves blobs in
|
||||||
|
place; run this command afterwards to delete the ones no longer
|
||||||
|
referenced.`,
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
// Use unified config resolution
|
// Use unified config resolution
|
||||||
@@ -48,18 +60,15 @@ work (e.g. after a crashed backup or to reclaim storage).`,
|
|||||||
}, func(v *vaultik.Vaultik) error {
|
}, func(v *vaultik.Vaultik) error {
|
||||||
return v.Prune(opts)
|
return v.Prune(opts)
|
||||||
}, func(err error) {
|
}, func(err error) {
|
||||||
if opts.JSON {
|
log.Info("Prune operation failed", "error", err)
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Error("Prune operation failed", "error", err)
|
|
||||||
ReportErrorf("Prune failed: %v", err)
|
ReportErrorf("Prune failed: %v", err)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd.Flags().BoolVar(&opts.Force, "force", false, "Skip confirmation prompt")
|
cmd.Flags().BoolVar(&opts.Force, "force", false, "Skip confirmation prompt")
|
||||||
cmd.Flags().BoolVar(&opts.JSON, "json", false, "Output pruning stats as JSON")
|
cmd.Flags().BoolVar(&opts.JSON, "json", false,
|
||||||
|
"Output pruning stats as JSON; skips the confirmation prompt, as --force does")
|
||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
@@ -18,6 +18,12 @@ func NewRemoteCommand() *cobra.Command {
|
|||||||
Use: "remote",
|
Use: "remote",
|
||||||
Short: "Remote storage management commands",
|
Short: "Remote storage management commands",
|
||||||
Long: "Commands for inspecting and managing remote storage",
|
Long: "Commands for inspecting and managing remote storage",
|
||||||
|
// cobra checks Args only on a command that has a Run: without
|
||||||
|
// one, a mistyped subcommand printed help and exited 0.
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
Run: func(cmd *cobra.Command, _ []string) {
|
||||||
|
_ = cmd.Help()
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add subcommands
|
// Add subcommands
|
||||||
@@ -45,7 +51,7 @@ This is destructive and irreversible. Requires --force.`,
|
|||||||
return errNukeNeedsForce
|
return errNukeNeedsForce
|
||||||
}
|
}
|
||||||
|
|
||||||
return runVaultikApp(cmd, mutating, false, false, "Remote nuke failed",
|
return runVaultikApp(cmd, mutating, false, "Remote nuke failed",
|
||||||
func(v *vaultik.Vaultik) error {
|
func(v *vaultik.Vaultik) error {
|
||||||
return v.NukeRemote(true)
|
return v.NukeRemote(true)
|
||||||
})
|
})
|
||||||
@@ -92,11 +98,7 @@ func newRemoteInfoCommand() *cobra.Command {
|
|||||||
}, func(v *vaultik.Vaultik) error {
|
}, func(v *vaultik.Vaultik) error {
|
||||||
return v.RemoteInfo(jsonOutput)
|
return v.RemoteInfo(jsonOutput)
|
||||||
}, func(err error) {
|
}, func(err error) {
|
||||||
if jsonOutput {
|
log.Info("Failed to get remote info", "error", err)
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Error("Failed to get remote info", "error", err)
|
|
||||||
ReportErrorf("Failed to get remote info: %v", err)
|
ReportErrorf("Failed to get remote info: %v", err)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -74,6 +74,21 @@ on the source system.`,
|
|||||||
NewDatabaseCommand(),
|
NewDatabaseCommand(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// cobra adds the completion command only when Execute runs, and with
|
||||||
|
// no Run, so it skipped its own cobra.NoArgs and a mistyped shell name
|
||||||
|
// printed help and exited 0. Adding it here lets it have a Run. Its
|
||||||
|
// scripts go to os.Stdout as it is now: a later SetOut does not
|
||||||
|
// redirect them.
|
||||||
|
cmd.InitDefaultCompletionCmd()
|
||||||
|
|
||||||
|
for _, sub := range cmd.Commands() {
|
||||||
|
if sub.Name() == "completion" {
|
||||||
|
sub.Run = func(completion *cobra.Command, _ []string) {
|
||||||
|
_ = completion.Help()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+101
-16
@@ -9,6 +9,10 @@ import (
|
|||||||
"sneak.berlin/go/vaultik/internal/vaultik"
|
"sneak.berlin/go/vaultik/internal/vaultik"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// filesMaxArgs is the maximum positional argument count of
|
||||||
|
// `snapshot files <snapshot-id> [path]`.
|
||||||
|
const filesMaxArgs = 2
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errSnapshotIDRequired = errors.New("snapshot ID required")
|
errSnapshotIDRequired = errors.New("snapshot ID required")
|
||||||
errWrongArgCount = errors.New("wrong argument count")
|
errWrongArgCount = errors.New("wrong argument count")
|
||||||
@@ -41,11 +45,18 @@ func NewSnapshotCommand() *cobra.Command {
|
|||||||
Use: "snapshot",
|
Use: "snapshot",
|
||||||
Short: "Snapshot management commands",
|
Short: "Snapshot management commands",
|
||||||
Long: "Commands for creating, listing, and managing snapshots",
|
Long: "Commands for creating, listing, and managing snapshots",
|
||||||
|
// cobra checks Args only on a command that has a Run: without
|
||||||
|
// one, a mistyped subcommand printed help and exited 0.
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
Run: func(cmd *cobra.Command, _ []string) {
|
||||||
|
_ = cmd.Help()
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add subcommands
|
// Add subcommands
|
||||||
cmd.AddCommand(newSnapshotCreateCommand())
|
cmd.AddCommand(newSnapshotCreateCommand())
|
||||||
cmd.AddCommand(newSnapshotListCommand())
|
cmd.AddCommand(newSnapshotListCommand())
|
||||||
|
cmd.AddCommand(newSnapshotFilesCommand())
|
||||||
cmd.AddCommand(newSnapshotPurgeCommand())
|
cmd.AddCommand(newSnapshotPurgeCommand())
|
||||||
cmd.AddCommand(newSnapshotVerifyCommand())
|
cmd.AddCommand(newSnapshotVerifyCommand())
|
||||||
cmd.AddCommand(newSnapshotRemoveCommand())
|
cmd.AddCommand(newSnapshotRemoveCommand())
|
||||||
@@ -66,10 +77,16 @@ func newSnapshotCreateCommand() *cobra.Command {
|
|||||||
If snapshot names are provided, only those snapshots are created.
|
If snapshot names are provided, only those snapshots are created.
|
||||||
If no names are provided, all configured snapshots are created.
|
If no names are provided, all configured snapshots are created.
|
||||||
|
|
||||||
Config is located at /etc/vaultik/config.yml by default, but can be overridden by
|
The config is read from the path given by --config or VAULTIK_CONFIG;
|
||||||
specifying a path using --config or by setting VAULTIK_CONFIG to a path.`,
|
otherwise from the platform config directory (~/.config/vaultik/config.yml
|
||||||
|
on Linux), then /etc/vaultik/config.yml.`,
|
||||||
Args: cobra.ArbitraryArgs,
|
Args: cobra.ArbitraryArgs,
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
err := opts.Validate()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// Pass snapshot names from args
|
// Pass snapshot names from args
|
||||||
opts.Snapshots = args
|
opts.Snapshots = args
|
||||||
// --skip-errors is a global flag on the root command.
|
// --skip-errors is a global flag on the root command.
|
||||||
@@ -96,7 +113,23 @@ specifying a path using --config or by setting VAULTIK_CONFIG to a path.`,
|
|||||||
}, func(v *vaultik.Vaultik) error {
|
}, func(v *vaultik.Vaultik) error {
|
||||||
return v.CreateSnapshot(opts)
|
return v.CreateSnapshot(opts)
|
||||||
}, func(err error) {
|
}, func(err error) {
|
||||||
log.Error("Snapshot creation failed", "error", err)
|
if errors.Is(err, vaultik.ErrPostBackupPruneFailed) {
|
||||||
|
log.Info("Post-backup prune failed", "error", err)
|
||||||
|
ReportErrorf("Backup completed, but %v", err)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, vaultik.ErrFilesUnreadable) ||
|
||||||
|
errors.Is(err, vaultik.ErrSourcePathEmpty) ||
|
||||||
|
errors.Is(err, vaultik.ErrVolumeNotMounted) {
|
||||||
|
log.Info("Backup completed with an error", "error", err)
|
||||||
|
ReportErrorf("Backup completed, but %v", err)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Snapshot creation failed", "error", err)
|
||||||
ReportErrorf("Snapshot creation failed: %v", err)
|
ReportErrorf("Snapshot creation failed: %v", err)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
@@ -105,8 +138,13 @@ specifying a path using --config or by setting VAULTIK_CONFIG to a path.`,
|
|||||||
cmd.Flags().BoolVar(&opts.Cron, "cron", false,
|
cmd.Flags().BoolVar(&opts.Cron, "cron", false,
|
||||||
"Run in cron mode (silent unless warning or error)")
|
"Run in cron mode (silent unless warning or error)")
|
||||||
cmd.Flags().BoolVar(&opts.Prune, "prune", false,
|
cmd.Flags().BoolVar(&opts.Prune, "prune", false,
|
||||||
"After backup, drop older snapshots of the same name and remove "+
|
"After backup, drop older snapshots of the same name, remove "+
|
||||||
"orphaned blobs")
|
"orphaned blobs older than prune_grace_period, and delete each "+
|
||||||
|
"directory under metadata/ with no manifest once all its "+
|
||||||
|
"objects are older than prune_grace_period and its snapshot is "+
|
||||||
|
"not in the local index (not after a backup that skipped "+
|
||||||
|
"unreadable files, found a configured path empty, or did not "+
|
||||||
|
"find a mount point an earlier snapshot found)")
|
||||||
cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "",
|
cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "",
|
||||||
"With --prune: keep snapshots newer than this duration "+
|
"With --prune: keep snapshots newer than this duration "+
|
||||||
"(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+
|
"(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+
|
||||||
@@ -126,7 +164,7 @@ func newSnapshotListCommand() *cobra.Command {
|
|||||||
Long: "Lists all snapshots with their ID, timestamp, and compressed size",
|
Long: "Lists all snapshots with their ID, timestamp, and compressed size",
|
||||||
Args: cobra.NoArgs,
|
Args: cobra.NoArgs,
|
||||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
return runVaultikApp(cmd, readOnly, false, false,
|
return runVaultikApp(cmd, readOnly, false,
|
||||||
"Failed to list snapshots",
|
"Failed to list snapshots",
|
||||||
func(v *vaultik.Vaultik) error {
|
func(v *vaultik.Vaultik) error {
|
||||||
return v.ListSnapshots(jsonOutput)
|
return v.ListSnapshots(jsonOutput)
|
||||||
@@ -139,6 +177,44 @@ func newSnapshotListCommand() *cobra.Command {
|
|||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newSnapshotFilesCommand creates the 'snapshot files' subcommand
|
||||||
|
func newSnapshotFilesCommand() *cobra.Command {
|
||||||
|
var jsonOutput bool
|
||||||
|
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "files <snapshot-id> [path]",
|
||||||
|
Short: "List the files in a snapshot",
|
||||||
|
Long: `Lists the path, size, mode and modification time of every file in a
|
||||||
|
snapshot, without restoring it. With a path, lists only that path and
|
||||||
|
what is under it; a path that matches nothing is an error.
|
||||||
|
|
||||||
|
The snapshot may be named by its ID or, on a host with no local index,
|
||||||
|
by the remote key that 'snapshot list' prints for a remote-only snapshot
|
||||||
|
(an unambiguous leading part is enough).
|
||||||
|
|
||||||
|
The file list is only in the snapshot's encrypted database, so this
|
||||||
|
downloads and decrypts it, and requires the age private key in the
|
||||||
|
VAULTIK_AGE_SECRET_KEY environment variable, as 'snapshot restore' does.`,
|
||||||
|
Args: cobra.RangeArgs(1, filesMaxArgs),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
path := ""
|
||||||
|
if len(args) == filesMaxArgs {
|
||||||
|
path = args[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
return runVaultikApp(cmd, readOnly, jsonOutput,
|
||||||
|
"Failed to list snapshot files",
|
||||||
|
func(v *vaultik.Vaultik) error {
|
||||||
|
return v.ListSnapshotFiles(args[0], path, jsonOutput)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
|
||||||
|
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
// newSnapshotPurgeCommand creates the 'snapshot purge' subcommand
|
// newSnapshotPurgeCommand creates the 'snapshot purge' subcommand
|
||||||
func newSnapshotPurgeCommand() *cobra.Command {
|
func newSnapshotPurgeCommand() *cobra.Command {
|
||||||
opts := &vaultik.SnapshotPurgeOptions{}
|
opts := &vaultik.SnapshotPurgeOptions{}
|
||||||
@@ -162,7 +238,7 @@ restrict the operation to specific snapshot names.`,
|
|||||||
return errPurgeCriteriaBoth
|
return errPurgeCriteriaBoth
|
||||||
}
|
}
|
||||||
|
|
||||||
return runVaultikApp(cmd, mutating, false, false,
|
return runVaultikApp(cmd, mutating, false,
|
||||||
"Failed to purge snapshots",
|
"Failed to purge snapshots",
|
||||||
func(v *vaultik.Vaultik) error {
|
func(v *vaultik.Vaultik) error {
|
||||||
return v.PurgeSnapshotsWithOptions(opts)
|
return v.PurgeSnapshotsWithOptions(opts)
|
||||||
@@ -225,7 +301,7 @@ func newSnapshotVerifyCommand() *cobra.Command {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Error("Verification failed", "error", err)
|
log.Info("Verification failed", "error", err)
|
||||||
ReportErrorf("Verification failed: %v", err)
|
ReportErrorf("Verification failed: %v", err)
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
@@ -251,21 +327,29 @@ By default, this removes the snapshot from the local index database and
|
|||||||
strips the snapshot's metadata from the backup destination store. Blobs
|
strips the snapshot's metadata from the backup destination store. Blobs
|
||||||
are NOT touched: deleting them requires reading every remaining remote
|
are NOT touched: deleting them requires reading every remaining remote
|
||||||
manifest (the destination store may hold snapshots this host doesn't
|
manifest (the destination store may hold snapshots this host doesn't
|
||||||
know about), which is what 'vaultik prune' does. On success the command
|
know about), which is what 'vaultik prune' does. The command prints the
|
||||||
prints the exact 'vaultik prune' invocation to run as a follow-up.
|
'vaultik prune' invocation to run as a follow-up only when it removed the
|
||||||
|
snapshot's metadata from the destination store, and never under --json.
|
||||||
|
|
||||||
|
An ID that names no snapshot in the local index or on the destination
|
||||||
|
store is an error.
|
||||||
|
|
||||||
Use --local-only to skip the remote half (e.g. when you want to forget a
|
Use --local-only to skip the remote half (e.g. when you want to forget a
|
||||||
snapshot locally without touching the destination store).
|
snapshot locally without touching the destination store); the snapshot
|
||||||
|
must then be in the local index.
|
||||||
|
|
||||||
If the remote is unreachable, the local-database removal still completes
|
If removing the snapshot's metadata from the destination store fails (for
|
||||||
and a warning is emitted; rerun 'vaultik prune' once the destination store
|
example because the remote is unreachable), the local-database removal
|
||||||
is reachable to finish remote cleanup.
|
still completes and a warning is emitted; run 'vaultik snapshot remove
|
||||||
|
<snapshot-id>' again once the destination store is reachable to remove
|
||||||
|
the snapshot's metadata from it ('vaultik prune' does not). For a
|
||||||
|
snapshot that is only on the destination store, that failure is an error.
|
||||||
|
|
||||||
To wipe the entire destination store and start over, use 'vaultik remote
|
To wipe the entire destination store and start over, use 'vaultik remote
|
||||||
nuke --force' — it is the single supported entry point for that.`,
|
nuke --force' — it is the single supported entry point for that.`,
|
||||||
Args: requireSnapshotIDArg,
|
Args: requireSnapshotIDArg,
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
return runVaultikApp(cmd, mutating, opts.JSON, opts.JSON,
|
return runVaultikApp(cmd, mutating, opts.JSON,
|
||||||
"Failed to remove snapshot",
|
"Failed to remove snapshot",
|
||||||
func(v *vaultik.Vaultik) error {
|
func(v *vaultik.Vaultik) error {
|
||||||
_, err := v.RemoveSnapshot(args[0], opts)
|
_, err := v.RemoveSnapshot(args[0], opts)
|
||||||
@@ -278,7 +362,8 @@ nuke --force' — it is the single supported entry point for that.`,
|
|||||||
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Skip confirmation prompt")
|
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Skip confirmation prompt")
|
||||||
cmd.Flags().BoolVar(&opts.DryRun, "dry-run", false,
|
cmd.Flags().BoolVar(&opts.DryRun, "dry-run", false,
|
||||||
"Show what would be removed without removing")
|
"Show what would be removed without removing")
|
||||||
cmd.Flags().BoolVar(&opts.JSON, "json", false, "Output result as JSON")
|
cmd.Flags().BoolVar(&opts.JSON, "json", false,
|
||||||
|
"Output result as JSON; skips the confirmation prompt, as --force does")
|
||||||
cmd.Flags().BoolVar(&opts.LocalOnly, "local-only", false,
|
cmd.Flags().BoolVar(&opts.LocalOnly, "local-only", false,
|
||||||
"Skip remote cleanup; only touch the local index")
|
"Skip remote cleanup; only touch the local index")
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ This command will restore files from the specified snapshot to the
|
|||||||
target directory.
|
target directory.
|
||||||
If no paths are specified, all files are restored.
|
If no paths are specified, all files are restored.
|
||||||
If paths are specified, only matching files/directories are restored.
|
If paths are specified, only matching files/directories are restored.
|
||||||
|
A path that matches nothing in the snapshot is named in a warning, and
|
||||||
|
the command exits non-zero after restoring the paths that match.
|
||||||
|
|
||||||
The snapshot may be named by its ID or, when restoring on a host with no
|
The snapshot may be named by its ID or, when restoring on a host with no
|
||||||
local index, by the remote key that 'snapshot list' prints for a
|
local index, by the remote key that 'snapshot list' prints for a
|
||||||
@@ -102,7 +104,7 @@ func runRestore(cmd *cobra.Command, args []string, opts *RestoreOptions) error {
|
|||||||
SkipErrors: rootFlags.SkipErrors,
|
SkipErrors: rootFlags.SkipErrors,
|
||||||
})
|
})
|
||||||
}, func(err error) {
|
}, func(err error) {
|
||||||
log.Error("Restore operation failed", "error", err)
|
log.Info("Restore operation failed", "error", err)
|
||||||
ReportErrorf("Restore failed: %v", err)
|
ReportErrorf("Restore failed: %v", err)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -37,13 +37,13 @@ func writeVersion(out *ui.Writer) {
|
|||||||
w := out.Out()
|
w := out.Out()
|
||||||
|
|
||||||
_, _ = fmt.Fprintf(w, "vaultik %s\n", globals.Version)
|
_, _ = fmt.Fprintf(w, "vaultik %s\n", globals.Version)
|
||||||
_, _ = fmt.Fprintf(w, " commit: %s\n", globals.Commit)
|
_, _ = fmt.Fprintf(w, " commit: %s\n", globals.Commit)
|
||||||
_, _ = fmt.Fprintf(w, " build date: %s\n", globals.CommitDate)
|
_, _ = fmt.Fprintf(w, " commit date: %s\n", globals.CommitDate)
|
||||||
_, _ = fmt.Fprintf(w, " go: %s\n", runtime.Version())
|
_, _ = fmt.Fprintf(w, " go: %s\n", runtime.Version())
|
||||||
_, _ = fmt.Fprintf(w, " os/arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
|
_, _ = fmt.Fprintf(w, " os/arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
|
||||||
_, _ = fmt.Fprintf(w, " author: %s\n", globals.Author)
|
_, _ = fmt.Fprintf(w, " author: %s\n", globals.Author)
|
||||||
_, _ = fmt.Fprintf(w, " homepage: %s\n", globals.Homepage)
|
_, _ = fmt.Fprintf(w, " homepage: %s\n", globals.Homepage)
|
||||||
_, _ = fmt.Fprintf(w, " license: %s\n", globals.License)
|
_, _ = fmt.Fprintf(w, " license: %s\n", globals.License)
|
||||||
|
|
||||||
if globals.IsDevVersion(globals.Version) {
|
if globals.IsDevVersion(globals.Version) {
|
||||||
_, _ = fmt.Fprintln(w)
|
_, _ = fmt.Fprintln(w)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cli_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -49,6 +50,42 @@ func TestVersionCommandReportsBuildVersion(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestVersionCommandReportLines checks the label, padding and value of
|
||||||
|
// every line of the report. Commit and CommitDate get different values,
|
||||||
|
// so a line that prints the wrong one fails.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // sets globals.Commit and globals.CommitDate
|
||||||
|
func TestVersionCommandReportLines(t *testing.T) {
|
||||||
|
const (
|
||||||
|
commit = "abc1234"
|
||||||
|
commitDate = "2026-11-09"
|
||||||
|
)
|
||||||
|
|
||||||
|
previousCommit, previousCommitDate := globals.Commit, globals.CommitDate
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
globals.Commit = previousCommit
|
||||||
|
globals.CommitDate = previousCommitDate
|
||||||
|
})
|
||||||
|
|
||||||
|
globals.Commit = commit
|
||||||
|
globals.CommitDate = commitDate
|
||||||
|
|
||||||
|
want := "vaultik " + globals.Version + "\n" +
|
||||||
|
" commit: " + commit + "\n" +
|
||||||
|
" commit date: " + commitDate + "\n" +
|
||||||
|
" go: " + runtime.Version() + "\n" +
|
||||||
|
" os/arch: " + runtime.GOOS + "/" + runtime.GOARCH + "\n" +
|
||||||
|
" author: " + globals.Author + "\n" +
|
||||||
|
" homepage: " + globals.Homepage + "\n" +
|
||||||
|
" license: " + globals.License + "\n"
|
||||||
|
|
||||||
|
out := runVersionCommand(t)
|
||||||
|
if !strings.HasPrefix(out, want) {
|
||||||
|
t.Errorf("report:\n%s\nwant it to start with:\n%s", out, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestVersionCommandFlagsDevelopmentBuild is the regression test for
|
// TestVersionCommandFlagsDevelopmentBuild is the regression test for
|
||||||
// the thing this command exists to prevent: a build that is not a
|
// the thing this command exists to prevent: a build that is not a
|
||||||
// release must say so. The notice used to be gated on the version
|
// release must say so. The notice used to be gated on the version
|
||||||
|
|||||||
+174
-50
@@ -4,12 +4,15 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"filippo.io/age"
|
"filippo.io/age"
|
||||||
"git.eeqj.de/sneak/smartconfig"
|
"git.eeqj.de/sneak/smartconfig"
|
||||||
@@ -29,15 +32,21 @@ const appName = "vaultik"
|
|||||||
//nolint:gosec // G101: marker for detecting a pasted secret key, not a credential
|
//nolint:gosec // G101: marker for detecting a pasted secret key, not a credential
|
||||||
const secretKeyPrefix = "AGE-SECRET-KEY-"
|
const secretKeyPrefix = "AGE-SECRET-KEY-"
|
||||||
|
|
||||||
// Defaults and validation bounds for tunable settings.
|
// Defaults and validation bounds for tunable settings. MB and GB are
|
||||||
|
// 1000-based, as the size parser reads them; the S3 part sizes are S3's own
|
||||||
|
// limits, which are 1024-based (MiB, GiB).
|
||||||
const (
|
const (
|
||||||
defaultBlobSizeLimit = Size(10 * 1024 * 1024 * 1024) // 10GB
|
defaultBlobSizeLimit = Size(10 * 1000 * 1000 * 1000) // 10GB
|
||||||
defaultChunkSize = Size(10 * 1024 * 1024) // 10MB
|
defaultChunkSize = Size(10 * 1000 * 1000) // 10MB
|
||||||
defaultS3PartSize = Size(5 * 1024 * 1024) // 5MB
|
defaultS3PartSize = Size(5 * 1024 * 1024) // 5MiB
|
||||||
defaultCompressionLevel = 3
|
defaultCompressionLevel = 3
|
||||||
minChunkSize = 1024 * 1024 // 1MB
|
defaultPruneGracePeriod = 24 * time.Hour
|
||||||
|
minChunkSize = 1000 * 1000 // 1MB
|
||||||
minCompressionLevel = 1
|
minCompressionLevel = 1
|
||||||
maxCompressionLevel = 19
|
maxCompressionLevel = 19
|
||||||
|
// S3 accepts a multipart upload part from 5MiB to 5GiB.
|
||||||
|
minS3PartSize = 5 * 1024 * 1024
|
||||||
|
maxS3PartSize = 5 * 1024 * 1024 * 1024
|
||||||
)
|
)
|
||||||
|
|
||||||
// Sentinel validation errors.
|
// Sentinel validation errors.
|
||||||
@@ -48,21 +57,35 @@ var (
|
|||||||
errRecipientNotX25519 = errors.New(
|
errRecipientNotX25519 = errors.New(
|
||||||
"not a valid recipient; only X25519 age1... public keys are supported")
|
"not a valid recipient; only X25519 age1... public keys are supported")
|
||||||
errNoSnapshots = errors.New(
|
errNoSnapshots = errors.New(
|
||||||
"at least one snapshot must be configured (see config.example.yml)")
|
"at least one snapshot must be configured (see configs/config.example.yml)")
|
||||||
errSnapshotNoPaths = errors.New("snapshot must have at least one path")
|
errSnapshotNoPaths = errors.New("snapshot must have at least one path")
|
||||||
errChunkSizeTooSmall = errors.New("chunk_size must be at least 1MB")
|
errChunkSizeTooSmall = errors.New("chunk_size must be at least 1MB")
|
||||||
errBlobSizeTooSmall = errors.New(
|
errBlobSizeTooSmall = errors.New(
|
||||||
"blob_size_limit must be at least the largest chunk the chunker can " +
|
"blob_size_limit must be at least the largest chunk the chunker can " +
|
||||||
"emit (chunk_size times the FastCDC size spread)")
|
"emit (chunk_size times the FastCDC size spread)")
|
||||||
errBadCompression = errors.New("compression_level must be between 1 and 19")
|
errBadCompression = errors.New("compression_level must be between 1 and 19")
|
||||||
|
errBadS3PartSize = errors.New("s3.part_size must be between 5MiB and 5GiB")
|
||||||
errBadStorageScheme = errors.New(
|
errBadStorageScheme = errors.New(
|
||||||
"storage_url must start with s3://, file://, or rclone://")
|
"storage_url must start with s3://, file://, or rclone://")
|
||||||
|
errFileURLNotAbsolute = errors.New(
|
||||||
|
"a file:// storage_url needs an absolute path, " +
|
||||||
|
"as in file:///path/to/backup")
|
||||||
|
errIndexPathNotAbsolute = errors.New(
|
||||||
|
"index_path and VAULTIK_INDEX_PATH need an absolute path, " +
|
||||||
|
"as in ~/.local/share/vaultik/index.sqlite")
|
||||||
|
errNegativePruneGracePeriod = errors.New(
|
||||||
|
"prune_grace_period must not be negative")
|
||||||
errStorageNotConfigured = errors.New(
|
errStorageNotConfigured = errors.New(
|
||||||
"storage not configured; set storage_url or provide s3.endpoint + " +
|
"storage not configured; set storage_url or provide s3.endpoint + " +
|
||||||
"s3.bucket + credentials")
|
"s3.bucket + credentials")
|
||||||
errS3BucketRequired = errors.New("s3.bucket is required (or set storage_url)")
|
errS3BucketRequired = errors.New("s3.bucket is required (or set storage_url)")
|
||||||
errS3KeyIDRequired = errors.New("s3.access_key_id is required")
|
)
|
||||||
errS3SecretRequired = errors.New("s3.secret_access_key is required")
|
|
||||||
|
// Validate returns these when S3 storage is configured without its
|
||||||
|
// credentials.
|
||||||
|
var (
|
||||||
|
ErrS3KeyIDRequired = errors.New("s3.access_key_id is required")
|
||||||
|
ErrS3SecretRequired = errors.New("s3.secret_access_key is required")
|
||||||
)
|
)
|
||||||
|
|
||||||
// expandTilde expands ~ at the start of a path to the user's home directory.
|
// expandTilde expands ~ at the start of a path to the user's home directory.
|
||||||
@@ -177,6 +200,15 @@ type Config struct {
|
|||||||
Snapshots map[string]SnapshotConfig `yaml:"snapshots"`
|
Snapshots map[string]SnapshotConfig `yaml:"snapshots"`
|
||||||
CompressionLevel int `yaml:"compression_level"`
|
CompressionLevel int `yaml:"compression_level"`
|
||||||
|
|
||||||
|
// PruneGracePeriod is how old a blob no manifest lists must be before
|
||||||
|
// a prune deletes it, and how old every object in a directory under
|
||||||
|
// metadata/ with no manifest must be before a prune deletes that
|
||||||
|
// directory. A backup writes its manifest only once it has uploaded
|
||||||
|
// all its blobs and its db.zst.age, so a younger blob or directory may
|
||||||
|
// belong to a backup still running, on this host or another sharing
|
||||||
|
// the destination store.
|
||||||
|
PruneGracePeriod time.Duration `yaml:"prune_grace_period"`
|
||||||
|
|
||||||
// StorageURL specifies the storage backend using a URL format.
|
// StorageURL specifies the storage backend using a URL format.
|
||||||
// Takes precedence over S3Config if set.
|
// Takes precedence over S3Config if set.
|
||||||
// Supported formats:
|
// Supported formats:
|
||||||
@@ -226,24 +258,84 @@ func New(path Path) (*Config, error) {
|
|||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load reads and parses the configuration file from the specified path.
|
// Load reads the configuration file at path, parses it with Parse, warns
|
||||||
// It applies default values for optional fields, performs environment variable
|
// when others can read the file, and validates the configuration.
|
||||||
// substitution using smartconfig, and validates the configuration.
|
// Returns an error if the file cannot be read, parsed, or if validation
|
||||||
// The configuration file should be in YAML format. Returns an error if the file
|
// fails.
|
||||||
// cannot be read, parsed, or if validation fails.
|
|
||||||
func Load(path string) (*Config, error) {
|
func Load(path string) (*Config, error) {
|
||||||
// Load config using smartconfig for interpolation
|
data, err := os.ReadFile(path) //nolint:gosec // G304: config path is operator-supplied
|
||||||
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
// refuses a key that no setting has and a size setting whose value is not a
|
||||||
|
// size, naming the setting. It applies default values for optional
|
||||||
|
// fields, fills in ${...} references using smartconfig, and expands ~ in
|
||||||
|
// paths.
|
||||||
|
func Parse(data []byte) (*Config, error) {
|
||||||
|
// smartconfig drops line numbers, so keys are checked in the data as
|
||||||
|
// written.
|
||||||
|
var root yaml.Node
|
||||||
|
|
||||||
|
err := yaml.Unmarshal(data, &root)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse config: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = checkKeys(&root, reflect.TypeFor[Config](), "",
|
||||||
|
map[*yaml.Node]bool{}, map[nodeAndType]bool{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load config using smartconfig for interpolation
|
||||||
|
sc, err := smartconfig.NewFromReader(bytes.NewReader(data))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to load config file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A ${...} reference can bring in keys that are not in the file, and
|
||||||
|
// is the value of a size setting only once it is filled in.
|
||||||
|
err = checkFilledConfig(sc.Data())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
cfg := &Config{
|
cfg := &Config{
|
||||||
// Set defaults
|
// Set defaults
|
||||||
BlobSizeLimit: defaultBlobSizeLimit,
|
BlobSizeLimit: defaultBlobSizeLimit,
|
||||||
ChunkSize: defaultChunkSize,
|
ChunkSize: defaultChunkSize,
|
||||||
IndexPath: filepath.Join(xdg.DataHome, appName, "index.sqlite"),
|
IndexPath: filepath.Join(xdg.DataHome, appName, "index.sqlite"),
|
||||||
CompressionLevel: defaultCompressionLevel,
|
CompressionLevel: defaultCompressionLevel,
|
||||||
|
PruneGracePeriod: defaultPruneGracePeriod,
|
||||||
|
S3: S3Config{PartSize: defaultS3PartSize},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert smartconfig data to YAML then unmarshal
|
// Convert smartconfig data to YAML then unmarshal
|
||||||
@@ -294,28 +386,6 @@ func Load(path string) (*Config, error) {
|
|||||||
cfg.S3.Region = "us-east-1"
|
cfg.S3.Region = "us-east-1"
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.S3.PartSize == 0 {
|
|
||||||
cfg.S3.PartSize = defaultS3PartSize
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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("Config file has insecure permissions (contains S3 credentials)",
|
|
||||||
"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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,12 +396,18 @@ func Load(path string) (*Config, error) {
|
|||||||
// never the value. An empty list is accepted, because only snapshot
|
// never the value. An empty list is accepted, because only snapshot
|
||||||
// create needs a recipient and it checks for one itself
|
// create needs a recipient and it checks for one itself
|
||||||
// - At least one snapshot must be configured with at least one path
|
// - At least one snapshot must be configured with at least one path
|
||||||
|
// - Every exclude pattern, global or in a snapshot, must compile; errors
|
||||||
|
// name the setting and quote the pattern
|
||||||
// - Storage must be configured (either storage_url or s3.* fields)
|
// - Storage must be configured (either storage_url or s3.* fields)
|
||||||
|
// - The index path must be absolute: a relative one would resolve against
|
||||||
|
// the working directory, so each directory would get its own index
|
||||||
// - Chunk size must be at least 1MB
|
// - Chunk size must be at least 1MB
|
||||||
// - Blob size limit must be at least the largest chunk the chunker can emit
|
// - Blob size limit must be at least the largest chunk the chunker can emit
|
||||||
// (chunk_size times chunker.ChunkSizeSpread), so a single-chunk blob never
|
// (chunk_size times chunker.ChunkSizeSpread), so a single-chunk blob never
|
||||||
// exceeds the configured limit
|
// exceeds the configured limit
|
||||||
// - Compression level must be between 1 and 19
|
// - Compression level must be between 1 and 19
|
||||||
|
// - S3 part size must be between 5MiB and 5GiB, the part sizes S3 accepts
|
||||||
|
// - Prune grace period must not be negative
|
||||||
//
|
//
|
||||||
// Returns an error describing the first validation failure encountered.
|
// Returns an error describing the first validation failure encountered.
|
||||||
func (c *Config) Validate() error {
|
func (c *Config) Validate() error {
|
||||||
@@ -342,22 +418,26 @@ func (c *Config) Validate() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(c.Snapshots) == 0 {
|
err := c.validateSnapshots()
|
||||||
return errNoSnapshots
|
if err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
for name, snap := range c.Snapshots {
|
err = c.validateExcludes()
|
||||||
if len(snap.Paths) == 0 {
|
if err != nil {
|
||||||
return fmt.Errorf("%w: %q", errSnapshotNoPaths, name)
|
return err
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate storage configuration
|
// Validate storage configuration
|
||||||
err := c.validateStorage()
|
err = c.validateStorage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !filepath.IsAbs(c.IndexPath) {
|
||||||
|
return fmt.Errorf("%w: %q", errIndexPathNotAbsolute, c.IndexPath)
|
||||||
|
}
|
||||||
|
|
||||||
if c.ChunkSize.Int64() < minChunkSize {
|
if c.ChunkSize.Int64() < minChunkSize {
|
||||||
return errChunkSizeTooSmall
|
return errChunkSizeTooSmall
|
||||||
}
|
}
|
||||||
@@ -376,6 +456,31 @@ func (c *Config) Validate() error {
|
|||||||
return errBadCompression
|
return errBadCompression
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if c.S3.PartSize.Int64() < minS3PartSize ||
|
||||||
|
c.S3.PartSize.Int64() > maxS3PartSize {
|
||||||
|
return errBadS3PartSize
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.PruneGracePeriod < 0 {
|
||||||
|
return errNegativePruneGracePeriod
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateSnapshots refuses a config with no snapshot or with a snapshot
|
||||||
|
// that has no path.
|
||||||
|
func (c *Config) validateSnapshots() error {
|
||||||
|
if len(c.Snapshots) == 0 {
|
||||||
|
return errNoSnapshots
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, snap := range c.Snapshots {
|
||||||
|
if len(snap.Paths) == 0 {
|
||||||
|
return fmt.Errorf("%w: %q", errSnapshotNoPaths, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,6 +516,18 @@ func (c *Config) setAgeSecretKey() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readableByOthersWarning is the warning Load logs when others can read
|
||||||
|
// the config file. It says "may contain" because the S3 credentials are
|
||||||
|
// seen only after smartconfig has replaced any ${...} reference in the
|
||||||
|
// file with its value, so a set credential need not be in the file.
|
||||||
|
func (c *Config) readableByOthersWarning() string {
|
||||||
|
if c.S3.AccessKeyID != "" || c.S3.SecretAccessKey != "" {
|
||||||
|
return "Config file is readable by others and may contain S3 credentials"
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Config file is readable by others"
|
||||||
|
}
|
||||||
|
|
||||||
// validateStorage validates storage configuration.
|
// validateStorage validates storage configuration.
|
||||||
// If StorageURL is set, it takes precedence. S3 URLs require credentials.
|
// If StorageURL is set, it takes precedence. S3 URLs require credentials.
|
||||||
// File URLs don't require any S3 configuration.
|
// File URLs don't require any S3 configuration.
|
||||||
@@ -430,11 +547,11 @@ func (c *Config) validateStorage() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if c.S3.AccessKeyID == "" {
|
if c.S3.AccessKeyID == "" {
|
||||||
return errS3KeyIDRequired
|
return ErrS3KeyIDRequired
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.S3.SecretAccessKey == "" {
|
if c.S3.SecretAccessKey == "" {
|
||||||
return errS3SecretRequired
|
return ErrS3SecretRequired
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -442,11 +559,18 @@ func (c *Config) validateStorage() error {
|
|||||||
|
|
||||||
// validateStorageURL validates URL-based storage configuration. File and
|
// validateStorageURL validates URL-based storage configuration. File and
|
||||||
// rclone URLs need no credentials; S3 URLs require the legacy s3.*
|
// rclone URLs need no credentials; S3 URLs require the legacy s3.*
|
||||||
// credential fields.
|
// credential fields. A file URL must name an absolute path: a relative one
|
||||||
|
// would resolve against the working directory, so the destination would
|
||||||
|
// move with it.
|
||||||
func (c *Config) validateStorageURL() error {
|
func (c *Config) validateStorageURL() error {
|
||||||
switch {
|
switch {
|
||||||
case strings.HasPrefix(c.StorageURL, "file://"):
|
case strings.HasPrefix(c.StorageURL, "file://"):
|
||||||
// File storage doesn't need S3 credentials
|
// storage.ParseStorageURL applies the same rule, but config
|
||||||
|
// cannot import storage, which imports config.
|
||||||
|
if !strings.HasPrefix(c.StorageURL, "file:///") {
|
||||||
|
return errFileURLNotAbsolute
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
case strings.HasPrefix(c.StorageURL, "rclone://"):
|
case strings.HasPrefix(c.StorageURL, "rclone://"):
|
||||||
// Rclone storage uses rclone's own config
|
// Rclone storage uses rclone's own config
|
||||||
@@ -454,11 +578,11 @@ func (c *Config) validateStorageURL() error {
|
|||||||
case strings.HasPrefix(c.StorageURL, "s3://"):
|
case strings.HasPrefix(c.StorageURL, "s3://"):
|
||||||
// S3 storage needs credentials
|
// S3 storage needs credentials
|
||||||
if c.S3.AccessKeyID == "" {
|
if c.S3.AccessKeyID == "" {
|
||||||
return fmt.Errorf("%w for s3:// URLs", errS3KeyIDRequired)
|
return fmt.Errorf("%w for s3:// URLs", ErrS3KeyIDRequired)
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.S3.SecretAccessKey == "" {
|
if c.S3.SecretAccessKey == "" {
|
||||||
return fmt.Errorf("%w for s3:// URLs", errS3SecretRequired)
|
return fmt.Errorf("%w for s3:// URLs", ErrS3SecretRequired)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"sneak.berlin/go/vaultik/internal/chunker"
|
"sneak.berlin/go/vaultik/internal/chunker"
|
||||||
|
"sneak.berlin/go/vaultik/internal/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -88,12 +90,12 @@ func TestConfigLoad(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TestExampleConfigIsScrubbedAndLoads checks that the shipped
|
// TestExampleConfigIsScrubbedAndLoads checks that the shipped
|
||||||
// config.example.yml carries only neutral placeholders (no real credentials,
|
// configs/config.example.yml carries only neutral placeholders (no real
|
||||||
// private addresses, or internal host names) and still parses.
|
// credentials, private addresses, or internal host names) and still parses.
|
||||||
func TestExampleConfigIsScrubbedAndLoads(t *testing.T) {
|
func TestExampleConfigIsScrubbedAndLoads(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
examplePath := filepath.Join("..", "..", "config.example.yml")
|
examplePath := filepath.Join("..", "..", "configs", "config.example.yml")
|
||||||
|
|
||||||
cfg, err := Load(examplePath)
|
cfg, err := Load(examplePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -163,9 +165,11 @@ func TestValidateBlobSizeLimit(t *testing.T) {
|
|||||||
AgeRecipients: []string{testSneakAgePublicKey},
|
AgeRecipients: []string{testSneakAgePublicKey},
|
||||||
Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}},
|
Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}},
|
||||||
StorageURL: "file:///tmp/vaultik-test-store",
|
StorageURL: "file:///tmp/vaultik-test-store",
|
||||||
|
IndexPath: "/tmp/vaultik-test-index.sqlite",
|
||||||
ChunkSize: chunkSize,
|
ChunkSize: chunkSize,
|
||||||
BlobSizeLimit: blobLimit,
|
BlobSizeLimit: blobLimit,
|
||||||
CompressionLevel: 3,
|
CompressionLevel: 3,
|
||||||
|
S3: S3Config{PartSize: defaultS3PartSize},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,6 +225,351 @@ func TestValidateBlobSizeLimit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestValidateS3PartSize checks that s3.part_size is held to the part sizes
|
||||||
|
// S3 accepts, 5MiB to 5GiB, by changing only the part size of the test
|
||||||
|
// config. "5MB" in the config file is 5,000,000 bytes, below the minimum.
|
||||||
|
func TestValidateS3PartSize(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
base, err := Load(os.Getenv("VAULTIK_CONFIG"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to load config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
partSize Size
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "5MB is rejected",
|
||||||
|
partSize: 5_000_000,
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "one byte below 5MiB is rejected",
|
||||||
|
partSize: minS3PartSize - 1,
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "5MiB is accepted",
|
||||||
|
partSize: minS3PartSize,
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "5GiB is accepted",
|
||||||
|
partSize: maxS3PartSize,
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "one byte above 5GiB is rejected",
|
||||||
|
partSize: maxS3PartSize + 1,
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := *base
|
||||||
|
cfg.S3.PartSize = tt.partSize
|
||||||
|
|
||||||
|
err := cfg.Validate()
|
||||||
|
if tt.wantErr {
|
||||||
|
if !errors.Is(err, errBadS3PartSize) {
|
||||||
|
t.Fatalf("Validate() error = %v, want errBadS3PartSize", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Validate() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadS3PartSize checks that a config file without s3.part_size loads
|
||||||
|
// with the 5MiB default, and that an explicit 0 fails at load like any other
|
||||||
|
// part size S3 refuses.
|
||||||
|
func TestLoadS3PartSize(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const withoutPartSize = "snapshots:\n" +
|
||||||
|
" test:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" +
|
||||||
|
"storage_url: file:///tmp/vaultik-test-storage\n"
|
||||||
|
|
||||||
|
writeConfig := func(t *testing.T, text string) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(text), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("absent loads as 5MiB", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg, err := Load(writeConfig(t, withoutPartSize))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.S3.PartSize != defaultS3PartSize {
|
||||||
|
t.Errorf("s3.part_size = %d, want %d",
|
||||||
|
cfg.S3.PartSize, defaultS3PartSize)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("0 is rejected", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
_, err := Load(writeConfig(t, withoutPartSize+"s3:\n part_size: 0\n"))
|
||||||
|
if !errors.Is(err, errBadS3PartSize) {
|
||||||
|
t.Fatalf("Load() error = %v, want errBadS3PartSize", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDocumentedSizeDefaults checks that the defaults are the documented
|
||||||
|
// chunk_size 10MB and blob_size_limit 10GB as the parser reads those values
|
||||||
|
// (1000-based), so writing a default out in the config file changes nothing.
|
||||||
|
func TestDocumentedSizeDefaults(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg, err := Parse([]byte("chunk_size: 10MB\nblob_size_limit: 10GB\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Parse() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.ChunkSize != defaultChunkSize {
|
||||||
|
t.Errorf("chunk_size: 10MB is %d bytes, the default is %d",
|
||||||
|
cfg.ChunkSize, defaultChunkSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.BlobSizeLimit != defaultBlobSizeLimit {
|
||||||
|
t.Errorf("blob_size_limit: 10GB is %d bytes, the default is %d",
|
||||||
|
cfg.BlobSizeLimit, defaultBlobSizeLimit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDocumentedSizeExamples checks the 1MB minimum chunk_size and that
|
||||||
|
// every size the README, configs/config.example.yml and the config init template
|
||||||
|
// list as an example is accepted.
|
||||||
|
func TestDocumentedSizeExamples(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const withoutSizes = "snapshots:\n" +
|
||||||
|
" test:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" +
|
||||||
|
"storage_url: file:///tmp/vaultik-test-storage\n"
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
setting string
|
||||||
|
wantErr error
|
||||||
|
}{
|
||||||
|
{"chunk_size: 1MB", nil},
|
||||||
|
{"chunk_size: 999999", errChunkSizeTooSmall},
|
||||||
|
{"chunk_size: 5M", nil},
|
||||||
|
{"chunk_size: 10M", nil},
|
||||||
|
{"chunk_size: 10MB", nil},
|
||||||
|
{"chunk_size: 64MiB", nil},
|
||||||
|
{"chunk_size: 1GB", nil},
|
||||||
|
// Four times the default chunk_size, the documented minimum.
|
||||||
|
{"blob_size_limit: 40MB", nil},
|
||||||
|
{"blob_size_limit: 500MB", nil},
|
||||||
|
{"blob_size_limit: 1GB", nil},
|
||||||
|
{"blob_size_limit: 1GiB", nil},
|
||||||
|
{"blob_size_limit: 10G", nil},
|
||||||
|
{"blob_size_limit: 10GB", nil},
|
||||||
|
{"s3: {part_size: 5MiB}", nil},
|
||||||
|
{"s3: {part_size: 10MB}", nil},
|
||||||
|
{"s3: {part_size: 16MiB}", nil},
|
||||||
|
{"s3: {part_size: 100MiB}", nil},
|
||||||
|
{"s3: {part_size: 5GiB}", nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.setting, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg, err := Parse([]byte(withoutSizes + tt.setting + "\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Parse() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = cfg.Validate()
|
||||||
|
if !errors.Is(err, tt.wantErr) {
|
||||||
|
t.Fatalf("Validate() error = %v, want %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestValidatePruneGracePeriod checks that a negative prune_grace_period
|
||||||
|
// is refused rather than acting like 0s, which deletes unreferenced blobs
|
||||||
|
// and directories under metadata/ with no manifest at once, and that 0s
|
||||||
|
// and the documented examples are accepted.
|
||||||
|
func TestValidatePruneGracePeriod(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const withoutGracePeriod = "snapshots:\n" +
|
||||||
|
" test:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" +
|
||||||
|
"storage_url: file:///tmp/vaultik-test-storage\n"
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
setting string
|
||||||
|
wantErr error
|
||||||
|
}{
|
||||||
|
{"prune_grace_period: 0s", nil},
|
||||||
|
{"prune_grace_period: 90m", nil},
|
||||||
|
{"prune_grace_period: 36h", nil},
|
||||||
|
{"prune_grace_period: -1h", errNegativePruneGracePeriod},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.setting, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg, err := Parse([]byte(withoutGracePeriod + tt.setting + "\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Parse() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = cfg.Validate()
|
||||||
|
if !errors.Is(err, tt.wantErr) {
|
||||||
|
t.Fatalf("Validate() error = %v, want %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadPruneGracePeriod checks that a config file without
|
||||||
|
// prune_grace_period loads with the documented 24h. The value is written out
|
||||||
|
// here rather than taken from defaultPruneGracePeriod, so that a change of the
|
||||||
|
// default fails this test.
|
||||||
|
func TestLoadPruneGracePeriod(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const withoutGracePeriod = "snapshots:\n" +
|
||||||
|
" test:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" +
|
||||||
|
"storage_url: file:///tmp/vaultik-test-storage\n"
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(withoutGracePeriod), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := Load(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.PruneGracePeriod != 24*time.Hour {
|
||||||
|
t.Errorf("prune_grace_period = %s, want 24h", cfg.PruneGracePeriod)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadRejectsRelativeFileURL checks that a file:// storage_url with a
|
||||||
|
// relative path fails at load. Accepted, it would resolve against the
|
||||||
|
// working directory, so a backup run from another directory would write
|
||||||
|
// to a different destination and still succeed.
|
||||||
|
func TestLoadRejectsRelativeFileURL(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const relativeConfig = "snapshots:\n" +
|
||||||
|
" test:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" +
|
||||||
|
"storage_url: file://dest\n"
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(relativeConfig), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = Load(path)
|
||||||
|
if !errors.Is(err, errFileURLNotAbsolute) {
|
||||||
|
t.Fatalf("Load() error = %v, want errFileURLNotAbsolute", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(err.Error(), "absolute path") {
|
||||||
|
t.Errorf("error %q does not say to use an absolute path", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadIndexPath checks that a relative index_path fails at load, naming
|
||||||
|
// the value. Accepted, it would resolve against the working directory, so a
|
||||||
|
// backup run from another directory would start from an empty index. A path
|
||||||
|
// starting with ~ is expanded and loads.
|
||||||
|
func TestLoadIndexPath(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("home directory: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
load := func(t *testing.T, indexPath string) (*Config, error) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
data := "snapshots:\n" +
|
||||||
|
" test:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" +
|
||||||
|
"storage_url: file:///tmp/vaultik-test-storage\n" +
|
||||||
|
"index_path: " + indexPath + "\n"
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(data), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Load(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("relative path is rejected", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
_, err := load(t, "relative/index.sqlite")
|
||||||
|
if !errors.Is(err, errIndexPathNotAbsolute) {
|
||||||
|
t.Fatalf("Load() error = %v, want errIndexPathNotAbsolute", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(err.Error(), `"relative/index.sqlite"`) {
|
||||||
|
t.Errorf("error %q does not name the value", err.Error())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("path starting with ~ is expanded", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg, err := load(t, "~/vaultik/index.sqlite")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
want := filepath.Join(home, "vaultik", "index.sqlite")
|
||||||
|
if cfg.IndexPath != want {
|
||||||
|
t.Errorf("IndexPath = %q, want %q", cfg.IndexPath, want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// TestValidateAgeRecipients checks that recipients are parsed at config load
|
// TestValidateAgeRecipients checks that recipients are parsed at config load
|
||||||
// (a bad entry fails immediately, not mid-backup) and that no invalid entry —
|
// (a bad entry fails immediately, not mid-backup) and that no invalid entry —
|
||||||
// least of all a pasted secret key — is echoed in the error. An empty list
|
// least of all a pasted secret key — is echoed in the error. An empty list
|
||||||
@@ -233,9 +582,11 @@ func TestValidateAgeRecipients(t *testing.T) {
|
|||||||
AgeRecipients: recipients,
|
AgeRecipients: recipients,
|
||||||
Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}},
|
Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}},
|
||||||
StorageURL: "file:///tmp/vaultik-test-store",
|
StorageURL: "file:///tmp/vaultik-test-store",
|
||||||
|
IndexPath: "/tmp/vaultik-test-index.sqlite",
|
||||||
ChunkSize: Size(10 * 1024 * 1024),
|
ChunkSize: Size(10 * 1024 * 1024),
|
||||||
BlobSizeLimit: Size(10 * 1024 * 1024 * 1024),
|
BlobSizeLimit: Size(10 * 1024 * 1024 * 1024),
|
||||||
CompressionLevel: 3,
|
CompressionLevel: 3,
|
||||||
|
S3: S3Config{PartSize: defaultS3PartSize},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,3 +694,125 @@ func TestAgeSecretKeySourceName(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// loadReadableConfig writes configYAML to a file that others can read,
|
||||||
|
// loads it, and returns what the logger wrote to stderr meanwhile. The
|
||||||
|
// logger writes to the os.Stderr it finds when it is initialized, so
|
||||||
|
// os.Stderr is pointed at a file first. Not parallel-safe: os.Stderr and
|
||||||
|
// the logger are process-global.
|
||||||
|
func loadReadableConfig(t *testing.T, configYAML string) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
configPath := filepath.Join(dir, "config.yml")
|
||||||
|
stderrPath := filepath.Join(dir, "stderr")
|
||||||
|
|
||||||
|
err := os.WriteFile(configPath, []byte(configYAML), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("writing config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
//nolint:gosec // G302: the test needs a config file others can read
|
||||||
|
err = os.Chmod(configPath, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("chmod config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
stderrFile, err := os.Create(stderrPath) //nolint:gosec // G304: test temp path
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("creating stderr file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
previous := os.Stderr
|
||||||
|
os.Stderr = stderrFile
|
||||||
|
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
|
||||||
|
_, loadErr := Load(configPath)
|
||||||
|
|
||||||
|
os.Stderr = previous
|
||||||
|
|
||||||
|
log.Initialize(log.Config{})
|
||||||
|
|
||||||
|
_ = stderrFile.Close()
|
||||||
|
|
||||||
|
if loadErr != nil {
|
||||||
|
t.Fatalf("Load() error = %v", loadErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
captured, err := os.ReadFile(stderrPath) //nolint:gosec // G304: test temp path
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading stderr file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(captured)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadWarnsReadableConfigWithoutS3Credentials checks that a config
|
||||||
|
// file others can read, holding no S3 credentials, is warned about
|
||||||
|
// without a claim that it holds them.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // loadReadableConfig replaces os.Stderr
|
||||||
|
func TestLoadWarnsReadableConfigWithoutS3Credentials(t *testing.T) {
|
||||||
|
stderr := loadReadableConfig(t, `
|
||||||
|
storage_url: file:///var/backups/vaultik
|
||||||
|
snapshots:
|
||||||
|
home:
|
||||||
|
paths:
|
||||||
|
- /home
|
||||||
|
`)
|
||||||
|
|
||||||
|
if !strings.Contains(stderr, "Config file is readable by others") {
|
||||||
|
t.Errorf("expected a warning that the file is readable by others, got %q",
|
||||||
|
stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(stderr, "S3 credentials") {
|
||||||
|
t.Errorf("warning names S3 credentials the file does not set: %q", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLoadWarnsReadableConfigWithS3Credentials checks that a config file
|
||||||
|
// others can read and that sets S3 credentials, as values or as ${ENV:...}
|
||||||
|
// references, is warned about as one that may contain them.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // loadReadableConfig replaces os.Stderr
|
||||||
|
func TestLoadWarnsReadableConfigWithS3Credentials(t *testing.T) {
|
||||||
|
t.Setenv("VAULTIK_TEST_ACCESS_KEY_ID", "test-access-key")
|
||||||
|
t.Setenv("VAULTIK_TEST_SECRET_ACCESS_KEY", "test-secret-key")
|
||||||
|
|
||||||
|
configs := map[string]string{
|
||||||
|
"values": `
|
||||||
|
storage_url: s3://bucket/prefix?endpoint=s3.example.com
|
||||||
|
s3:
|
||||||
|
access_key_id: test-access-key
|
||||||
|
secret_access_key: test-secret-key
|
||||||
|
snapshots:
|
||||||
|
home:
|
||||||
|
paths:
|
||||||
|
- /home
|
||||||
|
`,
|
||||||
|
"references": `
|
||||||
|
storage_url: s3://bucket/prefix?endpoint=s3.example.com
|
||||||
|
s3:
|
||||||
|
access_key_id: ${ENV:VAULTIK_TEST_ACCESS_KEY_ID}
|
||||||
|
secret_access_key: ${ENV:VAULTIK_TEST_SECRET_ACCESS_KEY}
|
||||||
|
snapshots:
|
||||||
|
home:
|
||||||
|
paths:
|
||||||
|
- /home
|
||||||
|
`,
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, configYAML := range configs {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
stderr := loadReadableConfig(t, configYAML)
|
||||||
|
|
||||||
|
if !strings.Contains(stderr,
|
||||||
|
"Config file is readable by others and may contain S3 credentials") {
|
||||||
|
t.Errorf("expected a warning naming the S3 credentials, got %q",
|
||||||
|
stderr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"sneak.berlin/go/vaultik/internal/exclude"
|
||||||
|
)
|
||||||
|
|
||||||
|
// validateExcludes refuses an exclude pattern, global or in a snapshot,
|
||||||
|
// that does not compile, naming the setting and quoting the pattern.
|
||||||
|
func (c *Config) validateExcludes() error {
|
||||||
|
err := validateExcludeList("exclude", c.Exclude)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range c.SnapshotNames() {
|
||||||
|
err = validateExcludeList("snapshots."+name+".exclude",
|
||||||
|
c.Snapshots[name].Exclude)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateExcludeList refuses the first pattern in patterns that does not
|
||||||
|
// compile. setting is the name of the list, as in "exclude".
|
||||||
|
func validateExcludeList(setting string, patterns []string) error {
|
||||||
|
for i, pattern := range patterns {
|
||||||
|
_, _, err := exclude.Compile(pattern)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s[%d]: %w", setting, i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package config_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"sneak.berlin/go/vaultik/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestLoadRefusesBadExcludePattern checks that an exclude pattern that does
|
||||||
|
// not compile, global or in a snapshot, fails at load with the setting and
|
||||||
|
// the pattern named, rather than the backup storing what it meant to leave
|
||||||
|
// out.
|
||||||
|
func TestLoadRefusesBadExcludePattern(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const storage = "storage_url: file:///tmp/vaultik-test-storage\n"
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
config string
|
||||||
|
wantErr string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "global",
|
||||||
|
config: "exclude: ['*.tmp', '.cache', 'build[']\n" +
|
||||||
|
"snapshots:\n" +
|
||||||
|
" home:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" + storage,
|
||||||
|
wantErr: `exclude[2]: "build[" is not a valid exclude pattern`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "snapshot",
|
||||||
|
config: "snapshots:\n" +
|
||||||
|
" home:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n" +
|
||||||
|
" exclude: ['/a/**/x[']\n" + storage,
|
||||||
|
wantErr: `snapshots.home.exclude[0]: "/a/**/x[" is not a valid exclude pattern`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(path, []byte(tt.config), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = config.Load(path)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("Load() returned nil, want an error containing %q", tt.wantErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||||
|
t.Fatalf("Load() error = %q, want it to contain %q", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// yamlMergeTag is the tag YAML gives a merge key (<<), which adds the keys
|
||||||
|
// of the map it names to the map it sits in.
|
||||||
|
const yamlMergeTag = "!!merge"
|
||||||
|
|
||||||
|
// EnvSection is the top-level key of a map of environment variables that
|
||||||
|
// smartconfig sets while it loads the config. It is not a vaultik setting,
|
||||||
|
// so its keys are not checked.
|
||||||
|
const EnvSection = "env"
|
||||||
|
|
||||||
|
var (
|
||||||
|
errUnknownKey = errors.New("unknown config key")
|
||||||
|
errAnchorContainsItself = errors.New("anchor contains itself")
|
||||||
|
)
|
||||||
|
|
||||||
|
// nodeAndType is a node of a parsed config and the setting type it is
|
||||||
|
// checked against.
|
||||||
|
type nodeAndType struct {
|
||||||
|
node *yaml.Node
|
||||||
|
typ reflect.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// SettingType returns the type of the setting that the dotted key names in
|
||||||
|
// Config, following the fields' yaml tags, as for s3.bucket or
|
||||||
|
// snapshots.home.exclude.0. A snapshot name or a list index may be any
|
||||||
|
// word. It returns an unknown key error when no setting has that key.
|
||||||
|
func SettingType(keys []string) (reflect.Type, error) {
|
||||||
|
typ := reflect.TypeFor[Config]()
|
||||||
|
|
||||||
|
for _, key := range keys {
|
||||||
|
switch {
|
||||||
|
case typ.Kind() == reflect.Map || typ.Kind() == reflect.Slice:
|
||||||
|
typ = typ.Elem()
|
||||||
|
case typ.Kind() == reflect.Struct:
|
||||||
|
field, ok := yamlField(typ, key)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("%w %q", errUnknownKey, strings.Join(keys, "."))
|
||||||
|
}
|
||||||
|
|
||||||
|
typ = field.Type
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w %q", errUnknownKey, strings.Join(keys, "."))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return typ, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// yamlField returns the field of struct type typ whose yaml tag names key.
|
||||||
|
func yamlField(typ reflect.Type, key string) (reflect.StructField, bool) {
|
||||||
|
for field := range typ.Fields() {
|
||||||
|
name, _, _ := strings.Cut(field.Tag.Get("yaml"), ",")
|
||||||
|
if name == key && name != "-" {
|
||||||
|
return field, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return reflect.StructField{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkKeys returns an error naming the first key in node, a parsed config
|
||||||
|
// or part of one at the dotted path, that no setting in typ has. The error
|
||||||
|
// gives the key's line in the file, when it has one. A value of the wrong
|
||||||
|
// type is left for the YAML decoder to report. following holds the aliases
|
||||||
|
// the walk is inside. Meeting one of them again means its anchor contains
|
||||||
|
// itself, which is an error. checked holds each anchored node the walk has
|
||||||
|
// checked completely, with the type it was checked against. An alias to
|
||||||
|
// that node is not followed again for that type.
|
||||||
|
func checkKeys(node *yaml.Node, typ reflect.Type, path string,
|
||||||
|
following map[*yaml.Node]bool, checked map[nodeAndType]bool,
|
||||||
|
) error {
|
||||||
|
switch node.Kind {
|
||||||
|
case yaml.DocumentNode:
|
||||||
|
for _, child := range node.Content {
|
||||||
|
err := checkKeys(child, typ, path, following, checked)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.AliasNode:
|
||||||
|
if following[node] {
|
||||||
|
return fmt.Errorf("%w: %q on line %d",
|
||||||
|
errAnchorContainsItself, node.Value, node.Line)
|
||||||
|
}
|
||||||
|
|
||||||
|
target := nodeAndType{node.Alias, typ}
|
||||||
|
if checked[target] {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
following[node] = true
|
||||||
|
defer delete(following, node)
|
||||||
|
|
||||||
|
err := checkKeys(node.Alias, typ, path, following, checked)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
checked[target] = true
|
||||||
|
case yaml.SequenceNode:
|
||||||
|
if typ.Kind() != reflect.Slice {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, child := range node.Content {
|
||||||
|
err := checkKeys(child, typ.Elem(), joinKey(path, strconv.Itoa(i)),
|
||||||
|
following, checked)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.MappingNode:
|
||||||
|
return checkMappingKeys(node, typ, path, following, checked)
|
||||||
|
case yaml.ScalarNode:
|
||||||
|
// A scalar has no keys.
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkFilledConfig checks data, the config after smartconfig has filled in
|
||||||
|
// its ${...} references: its keys with checkKeys, then its size settings
|
||||||
|
// with checkSizes. A key that a reference brings in is not in the file, and
|
||||||
|
// the copy that Encode makes has no line numbers.
|
||||||
|
func checkFilledConfig(data map[string]any) error {
|
||||||
|
var filled yaml.Node
|
||||||
|
|
||||||
|
err := filled.Encode(data)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal config data: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = checkKeys(&filled, reflect.TypeFor[Config](), "",
|
||||||
|
map[*yaml.Node]bool{}, map[nodeAndType]bool{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return checkSizes(&filled, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkMappingKeys is checkKeys for a map.
|
||||||
|
func checkMappingKeys(node *yaml.Node, typ reflect.Type, path string,
|
||||||
|
following map[*yaml.Node]bool, checked map[nodeAndType]bool,
|
||||||
|
) error {
|
||||||
|
for i := 0; i+1 < len(node.Content); i += 2 {
|
||||||
|
key, value := node.Content[i], node.Content[i+1]
|
||||||
|
|
||||||
|
if key.Tag == yamlMergeTag {
|
||||||
|
// The value is one map or a list of maps.
|
||||||
|
merged := []*yaml.Node{value}
|
||||||
|
if value.Kind == yaml.SequenceNode {
|
||||||
|
merged = value.Content
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, m := range merged {
|
||||||
|
err := checkKeys(m, typ, path, following, checked)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
keyPath := joinKey(path, key.Value)
|
||||||
|
if keyPath == EnvSection {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var valueType reflect.Type
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case typ.Kind() == reflect.Map:
|
||||||
|
valueType = typ.Elem()
|
||||||
|
case typ.Kind() == reflect.Struct:
|
||||||
|
field, ok := yamlField(typ, key.Value)
|
||||||
|
if !ok && key.Line == 0 {
|
||||||
|
// A key that a ${...} reference brought in has no line.
|
||||||
|
return fmt.Errorf("%w %q", errUnknownKey, keyPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("%w %q on line %d",
|
||||||
|
errUnknownKey, keyPath, key.Line)
|
||||||
|
}
|
||||||
|
|
||||||
|
valueType = field.Type
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := checkKeys(value, valueType, keyPath, following, checked)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// joinKey appends key to the dotted path.
|
||||||
|
func joinKey(path, key string) string {
|
||||||
|
if path == "" {
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
|
||||||
|
return path + "." + key
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package config //nolint:testpackage // checks the unexported errUnknownKey
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// keysTestConfig loads; each case below adds one line to it.
|
||||||
|
const keysTestConfig = "storage_url: file:///tmp/vaultik-test-storage\n" +
|
||||||
|
"s3:\n" +
|
||||||
|
" region: us-east-1\n" +
|
||||||
|
"snapshots:\n" +
|
||||||
|
" test:\n" +
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n"
|
||||||
|
|
||||||
|
// TestParseRefusesUnknownKey checks that a key no setting has, at any
|
||||||
|
// depth, fails the parse with an error naming the key and its line. A key
|
||||||
|
// that a ${...} reference brings in is not in the file, so its error gives
|
||||||
|
// no line.
|
||||||
|
func TestParseRefusesUnknownKey(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
snapshotPath := filepath.Join(t.TempDir(), "snapshot.yml")
|
||||||
|
|
||||||
|
err := os.WriteFile(snapshotPath, []byte("other:\n"+
|
||||||
|
" paths: [/tmp/vaultik-test-source]\n"+
|
||||||
|
" exlude: [/tmp/cache]\n"), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write snapshot: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
yaml string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"top level", keysTestConfig + "compression_lvl: 9\n",
|
||||||
|
`unknown config key "compression_lvl" on line 7`},
|
||||||
|
{"in a snapshot", keysTestConfig + " exlude: [/tmp/cache]\n",
|
||||||
|
`unknown config key "snapshots.test.exlude" on line 7`},
|
||||||
|
{"in s3", strings.Replace(keysTestConfig, " region:",
|
||||||
|
" bukcet: b\n region:", 1),
|
||||||
|
`unknown config key "s3.bukcet" on line 3`},
|
||||||
|
{"from a reference",
|
||||||
|
keysTestConfig + " other: ${YAML:" + snapshotPath + ":other}\n",
|
||||||
|
`unknown config key "snapshots.other.exlude"`},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
_, err := Parse([]byte(tt.yaml))
|
||||||
|
if !errors.Is(err, errUnknownKey) {
|
||||||
|
t.Fatalf("Parse() error = %v, want errUnknownKey", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err.Error() != tt.want {
|
||||||
|
t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseRefusesAnchorThatContainsItself checks that a YAML merge key (<<)
|
||||||
|
// naming the anchor of the map it sits in fails the parse with an error.
|
||||||
|
func TestParseRefusesAnchorThatContainsItself(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
data := strings.Replace(keysTestConfig, " test:", " test: &test", 1) +
|
||||||
|
" <<: *test\n"
|
||||||
|
|
||||||
|
_, err := Parse([]byte(data))
|
||||||
|
if !errors.Is(err, errAnchorContainsItself) {
|
||||||
|
t.Fatalf("Parse() error = %v, want errAnchorContainsItself", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
want := `anchor contains itself: "test" on line 7`
|
||||||
|
if err.Error() != want {
|
||||||
|
t.Errorf("Parse() error = %q, want %q", err.Error(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseRefusesExcessiveAliasing checks that Parse returns an error for
|
||||||
|
// a file whose merge keys (<<) fan out. Each of eight snapshots merges the
|
||||||
|
// one before it ten times. A key check that followed every alias would walk
|
||||||
|
// the first snapshot over 10^8 times and run past the package's test
|
||||||
|
// timeout.
|
||||||
|
func TestParseRefusesExcessiveAliasing(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const snapshots, merges = 8, 10
|
||||||
|
|
||||||
|
var data strings.Builder
|
||||||
|
|
||||||
|
data.WriteString(strings.Replace(keysTestConfig, " test:", " test: &s0", 1))
|
||||||
|
|
||||||
|
for i := 1; i <= snapshots; i++ {
|
||||||
|
aliases := slices.Repeat([]string{"*s" + strconv.Itoa(i-1)}, merges)
|
||||||
|
fmt.Fprintf(&data, " s%d: &s%d\n <<: [%s]\n",
|
||||||
|
i, i, strings.Join(aliases, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := Parse([]byte(data.String()))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Parse() returned no error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseAcceptsKnownKeys checks that a config with a ${...} reference
|
||||||
|
// and a YAML merge key (<<) still parses.
|
||||||
|
func TestParseAcceptsKnownKeys(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
levelPath := filepath.Join(t.TempDir(), "level")
|
||||||
|
|
||||||
|
err := os.WriteFile(levelPath, []byte("9"), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write level: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
data := strings.Replace(keysTestConfig, " test:", " test: &test", 1) +
|
||||||
|
" other:\n" +
|
||||||
|
" <<: *test\n" +
|
||||||
|
" exclude: [/tmp/vaultik-test-source/cache]\n" +
|
||||||
|
"compression_level: ${FILE:" + levelPath + "}\n"
|
||||||
|
|
||||||
|
cfg, err := Parse([]byte(data))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Parse() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.CompressionLevel != 9 {
|
||||||
|
t.Errorf("compression_level = %d, want 9", cfg.CompressionLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
other := cfg.Snapshots["other"]
|
||||||
|
if len(other.Paths) != 1 || len(other.Exclude) != 1 {
|
||||||
|
t.Errorf("snapshot other = %+v, want the paths of test and one exclude",
|
||||||
|
other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseAcceptsEnvSection checks that a config with a top-level env
|
||||||
|
// section still parses. smartconfig sets the environment variables it
|
||||||
|
// lists, so its keys are not settings.
|
||||||
|
func TestParseAcceptsEnvSection(t *testing.T) {
|
||||||
|
const name = "VAULTIK_TEST_ENV_SECTION"
|
||||||
|
|
||||||
|
// Parse sets the variable; t.Setenv restores it after the test.
|
||||||
|
t.Setenv(name, "")
|
||||||
|
|
||||||
|
_, err := Parse([]byte(keysTestConfig + "env:\n " + name + ": set\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Parse() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+77
-11
@@ -4,13 +4,20 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"reflect"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/dustin/go-humanize"
|
"github.com/dustin/go-humanize"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errSizeType = errors.New("size must be a number or string")
|
errSizeType = errors.New("size must be a number or string")
|
||||||
errSizeTooLarge = errors.New("size exceeds maximum supported value")
|
errSizeTooLarge = errors.New("size exceeds maximum supported value")
|
||||||
|
errNotASize = errors.New(
|
||||||
|
"is not a size; use a number of bytes or a unit such as 10MB")
|
||||||
)
|
)
|
||||||
|
|
||||||
// Size represents a byte size that can be specified in configuration files.
|
// Size represents a byte size that can be specified in configuration files.
|
||||||
@@ -32,6 +39,15 @@ func (s *Size) UnmarshalYAML(unmarshal func(any) error) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A number too large for an int64 decodes as a float64. Its text can be
|
||||||
|
// 1e+20, which is not a size string.
|
||||||
|
var floatVal float64
|
||||||
|
|
||||||
|
err = unmarshal(&floatVal)
|
||||||
|
if err == nil && floatVal > math.MaxInt64 {
|
||||||
|
return errSizeTooLarge
|
||||||
|
}
|
||||||
|
|
||||||
// Try to unmarshal as string
|
// Try to unmarshal as string
|
||||||
var strVal string
|
var strVal string
|
||||||
|
|
||||||
@@ -40,17 +56,66 @@ func (s *Size) UnmarshalYAML(unmarshal func(any) error) error {
|
|||||||
return errSizeType
|
return errSizeType
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the string using go-humanize
|
size, err := ParseSize(strVal)
|
||||||
bytes, err := humanize.ParseBytes(strVal)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid size format: %w", err)
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if bytes > math.MaxInt64 {
|
*s = size
|
||||||
return fmt.Errorf("%w: %s", errSizeTooLarge, strVal)
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkSizes returns an error naming the first size setting in node whose
|
||||||
|
// value is not a size. node is the config, or the part of it at the dotted
|
||||||
|
// keys, after smartconfig has filled in its ${...} references.
|
||||||
|
func checkSizes(node *yaml.Node, keys []string) error {
|
||||||
|
typ, err := SettingType(keys)
|
||||||
|
if err != nil {
|
||||||
|
// Unknown keys are refused before this check, so keys is in one of
|
||||||
|
// two places. The env section holds no settings. A value of the
|
||||||
|
// wrong shape, such as a map given for hostname or inside exclude,
|
||||||
|
// is reported later by the YAML decoder.
|
||||||
|
return nil //nolint:nilerr // not an error here
|
||||||
}
|
}
|
||||||
|
|
||||||
*s = Size(bytes)
|
if typ == reflect.TypeFor[Size]() {
|
||||||
|
var size Size
|
||||||
|
|
||||||
|
err = node.Decode(&size)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s: %w", strings.Join(keys, "."), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch node.Kind {
|
||||||
|
case yaml.DocumentNode:
|
||||||
|
for _, child := range node.Content {
|
||||||
|
err = checkSizes(child, keys)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.MappingNode:
|
||||||
|
for i := 0; i+1 < len(node.Content); i += 2 {
|
||||||
|
err = checkSizes(node.Content[i+1],
|
||||||
|
slices.Concat(keys, []string{node.Content[i].Value}))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.SequenceNode:
|
||||||
|
for i, child := range node.Content {
|
||||||
|
err = checkSizes(child, slices.Concat(keys, []string{strconv.Itoa(i)}))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case yaml.ScalarNode, yaml.AliasNode:
|
||||||
|
// A scalar holds no settings, and the filled config has no aliases.
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -70,16 +135,17 @@ func (s Size) String() string {
|
|||||||
return humanize.Bytes(uint64(s))
|
return humanize.Bytes(uint64(s))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseSize parses a size string into a Size value
|
// ParseSize parses a size string, such as "10MB", into a Size value. An
|
||||||
|
// error quotes s.
|
||||||
func ParseSize(s string) (Size, error) {
|
func ParseSize(s string) (Size, error) {
|
||||||
bytes, err := humanize.ParseBytes(s)
|
bytes, err := humanize.ParseBigBytes(s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("invalid size format: %w", err)
|
return 0, fmt.Errorf("%q %w", s, errNotASize)
|
||||||
}
|
}
|
||||||
|
|
||||||
if bytes > math.MaxInt64 {
|
if !bytes.IsInt64() {
|
||||||
return 0, fmt.Errorf("%w: %s", errSizeTooLarge, s)
|
return 0, fmt.Errorf("%w: %s", errSizeTooLarge, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
return Size(bytes), nil
|
return Size(bytes.Int64()), nil
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package config //nolint:testpackage // checks errNotASize and errSizeTooLarge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestParseRefusesValueThatIsNotASize checks that a size setting whose
|
||||||
|
// value is not a size fails the parse with an error naming the setting and
|
||||||
|
// quoting the value, also when a ${...} reference fills the value in.
|
||||||
|
func TestParseRefusesValueThatIsNotASize(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
sizePath := filepath.Join(t.TempDir(), "size")
|
||||||
|
|
||||||
|
err := os.WriteFile(sizePath, []byte("lots"), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write size: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
yaml string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"chunk_size", keysTestConfig + "chunk_size: banana\n",
|
||||||
|
`chunk_size: "banana" is not a size; ` +
|
||||||
|
"use a number of bytes or a unit such as 10MB"},
|
||||||
|
{"blob_size_limit", keysTestConfig + "blob_size_limit: 10XB\n",
|
||||||
|
`blob_size_limit: "10XB" is not a size; ` +
|
||||||
|
"use a number of bytes or a unit such as 10MB"},
|
||||||
|
{"s3.part_size", strings.Replace(keysTestConfig, " region:",
|
||||||
|
" part_size: big\n region:", 1),
|
||||||
|
`s3.part_size: "big" is not a size; ` +
|
||||||
|
"use a number of bytes or a unit such as 10MB"},
|
||||||
|
{"from a reference",
|
||||||
|
keysTestConfig + "chunk_size: ${FILE:" + sizePath + "}\n",
|
||||||
|
`chunk_size: "lots" is not a size; ` +
|
||||||
|
"use a number of bytes or a unit such as 10MB"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
_, err := Parse([]byte(tt.yaml))
|
||||||
|
if !errors.Is(err, errNotASize) {
|
||||||
|
t.Fatalf("Parse() error = %v, want errNotASize", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err.Error() != tt.want {
|
||||||
|
t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseRefusesSizeTooLarge checks that a size setting whose value is
|
||||||
|
// too large for a size fails the parse with an error naming the setting.
|
||||||
|
// YAML reads the second value as a float.
|
||||||
|
func TestParseRefusesSizeTooLarge(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
value string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"100EB", "chunk_size: size exceeds maximum supported value: 100EB"},
|
||||||
|
{"99999999999999999999",
|
||||||
|
"chunk_size: size exceeds maximum supported value"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.value, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
_, err := Parse([]byte(keysTestConfig + "chunk_size: " + tt.value + "\n"))
|
||||||
|
if !errors.Is(err, errSizeTooLarge) {
|
||||||
|
t.Fatalf("Parse() error = %v, want errSizeTooLarge", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err.Error() != tt.want {
|
||||||
|
t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseAcceptsSizes checks that size settings given as a number of
|
||||||
|
// bytes, as a unit, and through a ${...} reference still parse.
|
||||||
|
func TestParseAcceptsSizes(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
sizePath := filepath.Join(t.TempDir(), "size")
|
||||||
|
|
||||||
|
err := os.WriteFile(sizePath, []byte("20MB"), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write size: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
data := strings.Replace(keysTestConfig, " region:",
|
||||||
|
" part_size: 6000000\n region:", 1) +
|
||||||
|
"chunk_size: ${FILE:" + sizePath + "}\n" +
|
||||||
|
"blob_size_limit: 1GB\n"
|
||||||
|
|
||||||
|
cfg, err := Parse([]byte(data))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Parse() unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.ChunkSize != 20_000_000 || cfg.BlobSizeLimit != 1_000_000_000 ||
|
||||||
|
cfg.S3.PartSize != 6_000_000 {
|
||||||
|
t.Errorf("chunk_size, blob_size_limit, s3.part_size = %d, %d, %d, "+
|
||||||
|
"want 20000000, 1000000000, 6000000",
|
||||||
|
cfg.ChunkSize, cfg.BlobSizeLimit, cfg.S3.PartSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,12 +58,7 @@ func (r *BlobChunkRepository) GetByBlobID(
|
|||||||
return nil, fmt.Errorf("querying blob chunks: %w", err)
|
return nil, fmt.Errorf("querying blob chunks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var blobChunks []*BlobChunk
|
var blobChunks []*BlobChunk
|
||||||
|
|
||||||
|
|||||||
@@ -83,12 +83,7 @@ func (r *BlobRepository) GetAll(ctx context.Context) (map[string]*Blob, error) {
|
|||||||
return nil, fmt.Errorf("querying blobs: %w", err)
|
return nil, fmt.Errorf("querying blobs: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
out := make(map[string]*Blob)
|
out := make(map[string]*Blob)
|
||||||
|
|
||||||
@@ -159,13 +154,16 @@ func (r *BlobRepository) UpdateFinished(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateUploaded marks a blob as uploaded
|
// UpdateUploaded marks a blob as uploaded and records the size of the
|
||||||
|
// stored object as its compressed size. That size can differ from the
|
||||||
|
// local copy's when an identical blob was already stored with another
|
||||||
|
// compression level or other recipients.
|
||||||
func (r *BlobRepository) UpdateUploaded(
|
func (r *BlobRepository) UpdateUploaded(
|
||||||
ctx context.Context, tx *sql.Tx, id string,
|
ctx context.Context, tx *sql.Tx, id string, storedSize int64,
|
||||||
) error {
|
) error {
|
||||||
query := `
|
query := `
|
||||||
UPDATE blobs
|
UPDATE blobs
|
||||||
SET uploaded_ts = ?
|
SET uploaded_ts = ?, compressed_size = ?
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
`
|
`
|
||||||
|
|
||||||
@@ -173,9 +171,9 @@ func (r *BlobRepository) UpdateUploaded(
|
|||||||
|
|
||||||
var err error
|
var err error
|
||||||
if tx != nil {
|
if tx != nil {
|
||||||
_, err = tx.ExecContext(ctx, query, now, id)
|
_, err = tx.ExecContext(ctx, query, now, storedSize, id)
|
||||||
} else {
|
} else {
|
||||||
_, err = r.db.ExecWithLog(ctx, query, now, id)
|
_, err = r.db.ExecWithLog(ctx, query, now, storedSize, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -122,8 +122,8 @@ func TestBlobRepositoryUpdates(t *testing.T) {
|
|||||||
t.Errorf("expected compressed size 500, got %d", updated.CompressedSize)
|
t.Errorf("expected compressed size 500, got %d", updated.CompressedSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test UpdateUploaded
|
// Test UpdateUploaded, with a stored object larger than the local copy
|
||||||
err = repo.UpdateUploaded(ctx, nil, blob.ID.String())
|
err = repo.UpdateUploaded(ctx, nil, blob.ID.String(), 600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("failed to update blob as uploaded: %v", err)
|
t.Fatalf("failed to update blob as uploaded: %v", err)
|
||||||
}
|
}
|
||||||
@@ -141,6 +141,10 @@ func TestBlobRepositoryUpdates(t *testing.T) {
|
|||||||
if uploaded.UploadedTS.Before(now.Add(-1 * time.Second)) {
|
if uploaded.UploadedTS.Before(now.Add(-1 * time.Second)) {
|
||||||
t.Error("uploaded timestamp should be around test time")
|
t.Error("uploaded timestamp should be around test time")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if uploaded.CompressedSize != 600 {
|
||||||
|
t.Errorf("expected the stored size 600, got %d", uploaded.CompressedSize)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBlobRepositoryDuplicate(t *testing.T) {
|
func TestBlobRepositoryDuplicate(t *testing.T) {
|
||||||
|
|||||||
@@ -61,12 +61,7 @@ func (r *ChunkFileRepository) GetByChunkHash(
|
|||||||
return nil, fmt.Errorf("querying chunk files: %w", err)
|
return nil, fmt.Errorf("querying chunk files: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return r.scanChunkFiles(rows)
|
return r.scanChunkFiles(rows)
|
||||||
}
|
}
|
||||||
@@ -87,12 +82,7 @@ func (r *ChunkFileRepository) GetByFilePath(
|
|||||||
return nil, fmt.Errorf("querying chunk files: %w", err)
|
return nil, fmt.Errorf("querying chunk files: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return r.scanChunkFiles(rows)
|
return r.scanChunkFiles(rows)
|
||||||
}
|
}
|
||||||
@@ -112,12 +102,7 @@ func (r *ChunkFileRepository) GetByFileID(
|
|||||||
return nil, fmt.Errorf("querying chunk files: %w", err)
|
return nil, fmt.Errorf("querying chunk files: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return r.scanChunkFiles(rows)
|
return r.scanChunkFiles(rows)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,12 +107,7 @@ func (r *ChunkRepository) GetByHashes(
|
|||||||
return nil, fmt.Errorf("querying chunks: %w", err)
|
return nil, fmt.Errorf("querying chunks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var chunks []*Chunk
|
var chunks []*Chunk
|
||||||
|
|
||||||
@@ -152,12 +147,7 @@ func (r *ChunkRepository) ListUnpacked(
|
|||||||
return nil, fmt.Errorf("querying unpacked chunks: %w", err)
|
return nil, fmt.Errorf("querying unpacked chunks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var chunks []*Chunk
|
var chunks []*Chunk
|
||||||
|
|
||||||
|
|||||||
@@ -38,12 +38,7 @@ func (r *ChunkRepository) list(ctx context.Context, query string) ([]*Chunk, err
|
|||||||
return nil, fmt.Errorf("querying chunks: %w", err)
|
return nil, fmt.Errorf("querying chunks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var chunks []*Chunk
|
var chunks []*Chunk
|
||||||
|
|
||||||
|
|||||||
@@ -219,7 +219,8 @@ func retryOpen(ctx context.Context, path string) (*DB, error) {
|
|||||||
|
|
||||||
// errUntrustedSnapshotSchema is returned when a downloaded snapshot
|
// errUntrustedSnapshotSchema is returned when a downloaded snapshot
|
||||||
// database carries schema objects the real schema never defines, or is
|
// database carries schema objects the real schema never defines, or is
|
||||||
// missing a table the restore and deep-verify queries read.
|
// missing a table the restore, deep-verify and `snapshot files` queries
|
||||||
|
// read.
|
||||||
var errUntrustedSnapshotSchema = errors.New(
|
var errUntrustedSnapshotSchema = errors.New(
|
||||||
"downloaded snapshot database has an untrusted schema")
|
"downloaded snapshot database has an untrusted schema")
|
||||||
|
|
||||||
@@ -241,12 +242,12 @@ func snapshotReadOnlyDSN(path string) string {
|
|||||||
|
|
||||||
// OpenReadOnly opens an already-materialized SQLite file for read-only
|
// OpenReadOnly opens an already-materialized SQLite file for read-only
|
||||||
// querying of a snapshot database downloaded from the store, used by
|
// querying of a snapshot database downloaded from the store, used by
|
||||||
// restore and deep verify. Unlike New it never applies schema migrations
|
// restore, deep verify and `snapshot files`. Unlike New it never applies
|
||||||
// and never writes: the connection is opened read-only with query_only
|
// schema migrations and never writes: the connection is opened read-only
|
||||||
// and trusted_schema=OFF. It refuses any file whose schema carries a
|
// with query_only and trusted_schema=OFF. It refuses any file whose schema
|
||||||
// trigger, view or virtual table, or lacks an expected table, so a forged
|
// carries a trigger, view or virtual table, or lacks an expected table, so
|
||||||
// file cannot redefine what the restore queries return. The caller owns
|
// a forged file cannot redefine what the restore queries return. The
|
||||||
// the file and must remove it.
|
// caller owns the file and must remove it.
|
||||||
func OpenReadOnly(ctx context.Context, path string) (*DB, error) {
|
func OpenReadOnly(ctx context.Context, path string) (*DB, error) {
|
||||||
conn, err := sql.Open("sqlite", snapshotReadOnlyDSN(path))
|
conn, err := sql.Open("sqlite", snapshotReadOnlyDSN(path))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -276,9 +277,9 @@ func OpenReadOnly(ctx context.Context, path string) (*DB, error) {
|
|||||||
// the plain table set the real schema defines. Any trigger, view or
|
// the plain table set the real schema defines. Any trigger, view or
|
||||||
// virtual table, or a missing expected table, fails the open.
|
// virtual table, or a missing expected table, fails the open.
|
||||||
func verifySnapshotSchema(ctx context.Context, conn *sql.DB) error {
|
func verifySnapshotSchema(ctx context.Context, conn *sql.DB) error {
|
||||||
// expectedSnapshotTables are the tables the restore and deep-verify
|
// expectedSnapshotTables are the tables the restore, deep-verify and
|
||||||
// queries read. A downloaded database missing any of them is not a
|
// `snapshot files` queries read. A downloaded database missing any of
|
||||||
// genuine snapshot database and is refused.
|
// them is not a genuine snapshot database and is refused.
|
||||||
expectedSnapshotTables := []string{
|
expectedSnapshotTables := []string{
|
||||||
"blob_chunks",
|
"blob_chunks",
|
||||||
"blobs",
|
"blobs",
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
package database
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Fatalf prints an error message to stderr and exits with status 1
|
|
||||||
func Fatalf(format string, args ...any) {
|
|
||||||
fmt.Fprintf(os.Stderr, "FATAL: "+format+"\n", args...)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
@@ -62,12 +62,7 @@ func (r *FileChunkRepository) GetByPath(
|
|||||||
return nil, fmt.Errorf("querying file chunks: %w", err)
|
return nil, fmt.Errorf("querying file chunks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return r.scanFileChunks(rows)
|
return r.scanFileChunks(rows)
|
||||||
}
|
}
|
||||||
@@ -88,12 +83,7 @@ func (r *FileChunkRepository) GetByFileID(
|
|||||||
return nil, fmt.Errorf("querying file chunks: %w", err)
|
return nil, fmt.Errorf("querying file chunks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return r.scanFileChunks(rows)
|
return r.scanFileChunks(rows)
|
||||||
}
|
}
|
||||||
@@ -117,12 +107,7 @@ func (r *FileChunkRepository) GetByPathTx(
|
|||||||
return nil, fmt.Errorf("querying file chunks: %w", err)
|
return nil, fmt.Errorf("querying file chunks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
fileChunks, err := r.scanFileChunks(rows)
|
fileChunks, err := r.scanFileChunks(rows)
|
||||||
LogSQL("GetByPathTx", "Complete", path, "count", len(fileChunks))
|
LogSQL("GetByPathTx", "Complete", path, "count", len(fileChunks))
|
||||||
|
|||||||
+80
-47
@@ -33,11 +33,13 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err
|
|||||||
}
|
}
|
||||||
|
|
||||||
query := `
|
query := `
|
||||||
INSERT INTO files (id, path, source_path, mtime, size, mode, uid, gid, link_target)
|
INSERT INTO files
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
(id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(path) DO UPDATE SET
|
ON CONFLICT(path) DO UPDATE SET
|
||||||
source_path = excluded.source_path,
|
source_path = excluded.source_path,
|
||||||
mtime = excluded.mtime,
|
mtime = excluded.mtime,
|
||||||
|
mtime_nsec = excluded.mtime_nsec,
|
||||||
size = excluded.size,
|
size = excluded.size,
|
||||||
mode = excluded.mode,
|
mode = excluded.mode,
|
||||||
uid = excluded.uid,
|
uid = excluded.uid,
|
||||||
@@ -54,16 +56,19 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err
|
|||||||
if tx != nil {
|
if tx != nil {
|
||||||
LogSQL("Execute", query,
|
LogSQL("Execute", query,
|
||||||
file.ID.String(), file.Path.String(), file.SourcePath.String(),
|
file.ID.String(), file.Path.String(), file.SourcePath.String(),
|
||||||
file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID,
|
file.MTime.Unix(), file.MTime.Nanosecond(),
|
||||||
|
file.Size, file.Mode, file.UID, file.GID,
|
||||||
file.LinkTarget.String())
|
file.LinkTarget.String())
|
||||||
err = tx.QueryRowContext(ctx, query,
|
err = tx.QueryRowContext(ctx, query,
|
||||||
file.ID.String(), file.Path.String(), file.SourcePath.String(),
|
file.ID.String(), file.Path.String(), file.SourcePath.String(),
|
||||||
file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID,
|
file.MTime.Unix(), file.MTime.Nanosecond(),
|
||||||
|
file.Size, file.Mode, file.UID, file.GID,
|
||||||
file.LinkTarget.String()).Scan(&idStr)
|
file.LinkTarget.String()).Scan(&idStr)
|
||||||
} else {
|
} else {
|
||||||
err = r.db.QueryRowWithLog(ctx, query,
|
err = r.db.QueryRowWithLog(ctx, query,
|
||||||
file.ID.String(), file.Path.String(), file.SourcePath.String(),
|
file.ID.String(), file.Path.String(), file.SourcePath.String(),
|
||||||
file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID,
|
file.MTime.Unix(), file.MTime.Nanosecond(),
|
||||||
|
file.Size, file.Mode, file.UID, file.GID,
|
||||||
file.LinkTarget.String()).Scan(&idStr)
|
file.LinkTarget.String()).Scan(&idStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,7 +89,7 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err
|
|||||||
// in the index.
|
// in the index.
|
||||||
func (r *FileRepository) GetByPath(ctx context.Context, path string) (*File, error) {
|
func (r *FileRepository) GetByPath(ctx context.Context, path string) (*File, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target
|
SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target
|
||||||
FROM files
|
FROM files
|
||||||
WHERE path = ?
|
WHERE path = ?
|
||||||
`
|
`
|
||||||
@@ -104,7 +109,7 @@ func (r *FileRepository) GetByPath(ctx context.Context, path string) (*File, err
|
|||||||
// GetByID retrieves a file by its UUID
|
// GetByID retrieves a file by its UUID
|
||||||
func (r *FileRepository) GetByID(ctx context.Context, id types.FileID) (*File, error) {
|
func (r *FileRepository) GetByID(ctx context.Context, id types.FileID) (*File, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target
|
SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target
|
||||||
FROM files
|
FROM files
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
`
|
`
|
||||||
@@ -127,7 +132,7 @@ func (r *FileRepository) GetByPathTx(
|
|||||||
ctx context.Context, tx *sql.Tx, path string,
|
ctx context.Context, tx *sql.Tx, path string,
|
||||||
) (*File, error) {
|
) (*File, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target
|
SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target
|
||||||
FROM files
|
FROM files
|
||||||
WHERE path = ?
|
WHERE path = ?
|
||||||
`
|
`
|
||||||
@@ -158,23 +163,19 @@ func (r *FileRepository) ListModifiedSince(
|
|||||||
ctx context.Context, since time.Time,
|
ctx context.Context, since time.Time,
|
||||||
) ([]*File, error) {
|
) ([]*File, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target
|
SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target
|
||||||
FROM files
|
FROM files
|
||||||
WHERE mtime >= ?
|
WHERE (mtime, mtime_nsec) >= (?, ?)
|
||||||
ORDER BY path
|
ORDER BY path
|
||||||
`
|
`
|
||||||
|
|
||||||
rows, err := r.db.conn.QueryContext(ctx, query, since.Unix())
|
rows, err := r.db.conn.QueryContext(ctx, query,
|
||||||
|
since.Unix(), since.Nanosecond())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("querying files: %w", err)
|
return nil, fmt.Errorf("querying files: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var files []*File
|
var files []*File
|
||||||
|
|
||||||
@@ -228,29 +229,68 @@ func (r *FileRepository) DeleteByID(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListByPrefix returns all files whose path starts with prefix, ordered by
|
// ListUnderPath returns the file at path and every file beneath it,
|
||||||
// path.
|
// ordered by path. Paths are compared case-sensitively, and a trailing
|
||||||
func (r *FileRepository) ListByPrefix(
|
// slash on path is ignored, so "/" lists every file.
|
||||||
ctx context.Context, prefix string,
|
func (r *FileRepository) ListUnderPath(
|
||||||
|
ctx context.Context, path string,
|
||||||
) ([]*File, error) {
|
) ([]*File, error) {
|
||||||
|
path = strings.TrimRight(path, "/")
|
||||||
|
dirPrefix := path + "/"
|
||||||
|
|
||||||
|
// LIKE would ignore ASCII case and treat _ and % in path as wildcards.
|
||||||
query := `
|
query := `
|
||||||
SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target
|
SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target
|
||||||
FROM files
|
FROM files
|
||||||
WHERE path LIKE ? || '%'
|
WHERE path = ? OR substr(path, 1, length(?)) = ?
|
||||||
ORDER BY path
|
ORDER BY path
|
||||||
`
|
`
|
||||||
|
|
||||||
rows, err := r.db.conn.QueryContext(ctx, query, prefix)
|
rows, err := r.db.conn.QueryContext(ctx, query, path, dirPrefix, dirPrefix)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("querying files: %w", err)
|
return nil, fmt.Errorf("querying files: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
|
var files []*File
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
file, err := r.scanFileRows(rows)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Fatalf("failed to close rows: %v", err)
|
return nil, fmt.Errorf("scanning file: %w", err)
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
|
files = append(files, file)
|
||||||
|
}
|
||||||
|
|
||||||
|
return files, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListUnderPathInSnapshot returns the files that ListUnderPath returns
|
||||||
|
// for path and that the snapshot lists, in no particular order.
|
||||||
|
func (r *FileRepository) ListUnderPathInSnapshot(
|
||||||
|
ctx context.Context, path, snapshotID string,
|
||||||
|
) ([]*File, error) {
|
||||||
|
path = strings.TrimRight(path, "/")
|
||||||
|
dirPrefix := path + "/"
|
||||||
|
|
||||||
|
query := `
|
||||||
|
SELECT f.id, f.path, f.source_path, f.mtime, f.mtime_nsec, f.size,
|
||||||
|
f.mode, f.uid, f.gid, f.link_target
|
||||||
|
FROM files f
|
||||||
|
JOIN snapshot_files sf ON sf.file_id = f.id
|
||||||
|
WHERE sf.snapshot_id = ?
|
||||||
|
AND (f.path = ? OR substr(f.path, 1, length(?)) = ?)
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := r.db.conn.QueryContext(ctx, query,
|
||||||
|
snapshotID, path, dirPrefix, dirPrefix)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("querying files: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() { _ = rows.Close() }()
|
||||||
|
|
||||||
var files []*File
|
var files []*File
|
||||||
|
|
||||||
@@ -293,12 +333,7 @@ func (r *FileRepository) ListIDsWithChunksNotInUploadedBlobs(
|
|||||||
return nil, fmt.Errorf("querying files: %w", err)
|
return nil, fmt.Errorf("querying files: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var ids []types.FileID
|
var ids []types.FileID
|
||||||
|
|
||||||
@@ -319,7 +354,7 @@ func (r *FileRepository) ListIDsWithChunksNotInUploadedBlobs(
|
|||||||
// ListAll returns all files in the database
|
// ListAll returns all files in the database
|
||||||
func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) {
|
func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target
|
SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target
|
||||||
FROM files
|
FROM files
|
||||||
ORDER BY path
|
ORDER BY path
|
||||||
`
|
`
|
||||||
@@ -329,12 +364,7 @@ func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) {
|
|||||||
return nil, fmt.Errorf("querying files: %w", err)
|
return nil, fmt.Errorf("querying files: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var files []*File
|
var files []*File
|
||||||
|
|
||||||
@@ -360,7 +390,7 @@ func (r *FileRepository) CreateBatch(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Each files row binds this many SQL variables.
|
// Each files row binds this many SQL variables.
|
||||||
const fileCols = 9
|
const fileCols = 10
|
||||||
|
|
||||||
// Batch at 100 rows to be safe with SQLite's variable limit.
|
// Batch at 100 rows to be safe with SQLite's variable limit.
|
||||||
const batchSize = 100
|
const batchSize = 100
|
||||||
@@ -371,7 +401,7 @@ func (r *FileRepository) CreateBatch(
|
|||||||
batch := files[i:end]
|
batch := files[i:end]
|
||||||
|
|
||||||
query := `INSERT INTO files
|
query := `INSERT INTO files
|
||||||
(id, path, source_path, mtime, size, mode, uid, gid, link_target)
|
(id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target)
|
||||||
VALUES `
|
VALUES `
|
||||||
|
|
||||||
args := make([]any, 0, len(batch)*fileCols)
|
args := make([]any, 0, len(batch)*fileCols)
|
||||||
@@ -383,11 +413,12 @@ func (r *FileRepository) CreateBatch(
|
|||||||
querySb325.WriteString(", ")
|
querySb325.WriteString(", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
querySb325.WriteString("(?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
querySb325.WriteString("(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
||||||
|
|
||||||
args = append(args,
|
args = append(args,
|
||||||
f.ID.String(), f.Path.String(), f.SourcePath.String(),
|
f.ID.String(), f.Path.String(), f.SourcePath.String(),
|
||||||
f.MTime.Unix(), f.Size, f.Mode, f.UID, f.GID,
|
f.MTime.Unix(), f.MTime.Nanosecond(),
|
||||||
|
f.Size, f.Mode, f.UID, f.GID,
|
||||||
f.LinkTarget.String())
|
f.LinkTarget.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -396,6 +427,7 @@ func (r *FileRepository) CreateBatch(
|
|||||||
query += ` ON CONFLICT(path) DO UPDATE SET
|
query += ` ON CONFLICT(path) DO UPDATE SET
|
||||||
source_path = excluded.source_path,
|
source_path = excluded.source_path,
|
||||||
mtime = excluded.mtime,
|
mtime = excluded.mtime,
|
||||||
|
mtime_nsec = excluded.mtime_nsec,
|
||||||
size = excluded.size,
|
size = excluded.size,
|
||||||
mode = excluded.mode,
|
mode = excluded.mode,
|
||||||
uid = excluded.uid,
|
uid = excluded.uid,
|
||||||
@@ -455,7 +487,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) {
|
|||||||
var (
|
var (
|
||||||
file File
|
file File
|
||||||
idStr, pathStr, sourcePathStr string
|
idStr, pathStr, sourcePathStr string
|
||||||
mtimeUnix int64
|
mtimeUnix, mtimeNsec int64
|
||||||
linkTarget sql.NullString
|
linkTarget sql.NullString
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -464,6 +496,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) {
|
|||||||
&pathStr,
|
&pathStr,
|
||||||
&sourcePathStr,
|
&sourcePathStr,
|
||||||
&mtimeUnix,
|
&mtimeUnix,
|
||||||
|
&mtimeNsec,
|
||||||
&file.Size,
|
&file.Size,
|
||||||
&file.Mode,
|
&file.Mode,
|
||||||
&file.UID,
|
&file.UID,
|
||||||
@@ -482,7 +515,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) {
|
|||||||
file.Path = types.FilePath(pathStr)
|
file.Path = types.FilePath(pathStr)
|
||||||
file.SourcePath = types.SourcePath(sourcePathStr)
|
file.SourcePath = types.SourcePath(sourcePathStr)
|
||||||
|
|
||||||
file.MTime = time.Unix(mtimeUnix, 0).UTC()
|
file.MTime = time.Unix(mtimeUnix, mtimeNsec).UTC()
|
||||||
if linkTarget.Valid {
|
if linkTarget.Valid {
|
||||||
file.LinkTarget = types.FilePath(linkTarget.String)
|
file.LinkTarget = types.FilePath(linkTarget.String)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
|
"slices"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"sneak.berlin/go/vaultik/internal/database"
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
// errTestRollback is the sentinel returned from transaction bodies to
|
// errTestRollback is the sentinel returned from transaction bodies to
|
||||||
@@ -134,6 +136,141 @@ func TestFileRepositoryListDelete(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFileRepositoryListUnderPath(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
repo := database.NewFileRepository(db)
|
||||||
|
|
||||||
|
const (
|
||||||
|
docDir = "/home/u/doc"
|
||||||
|
docFile = "/home/u/doc/a.txt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// In path order, so the root case can expect all of them as listed.
|
||||||
|
paths := []string{
|
||||||
|
"/home/u/50%/x.txt",
|
||||||
|
"/home/u/50percent/y.txt",
|
||||||
|
"/home/u/DOC/c.txt",
|
||||||
|
"/home/u/a_b/x.txt",
|
||||||
|
"/home/u/axb/y.txt",
|
||||||
|
docDir,
|
||||||
|
"/home/u/doc.txt.bak",
|
||||||
|
docFile,
|
||||||
|
"/home/u/doc/sub/b.txt",
|
||||||
|
"/home/u/doc2/b.txt",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, path := range paths {
|
||||||
|
err := repo.Create(ctx, nil, &database.File{
|
||||||
|
Path: types.FilePath(path),
|
||||||
|
MTime: time.Now().Truncate(time.Second),
|
||||||
|
Mode: 0644,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
docTree := []string{docDir, docFile, "/home/u/doc/sub/b.txt"}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{"directory", docDir, docTree},
|
||||||
|
{"directory with trailing slash", docDir + "/", docTree},
|
||||||
|
{"directory differing only in case", "/home/u/DOC",
|
||||||
|
[]string{"/home/u/DOC/c.txt"}},
|
||||||
|
{"file", docFile, []string{docFile}},
|
||||||
|
{"underscore is literal", "/home/u/a_b",
|
||||||
|
[]string{"/home/u/a_b/x.txt"}},
|
||||||
|
{"percent is literal", "/home/u/50%",
|
||||||
|
[]string{"/home/u/50%/x.txt"}},
|
||||||
|
{"root", "/", paths},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
files, err := repo.ListUnderPath(ctx, tt.path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: failed to list files: %v", tt.name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := make([]string, 0, len(files))
|
||||||
|
for _, f := range files {
|
||||||
|
got = append(got, f.Path.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slices.Equal(got, tt.want) {
|
||||||
|
t.Errorf("%s: listing %q got %q, want %q",
|
||||||
|
tt.name, tt.path, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListUnderPathInSnapshot leaves out files outside path and files the
|
||||||
|
// snapshot does not list, though another snapshot lists them.
|
||||||
|
func TestFileRepositoryListUnderPathInSnapshot(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
files := database.NewFileRepository(db)
|
||||||
|
snapshots := database.NewSnapshotRepository(db)
|
||||||
|
|
||||||
|
listed := map[string][]string{
|
||||||
|
"one": {"/src/a.txt", "/src2/c.txt"},
|
||||||
|
"two": {"/src/b.txt"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for snapshotID, paths := range listed {
|
||||||
|
err := snapshots.Create(ctx, nil, &database.Snapshot{
|
||||||
|
ID: types.SnapshotID(snapshotID),
|
||||||
|
Hostname: "host",
|
||||||
|
StartedAt: time.Now(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create snapshot %s: %v", snapshotID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, path := range paths {
|
||||||
|
err := files.Create(ctx, nil, &database.File{
|
||||||
|
Path: types.FilePath(path),
|
||||||
|
MTime: time.Now().Truncate(time.Second),
|
||||||
|
Mode: 0644,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create %s: %v", path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = snapshots.AddFile(ctx, nil, snapshotID, path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to add %s to %s: %v", path, snapshotID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
found, err := files.ListUnderPathInSnapshot(ctx, "/src", "one")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to list files: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := make([]string, 0, len(found))
|
||||||
|
for _, f := range found {
|
||||||
|
got = append(got, f.Path.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slices.Equal(got, []string{"/src/a.txt"}) {
|
||||||
|
t.Errorf("got %q, want only /src/a.txt", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestFileRepositorySymlink(t *testing.T) {
|
func TestFileRepositorySymlink(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -174,6 +311,115 @@ func TestFileRepositorySymlink(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// An mtime after 2262 or before 1678 does not fit in int64 nanoseconds
|
||||||
|
// since the epoch, and must still come back from the database unchanged.
|
||||||
|
func TestFileRepositoryMTimeOutsideInt64NanosecondRange(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
repo := database.NewFileRepository(db)
|
||||||
|
|
||||||
|
mtimes := []time.Time{
|
||||||
|
time.Date(2300, time.January, 1, 0, 0, 0, 123456789, time.UTC),
|
||||||
|
time.Date(1601, time.January, 1, 0, 0, 0, 987654321, time.UTC),
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, mtime := range mtimes {
|
||||||
|
created := &database.File{
|
||||||
|
Path: types.FilePath("/created-" + mtime.Format(time.RFC3339Nano)),
|
||||||
|
MTime: mtime,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := repo.Create(ctx, nil, created)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
batched := &database.File{
|
||||||
|
ID: types.NewFileID(),
|
||||||
|
Path: types.FilePath("/batched-" + mtime.Format(time.RFC3339Nano)),
|
||||||
|
MTime: mtime,
|
||||||
|
}
|
||||||
|
|
||||||
|
err = repo.CreateBatch(ctx, nil, []*database.File{batched})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to batch create file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, path := range []types.FilePath{created.Path, batched.Path} {
|
||||||
|
retrieved, err := repo.GetByPath(ctx, path.String())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to get file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !retrieved.MTime.Equal(mtime) {
|
||||||
|
t.Errorf("%s: mtime got %v, want %v",
|
||||||
|
path, retrieved.MTime, mtime)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A file already in the index and rewritten within the same second must get
|
||||||
|
// its new nanoseconds stored, through both Create and CreateBatch.
|
||||||
|
func TestFileRepositoryUpsertMTimeInSameSecond(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
repo := database.NewFileRepository(db)
|
||||||
|
|
||||||
|
indexed := time.Date(2026, time.October, 7, 12, 0, 0, 100000000, time.UTC)
|
||||||
|
rewritten := indexed.Add(800 * time.Millisecond)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
upsert func(file *database.File) error
|
||||||
|
}{
|
||||||
|
{"Create", func(file *database.File) error {
|
||||||
|
return repo.Create(ctx, nil, file)
|
||||||
|
}},
|
||||||
|
{"CreateBatch", func(file *database.File) error {
|
||||||
|
return repo.CreateBatch(ctx, nil, []*database.File{file})
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
file := &database.File{
|
||||||
|
ID: types.NewFileID(),
|
||||||
|
Path: types.FilePath("/" + tt.name),
|
||||||
|
MTime: indexed,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := tt.upsert(file)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: failed to create file: %v", tt.name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
file.MTime = rewritten
|
||||||
|
|
||||||
|
err = tt.upsert(file)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: failed to update file: %v", tt.name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
retrieved, err := repo.GetByPath(ctx, file.Path.String())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: failed to get file: %v", tt.name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !retrieved.MTime.Equal(rewritten) {
|
||||||
|
t.Errorf("%s: mtime got %v, want %v",
|
||||||
|
tt.name, retrieved.MTime, rewritten)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestFileRepositoryTransaction(t *testing.T) {
|
func TestFileRepositoryTransaction(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -14,8 +14,7 @@ type File struct {
|
|||||||
ID types.FileID // UUID primary key
|
ID types.FileID // UUID primary key
|
||||||
Path types.FilePath // Absolute path of the file
|
Path types.FilePath // Absolute path of the file
|
||||||
|
|
||||||
// SourcePath is the source directory this file came from (used for
|
// SourcePath is the source directory this file came from.
|
||||||
// restore path stripping).
|
|
||||||
SourcePath types.SourcePath
|
SourcePath types.SourcePath
|
||||||
MTime time.Time
|
MTime time.Time
|
||||||
Size int64
|
Size int64
|
||||||
@@ -99,8 +98,8 @@ type Snapshot struct {
|
|||||||
StartedAt time.Time
|
StartedAt time.Time
|
||||||
CompletedAt *time.Time // nil if still in progress
|
CompletedAt *time.Time // nil if still in progress
|
||||||
FileCount int64
|
FileCount int64
|
||||||
ChunkCount int64
|
ChunkCount int64 // Chunks this snapshot stored that were not stored before
|
||||||
BlobCount int64
|
BlobCount int64 // Blobs this snapshot created
|
||||||
TotalSize int64 // Total size of all referenced files
|
TotalSize int64 // Total size of all referenced files
|
||||||
|
|
||||||
// BlobSize is the total size of all referenced blobs (compressed and
|
// BlobSize is the total size of all referenced blobs (compressed and
|
||||||
|
|||||||
@@ -20,6 +20,17 @@ const indexDirPerm = 0o700
|
|||||||
// backed-up path and chunk hash and must stay private.
|
// backed-up path and chunk hash and must stay private.
|
||||||
const indexFilePerm = 0o600
|
const indexFilePerm = 0o600
|
||||||
|
|
||||||
|
// IndexFiles returns the path of the index at indexPath and the paths of
|
||||||
|
// the side files SQLite keeps beside it while it writes.
|
||||||
|
func IndexFiles(indexPath string) []string {
|
||||||
|
return []string{
|
||||||
|
indexPath,
|
||||||
|
indexPath + "-wal",
|
||||||
|
indexPath + "-shm",
|
||||||
|
indexPath + "-journal",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ensureIndexFileMode makes the index file owner-only before the SQLite
|
// ensureIndexFileMode makes the index file owner-only before the SQLite
|
||||||
// driver opens it: it creates the file 0600 if absent, or chmods an existing
|
// driver opens it: it creates the file 0600 if absent, or chmods an existing
|
||||||
// one to 0600. Doing this first matters because SQLite creates its -wal and
|
// one to 0600. Doing this first matters because SQLite creates its -wal and
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package database
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -60,22 +61,24 @@ func (r *Repositories) WithTx(ctx context.Context, fn TxFunc) error {
|
|||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if p := recover(); p != nil {
|
if p := recover(); p != nil {
|
||||||
rollbackErr := tx.Rollback()
|
// The panic is the failure to report, so a rollback error
|
||||||
if rollbackErr != nil {
|
// is dropped.
|
||||||
Fatalf("failed to rollback transaction: %v", rollbackErr)
|
_ = tx.Rollback()
|
||||||
}
|
|
||||||
|
|
||||||
panic(p)
|
panic(p)
|
||||||
} else if err != nil {
|
|
||||||
rollbackErr := tx.Rollback()
|
|
||||||
if rollbackErr != nil {
|
|
||||||
Fatalf("failed to rollback transaction: %v", rollbackErr)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
err = fn(ctx, tx)
|
err = fn(ctx, tx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// Once ctx is cancelled, database/sql rolls the transaction
|
||||||
|
// back itself and Rollback returns sql.ErrTxDone.
|
||||||
|
rollbackErr := tx.Rollback()
|
||||||
|
if rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) {
|
||||||
|
return fmt.Errorf("%w; rolling back transaction: %w",
|
||||||
|
err, rollbackErr)
|
||||||
|
}
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,22 +106,24 @@ func (r *Repositories) WithReadTx(ctx context.Context, fn TxFunc) error {
|
|||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if p := recover(); p != nil {
|
if p := recover(); p != nil {
|
||||||
rollbackErr := tx.Rollback()
|
// The panic is the failure to report, so a rollback error
|
||||||
if rollbackErr != nil {
|
// is dropped.
|
||||||
Fatalf("failed to rollback transaction: %v", rollbackErr)
|
_ = tx.Rollback()
|
||||||
}
|
|
||||||
|
|
||||||
panic(p)
|
panic(p)
|
||||||
} else if err != nil {
|
|
||||||
rollbackErr := tx.Rollback()
|
|
||||||
if rollbackErr != nil {
|
|
||||||
Fatalf("failed to rollback transaction: %v", rollbackErr)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
err = fn(ctx, tx)
|
err = fn(ctx, tx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// Once ctx is cancelled, database/sql rolls the transaction
|
||||||
|
// back itself and Rollback returns sql.ErrTxDone.
|
||||||
|
rollbackErr := tx.Rollback()
|
||||||
|
if rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) {
|
||||||
|
return fmt.Errorf("%w; rolling back transaction: %w",
|
||||||
|
err, rollbackErr)
|
||||||
|
}
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -235,6 +236,125 @@ func TestRepositoriesTransactionRollback(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// When the context is cancelled during the body, database/sql rolls the
|
||||||
|
// transaction back itself, so WithTx's own rollback finds it already
|
||||||
|
// done. WithTx must return the body's error alone, without that rollback.
|
||||||
|
func TestRepositoriesTransactionContextCancelled(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
file := &database.File{
|
||||||
|
Path: "/test/cancelled_file.txt",
|
||||||
|
MTime: time.Now().Truncate(time.Second),
|
||||||
|
Size: 1024,
|
||||||
|
Mode: 0644,
|
||||||
|
UID: 1000,
|
||||||
|
GID: 1000,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := repos.Files.Create(ctx, tx, file)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
// database/sql rolls back from a goroutine of its own; wait
|
||||||
|
// until it has, so the test does not depend on that race.
|
||||||
|
for {
|
||||||
|
_, err = tx.ExecContext(context.WithoutCancel(ctx), "SELECT 1")
|
||||||
|
if errors.Is(err, sql.ErrTxDone) {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("expected context.Canceled, got: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, sql.ErrTxDone) {
|
||||||
|
t.Fatalf("the already-done rollback was reported: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := repos.Files.GetByPath(
|
||||||
|
context.Background(), "/test/cancelled_file.txt",
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("error checking for file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if file != nil {
|
||||||
|
t.Error("file should not exist after the cancelled transaction")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A body that ends the transaction itself with ROLLBACK makes WithTx's
|
||||||
|
// own rollback fail. WithTx must return that failure together with the
|
||||||
|
// body's error.
|
||||||
|
func TestRepositoriesTransactionRollbackFails(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
_, err := tx.ExecContext(ctx, "ROLLBACK")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return errIntentionalRollback
|
||||||
|
})
|
||||||
|
if !errors.Is(err, errIntentionalRollback) {
|
||||||
|
t.Fatalf("expected the body's error, got: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(err.Error(), "rolling back transaction") {
|
||||||
|
t.Errorf("expected the failed rollback in the error, got: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// When the body ends the transaction itself with ROLLBACK and then
|
||||||
|
// panics, WithTx's own rollback fails; the panic must still reach the
|
||||||
|
// caller.
|
||||||
|
func TestRepositoriesTransactionPanicRollbackFails(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if recover() == nil {
|
||||||
|
t.Error("expected the body's panic to reach the caller")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
_ = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
_, err := tx.ExecContext(ctx, "ROLLBACK")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
panic(errIntentionalRollback)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func TestRepositoriesReadTransaction(t *testing.T) {
|
func TestRepositoriesReadTransaction(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -291,3 +411,41 @@ func TestRepositoriesReadTransaction(t *testing.T) {
|
|||||||
t.Error("expected to retrieve file in read transaction")
|
t.Error("expected to retrieve file in read transaction")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// When the context is cancelled during a read transaction's body,
|
||||||
|
// database/sql rolls the transaction back itself, so WithReadTx's own
|
||||||
|
// rollback finds it already done. WithReadTx must return the body's error
|
||||||
|
// alone, without that rollback.
|
||||||
|
func TestRepositoriesReadTransactionContextCancelled(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
err := repos.WithReadTx(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
// database/sql rolls back from a goroutine of its own; wait
|
||||||
|
// until it has, so the test does not depend on that race.
|
||||||
|
for {
|
||||||
|
_, err := tx.ExecContext(context.WithoutCancel(ctx), "SELECT 1")
|
||||||
|
if errors.Is(err, sql.ErrTxDone) {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("expected context.Canceled, got: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, sql.ErrTxDone) {
|
||||||
|
t.Fatalf("the already-done rollback was reported: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -824,7 +824,7 @@ func TestTransactionIsolation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verify the file was not created (transaction rolled back)
|
// Verify the file was not created (transaction rolled back)
|
||||||
files, err := repos.Files.ListByPrefix(ctx, "/tx-test")
|
files, err := repos.Files.ListUnderPath(ctx, "/tx-test.txt")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -916,7 +916,7 @@ func TestConcurrentOrphanedCleanup(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verify correct files were deleted
|
// Verify correct files were deleted
|
||||||
files, err := repos.Files.ListByPrefix(ctx, "/concurrent-")
|
files, err := repos.Files.ListAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ func TestOrphanedFileCleanupDebug(t *testing.T) {
|
|||||||
t.Logf("Files count after cleanup: %d", count)
|
t.Logf("Files count after cleanup: %d", count)
|
||||||
|
|
||||||
// List remaining files
|
// List remaining files
|
||||||
files, err := repos.Files.ListByPrefix(ctx, "/")
|
files, err := repos.Files.ListUnderPath(ctx, "/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package database
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"database/sql"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -367,7 +368,7 @@ func verifyBlobNullUploadTS(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// createLargeDatasetFiles creates fileCount files and adds every other
|
// createLargeDatasetFiles creates fileCount files and adds every other
|
||||||
// one to the snapshot.
|
// one to the snapshot, in one transaction as a backup writes them.
|
||||||
func createLargeDatasetFiles(
|
func createLargeDatasetFiles(
|
||||||
t *testing.T,
|
t *testing.T,
|
||||||
repos *Repositories,
|
repos *Repositories,
|
||||||
@@ -376,31 +377,38 @@ func createLargeDatasetFiles(
|
|||||||
) {
|
) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|
||||||
for i := range fileCount {
|
err := repos.WithTx(context.Background(),
|
||||||
file := &File{
|
func(ctx context.Context, tx *sql.Tx) error {
|
||||||
Path: types.FilePath(fmt.Sprintf("/large/file%05d.txt", i)),
|
for i := range fileCount {
|
||||||
MTime: time.Now(),
|
file := &File{
|
||||||
Size: int64(i * 1024),
|
Path: types.FilePath(fmt.Sprintf("/large/file%05d.txt", i)),
|
||||||
Mode: 0644,
|
MTime: time.Now(),
|
||||||
UID: uint32(1000 + (i % 10)),
|
Size: int64(i * 1024),
|
||||||
GID: uint32(1000 + (i % 10)),
|
Mode: 0644,
|
||||||
}
|
UID: uint32(1000 + (i % 10)),
|
||||||
|
GID: uint32(1000 + (i % 10)),
|
||||||
|
}
|
||||||
|
|
||||||
err := repos.Files.Create(ctx, nil, file)
|
err := repos.Files.Create(ctx, tx, file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("failed to create file %d: %v", i, err)
|
return fmt.Errorf("creating file %d: %w", i, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add half to snapshot
|
// Add half to snapshot
|
||||||
if i%2 == 0 {
|
if i%2 == 0 {
|
||||||
err = repos.Snapshots.AddFileByID(ctx, nil, snapshotID, file.ID)
|
err = repos.Snapshots.AddFileByID(ctx, tx, snapshotID, file.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Logf("Created %d files in %v", fileCount, time.Since(start))
|
t.Logf("Created %d files in %v", fileCount, time.Since(start))
|
||||||
@@ -442,12 +450,12 @@ func TestLargeDatasets(t *testing.T) {
|
|||||||
createLargeDatasetFiles(t, repos, snapshot.ID.String(), fileCount)
|
createLargeDatasetFiles(t, repos, snapshot.ID.String(), fileCount)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Test ListByPrefix performance
|
// Test ListUnderPath performance
|
||||||
//nolint:paralleltest // phases share one database and are order-dependent
|
//nolint:paralleltest // phases share one database and are order-dependent
|
||||||
t.Run("list by prefix performance", func(t *testing.T) {
|
t.Run("list under path performance", func(t *testing.T) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|
||||||
files, err := repos.Files.ListByPrefix(ctx, "/large/")
|
files, err := repos.Files.ListUnderPath(ctx, "/large/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -472,7 +480,7 @@ func TestLargeDatasets(t *testing.T) {
|
|||||||
t.Logf("Cleaned up orphaned files in %v", time.Since(start))
|
t.Logf("Cleaned up orphaned files in %v", time.Since(start))
|
||||||
|
|
||||||
// Verify correct number remain
|
// Verify correct number remain
|
||||||
files, err := repos.Files.ListByPrefix(ctx, "/large/")
|
files, err := repos.Files.ListUnderPath(ctx, "/large/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -606,8 +614,7 @@ func TestTimezoneHandling(t *testing.T) {
|
|||||||
t.Skip("timezone not available")
|
t.Skip("timezone not available")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use Truncate to remove sub-second precision since we store as Unix timestamps
|
nyTime := time.Now().In(loc)
|
||||||
nyTime := time.Now().In(loc).Truncate(time.Second)
|
|
||||||
file := &File{
|
file := &File{
|
||||||
Path: "/timezone-test.txt",
|
Path: "/timezone-test.txt",
|
||||||
MTime: nyTime,
|
MTime: nyTime,
|
||||||
|
|||||||
@@ -5,8 +5,9 @@
|
|||||||
CREATE TABLE IF NOT EXISTS files (
|
CREATE TABLE IF NOT EXISTS files (
|
||||||
id TEXT PRIMARY KEY, -- UUID
|
id TEXT PRIMARY KEY, -- UUID
|
||||||
path TEXT NOT NULL UNIQUE,
|
path TEXT NOT NULL UNIQUE,
|
||||||
source_path TEXT NOT NULL DEFAULT '', -- The source directory this file came from (for restore path stripping)
|
source_path TEXT NOT NULL DEFAULT '', -- The source directory this file came from
|
||||||
mtime INTEGER NOT NULL,
|
mtime INTEGER NOT NULL, -- whole seconds since the Unix epoch
|
||||||
|
mtime_nsec INTEGER NOT NULL, -- nanoseconds within that second, 0 to 999999999
|
||||||
size INTEGER NOT NULL,
|
size INTEGER NOT NULL,
|
||||||
mode INTEGER NOT NULL,
|
mode INTEGER NOT NULL,
|
||||||
uid INTEGER NOT NULL,
|
uid INTEGER NOT NULL,
|
||||||
@@ -85,8 +86,10 @@ CREATE TABLE IF NOT EXISTS snapshots (
|
|||||||
completed_at INTEGER,
|
completed_at INTEGER,
|
||||||
file_count INTEGER NOT NULL DEFAULT 0,
|
file_count INTEGER NOT NULL DEFAULT 0,
|
||||||
chunk_count INTEGER NOT NULL DEFAULT 0,
|
chunk_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
new_chunk_size INTEGER NOT NULL DEFAULT 0,
|
||||||
blob_count INTEGER NOT NULL DEFAULT 0,
|
blob_count INTEGER NOT NULL DEFAULT 0,
|
||||||
total_size INTEGER NOT NULL DEFAULT 0,
|
total_size INTEGER NOT NULL DEFAULT 0,
|
||||||
|
uncompressed_chunk_size INTEGER NOT NULL DEFAULT 0,
|
||||||
blob_size INTEGER NOT NULL DEFAULT 0,
|
blob_size INTEGER NOT NULL DEFAULT 0,
|
||||||
blob_uncompressed_size INTEGER NOT NULL DEFAULT 0,
|
blob_uncompressed_size INTEGER NOT NULL DEFAULT 0,
|
||||||
compression_ratio REAL NOT NULL DEFAULT 1.0,
|
compression_ratio REAL NOT NULL DEFAULT 1.0,
|
||||||
@@ -120,6 +123,16 @@ CREATE TABLE IF NOT EXISTS snapshot_blobs (
|
|||||||
-- Index for efficient blob lookups (used in orphan detection)
|
-- Index for efficient blob lookups (used in orphan detection)
|
||||||
CREATE INDEX IF NOT EXISTS idx_snapshot_blobs_blob_id ON snapshot_blobs(blob_id);
|
CREATE INDEX IF NOT EXISTS idx_snapshot_blobs_blob_id ON snapshot_blobs(blob_id);
|
||||||
|
|
||||||
|
-- Snapshot mount points table: the directories at or below a configured
|
||||||
|
-- path that the snapshot's backup found on a different filesystem from
|
||||||
|
-- their parent directory, as a mount point is, and found an entry in
|
||||||
|
CREATE TABLE IF NOT EXISTS snapshot_mount_points (
|
||||||
|
snapshot_id TEXT NOT NULL,
|
||||||
|
path TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (snapshot_id, path),
|
||||||
|
FOREIGN KEY (snapshot_id) REFERENCES snapshots(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
-- Uploads table: tracks blob upload metrics
|
-- Uploads table: tracks blob upload metrics
|
||||||
CREATE TABLE IF NOT EXISTS uploads (
|
CREATE TABLE IF NOT EXISTS uploads (
|
||||||
blob_hash TEXT PRIMARY KEY,
|
blob_hash TEXT PRIMARY KEY,
|
||||||
|
|||||||
+144
-97
@@ -24,7 +24,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// SnapshotRepository provides access to the snapshots table and its
|
// SnapshotRepository provides access to the snapshots table and its
|
||||||
// snapshot_files / snapshot_blobs association tables.
|
// snapshot_files / snapshot_blobs association tables, and to the mount
|
||||||
|
// points each snapshot's backup found (snapshot_mount_points).
|
||||||
type SnapshotRepository struct {
|
type SnapshotRepository struct {
|
||||||
db *DB
|
db *DB
|
||||||
}
|
}
|
||||||
@@ -120,14 +121,20 @@ func (r *SnapshotRepository) UpdateCounts(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateExtendedStats updates extended statistics for a snapshot
|
// UpdateExtendedStats updates extended statistics for a snapshot. It also
|
||||||
|
// records the total plaintext size of the distinct chunks the snapshot's
|
||||||
|
// files reference. Only the snapshot's own backup can take that total: a
|
||||||
|
// file's row is shared by every snapshot that lists it, and a later
|
||||||
|
// backup of a changed file rewrites the row with the new chunks.
|
||||||
func (r *SnapshotRepository) UpdateExtendedStats(
|
func (r *SnapshotRepository) UpdateExtendedStats(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
tx *sql.Tx,
|
tx *sql.Tx,
|
||||||
snapshotID string,
|
snapshotID string,
|
||||||
blobUncompressedSize int64,
|
blobUncompressedSize int64,
|
||||||
compressionLevel int,
|
compressionLevel int,
|
||||||
|
uploadBytes int64,
|
||||||
uploadDurationMs int64,
|
uploadDurationMs int64,
|
||||||
|
newChunkSize int64,
|
||||||
) error {
|
) error {
|
||||||
compressionRatio, err := r.extendedCompressionRatio(
|
compressionRatio, err := r.extendedCompressionRatio(
|
||||||
ctx, tx, snapshotID, blobUncompressedSize,
|
ctx, tx, snapshotID, blobUncompressedSize,
|
||||||
@@ -141,19 +148,30 @@ func (r *SnapshotRepository) UpdateExtendedStats(
|
|||||||
SET blob_uncompressed_size = ?,
|
SET blob_uncompressed_size = ?,
|
||||||
compression_ratio = ?,
|
compression_ratio = ?,
|
||||||
compression_level = ?,
|
compression_level = ?,
|
||||||
upload_bytes = blob_size,
|
upload_bytes = ?,
|
||||||
upload_duration_ms = ?
|
upload_duration_ms = ?,
|
||||||
|
new_chunk_size = ?,
|
||||||
|
uncompressed_chunk_size = (
|
||||||
|
SELECT COALESCE(SUM(c.size), 0)
|
||||||
|
FROM (
|
||||||
|
SELECT DISTINCT fc.chunk_hash
|
||||||
|
FROM snapshot_files sf
|
||||||
|
JOIN file_chunks fc ON sf.file_id = fc.file_id
|
||||||
|
WHERE sf.snapshot_id = snapshots.id
|
||||||
|
) sc
|
||||||
|
JOIN chunks c ON sc.chunk_hash = c.chunk_hash
|
||||||
|
)
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
`
|
`
|
||||||
|
|
||||||
if tx != nil {
|
if tx != nil {
|
||||||
_, err = tx.ExecContext(ctx, query,
|
_, err = tx.ExecContext(ctx, query,
|
||||||
blobUncompressedSize, compressionRatio, compressionLevel,
|
blobUncompressedSize, compressionRatio, compressionLevel,
|
||||||
uploadDurationMs, snapshotID)
|
uploadBytes, uploadDurationMs, newChunkSize, snapshotID)
|
||||||
} else {
|
} else {
|
||||||
_, err = r.db.ExecWithLog(ctx, query,
|
_, err = r.db.ExecWithLog(ctx, query,
|
||||||
blobUncompressedSize, compressionRatio, compressionLevel,
|
blobUncompressedSize, compressionRatio, compressionLevel,
|
||||||
uploadDurationMs, snapshotID)
|
uploadBytes, uploadDurationMs, newChunkSize, snapshotID)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -220,10 +238,11 @@ func (r *SnapshotRepository) GetByID(
|
|||||||
|
|
||||||
// GetOnlySnapshot returns the sole snapshot in an exported per-snapshot
|
// GetOnlySnapshot returns the sole snapshot in an exported per-snapshot
|
||||||
// metadata database. The backup path writes each snapshot's database with
|
// metadata database. The backup path writes each snapshot's database with
|
||||||
// exactly one snapshot row (see cleanSnapshotDB), so restore and deep
|
// exactly one snapshot row (see cleanSnapshotDB), so restore, deep verify
|
||||||
// verify expect exactly one. Zero rows return ErrNoSnapshotInDatabase and
|
// and `snapshot files` expect exactly one. Zero rows return
|
||||||
// more than one returns ErrMultipleSnapshotsInDatabase; callers treat
|
// ErrNoSnapshotInDatabase and more than one returns
|
||||||
// either as a failed identity check on the downloaded database.
|
// ErrMultipleSnapshotsInDatabase; callers treat either as a failed
|
||||||
|
// identity check on the downloaded database.
|
||||||
func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, error) {
|
func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT id, hostname, vaultik_version, vaultik_git_revision,
|
SELECT id, hostname, vaultik_version, vaultik_git_revision,
|
||||||
@@ -238,12 +257,7 @@ func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, er
|
|||||||
return nil, fmt.Errorf("querying snapshots: %w", err)
|
return nil, fmt.Errorf("querying snapshots: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
snapshots, err := r.scanSnapshotRows(rows)
|
snapshots, err := r.scanSnapshotRows(rows)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -278,12 +292,7 @@ func (r *SnapshotRepository) ListRecent(
|
|||||||
return nil, fmt.Errorf("querying snapshots: %w", err)
|
return nil, fmt.Errorf("querying snapshots: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return r.scanSnapshotRows(rows)
|
return r.scanSnapshotRows(rows)
|
||||||
}
|
}
|
||||||
@@ -493,32 +502,57 @@ func (r *SnapshotRepository) GetBlobHashes(
|
|||||||
ORDER BY sb.blob_hash
|
ORDER BY sb.blob_hash
|
||||||
`
|
`
|
||||||
|
|
||||||
rows, err := r.db.conn.QueryContext(ctx, query, snapshotID)
|
blobs, err := r.queryStrings(ctx, query, snapshotID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("querying blob hashes: %w", err)
|
return nil, fmt.Errorf("querying blob hashes: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
return blobs, nil
|
||||||
err := rows.Close()
|
}
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
var blobs []string
|
// AddMountPoint records dir as a directory that the backup of a snapshot
|
||||||
|
// found on a different filesystem from its parent directory, as a mount
|
||||||
|
// point is, using tx when non-nil.
|
||||||
|
func (r *SnapshotRepository) AddMountPoint(
|
||||||
|
ctx context.Context, tx *sql.Tx, snapshotID string, dir string,
|
||||||
|
) error {
|
||||||
|
query := `
|
||||||
|
INSERT OR IGNORE INTO snapshot_mount_points (snapshot_id, path)
|
||||||
|
VALUES (?, ?)
|
||||||
|
`
|
||||||
|
|
||||||
for rows.Next() {
|
var err error
|
||||||
var blobHash string
|
if tx != nil {
|
||||||
|
_, err = tx.ExecContext(ctx, query, snapshotID, dir)
|
||||||
err := rows.Scan(&blobHash)
|
} else {
|
||||||
if err != nil {
|
_, err = r.db.ExecWithLog(ctx, query, snapshotID, dir)
|
||||||
return nil, fmt.Errorf("scanning blob hash: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
blobs = append(blobs, blobHash)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return blobs, rows.Err()
|
if err != nil {
|
||||||
|
return fmt.Errorf("adding mount point to snapshot: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMountPoints returns the directories AddMountPoint recorded for a
|
||||||
|
// snapshot, sorted.
|
||||||
|
func (r *SnapshotRepository) GetMountPoints(
|
||||||
|
ctx context.Context, snapshotID string,
|
||||||
|
) ([]string, error) {
|
||||||
|
query := `
|
||||||
|
SELECT path
|
||||||
|
FROM snapshot_mount_points
|
||||||
|
WHERE snapshot_id = ?
|
||||||
|
ORDER BY path
|
||||||
|
`
|
||||||
|
|
||||||
|
dirs, err := r.queryStrings(ctx, query, snapshotID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("querying mount points: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return dirs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSnapshotTotalCompressedSize returns the total compressed size of all
|
// GetSnapshotTotalCompressedSize returns the total compressed size of all
|
||||||
@@ -543,71 +577,66 @@ func (r *SnapshotRepository) GetSnapshotTotalCompressedSize(
|
|||||||
return totalSize, nil
|
return totalSize, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSnapshotUncompressedChunkSize returns the sum of plaintext sizes of all unique
|
// GetSnapshotBlobSizes returns the total compressed and uncompressed sizes
|
||||||
// chunks referenced by a snapshot (via snapshot_files → file_chunks → chunks).
|
// of all blobs referenced by a snapshot.
|
||||||
|
func (r *SnapshotRepository) GetSnapshotBlobSizes(
|
||||||
|
ctx context.Context, snapshotID string,
|
||||||
|
) (int64, int64, error) {
|
||||||
|
query := `
|
||||||
|
SELECT COALESCE(SUM(b.compressed_size), 0),
|
||||||
|
COALESCE(SUM(b.uncompressed_size), 0)
|
||||||
|
FROM snapshot_blobs sb
|
||||||
|
JOIN blobs b ON sb.blob_hash = b.blob_hash
|
||||||
|
WHERE sb.snapshot_id = ?
|
||||||
|
`
|
||||||
|
|
||||||
|
var compressed, uncompressed int64
|
||||||
|
|
||||||
|
err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(
|
||||||
|
&compressed, &uncompressed)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, fmt.Errorf("querying snapshot blob sizes: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return compressed, uncompressed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSnapshotUncompressedChunkSize returns the total plaintext size of the
|
||||||
|
// distinct chunks the snapshot's files reference, as the snapshot's backup
|
||||||
|
// recorded it (see UpdateExtendedStats).
|
||||||
func (r *SnapshotRepository) GetSnapshotUncompressedChunkSize(
|
func (r *SnapshotRepository) GetSnapshotUncompressedChunkSize(
|
||||||
ctx context.Context, snapshotID string,
|
ctx context.Context, snapshotID string,
|
||||||
) (int64, error) {
|
) (int64, error) {
|
||||||
query := `
|
query := `SELECT uncompressed_chunk_size FROM snapshots WHERE id = ?`
|
||||||
SELECT COALESCE(SUM(c.size), 0)
|
|
||||||
FROM (
|
|
||||||
SELECT DISTINCT fc.chunk_hash
|
|
||||||
FROM snapshot_files sf
|
|
||||||
JOIN file_chunks fc ON sf.file_id = fc.file_id
|
|
||||||
WHERE sf.snapshot_id = ?
|
|
||||||
) sc
|
|
||||||
JOIN chunks c ON sc.chunk_hash = c.chunk_hash
|
|
||||||
`
|
|
||||||
|
|
||||||
var totalSize int64
|
var uncompressedChunkSize int64
|
||||||
|
|
||||||
err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&totalSize)
|
err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&uncompressedChunkSize)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("querying uncompressed chunk size: %w", err)
|
return 0, fmt.Errorf("querying uncompressed chunk size: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return totalSize, nil
|
return uncompressedChunkSize, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSnapshotNewChunkSize returns the sum of plaintext sizes of chunks that are
|
// GetSnapshotNewChunkSize returns the total plaintext size of the chunks the
|
||||||
// referenced by this snapshot but not by any earlier completed snapshot known to
|
// snapshot's backup stored that were not stored before, as the backup
|
||||||
// the local database. The result is the marginal uncompressed data this snapshot
|
// recorded it. It is not derived from the snapshot's files: a file's row is
|
||||||
// added to the dedup pool — i.e., the delta from prior snapshots.
|
// shared by every snapshot that lists it and is rewritten when the file
|
||||||
|
// changes, so it shows only the file's latest chunks.
|
||||||
func (r *SnapshotRepository) GetSnapshotNewChunkSize(
|
func (r *SnapshotRepository) GetSnapshotNewChunkSize(
|
||||||
ctx context.Context, snapshotID string,
|
ctx context.Context, snapshotID string,
|
||||||
) (int64, error) {
|
) (int64, error) {
|
||||||
query := `
|
query := `SELECT new_chunk_size FROM snapshots WHERE id = ?`
|
||||||
WITH this_snap_chunks AS (
|
|
||||||
SELECT DISTINCT fc.chunk_hash
|
|
||||||
FROM snapshot_files sf
|
|
||||||
JOIN file_chunks fc ON sf.file_id = fc.file_id
|
|
||||||
WHERE sf.snapshot_id = ?
|
|
||||||
),
|
|
||||||
prior_chunks AS (
|
|
||||||
SELECT DISTINCT fc.chunk_hash
|
|
||||||
FROM snapshots s
|
|
||||||
JOIN snapshot_files sf ON sf.snapshot_id = s.id
|
|
||||||
JOIN file_chunks fc ON fc.file_id = sf.file_id
|
|
||||||
WHERE s.completed_at IS NOT NULL
|
|
||||||
AND s.id != ?
|
|
||||||
AND s.started_at < (SELECT started_at FROM snapshots WHERE id = ?)
|
|
||||||
)
|
|
||||||
SELECT COALESCE(SUM(c.size), 0)
|
|
||||||
FROM chunks c
|
|
||||||
JOIN this_snap_chunks t ON c.chunk_hash = t.chunk_hash
|
|
||||||
WHERE c.chunk_hash NOT IN (SELECT chunk_hash FROM prior_chunks)
|
|
||||||
`
|
|
||||||
|
|
||||||
var totalSize int64
|
var newChunkSize int64
|
||||||
|
|
||||||
err := r.db.conn.QueryRowContext(
|
err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&newChunkSize)
|
||||||
ctx, query, snapshotID, snapshotID, snapshotID,
|
|
||||||
).Scan(&totalSize)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("querying new chunk size: %w", err)
|
return 0, fmt.Errorf("querying new chunk size: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return totalSize, nil
|
return newChunkSize, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetIncompleteSnapshots returns all snapshots that haven't been completed
|
// GetIncompleteSnapshots returns all snapshots that haven't been completed
|
||||||
@@ -628,12 +657,7 @@ func (r *SnapshotRepository) GetIncompleteSnapshots(
|
|||||||
return nil, fmt.Errorf("querying incomplete snapshots: %w", err)
|
return nil, fmt.Errorf("querying incomplete snapshots: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return r.scanSnapshotRows(rows)
|
return r.scanSnapshotRows(rows)
|
||||||
}
|
}
|
||||||
@@ -656,12 +680,7 @@ func (r *SnapshotRepository) GetIncompleteByHostname(
|
|||||||
return nil, fmt.Errorf("querying incomplete snapshots: %w", err)
|
return nil, fmt.Errorf("querying incomplete snapshots: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func() {
|
defer func() { _ = rows.Close() }()
|
||||||
err := rows.Close()
|
|
||||||
if err != nil {
|
|
||||||
Fatalf("failed to close rows: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Same column set as every other multi-row snapshot query, so the
|
// Same column set as every other multi-row snapshot query, so the
|
||||||
// shared scanner applies — including its timestamp normalization.
|
// shared scanner applies — including its timestamp normalization.
|
||||||
@@ -722,6 +741,34 @@ func (r *SnapshotRepository) DeleteSnapshotUploads(
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// queryStrings runs query, which selects one text column, and returns
|
||||||
|
// its values in the order of the rows.
|
||||||
|
func (r *SnapshotRepository) queryStrings(
|
||||||
|
ctx context.Context, query string, args ...any,
|
||||||
|
) ([]string, error) {
|
||||||
|
rows, err := r.db.conn.QueryContext(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() { _ = rows.Close() }()
|
||||||
|
|
||||||
|
var values []string
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var value string
|
||||||
|
|
||||||
|
err := rows.Scan(&value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
values = append(values, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
return values, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
// extendedCompressionRatio computes the compression ratio for a snapshot
|
// extendedCompressionRatio computes the compression ratio for a snapshot
|
||||||
// from its stored blob_size and the given uncompressed size. Returns 1.0
|
// from its stored blob_size and the given uncompressed size. Returns 1.0
|
||||||
// when the uncompressed size is zero.
|
// when the uncompressed size is zero.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"slices"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -145,6 +146,65 @@ func TestSnapshotRepositoryUpdateCounts(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetSnapshotBlobSizes totals the blobs the snapshot references, and only
|
||||||
|
// those.
|
||||||
|
func TestSnapshotRepositoryGetSnapshotBlobSizes(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
snapshot := &database.Snapshot{
|
||||||
|
ID: "2024-01-03T12:00:00Z",
|
||||||
|
Hostname: testHostname,
|
||||||
|
VaultikVersion: testVersion,
|
||||||
|
StartedAt: time.Now().Truncate(time.Second),
|
||||||
|
}
|
||||||
|
|
||||||
|
err := repos.Snapshots.Create(ctx, nil, snapshot)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create snapshot: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
blobs := []*database.Blob{
|
||||||
|
{Hash: "referenced-1", CompressedSize: 10, UncompressedSize: 100},
|
||||||
|
{Hash: "referenced-2", CompressedSize: 20, UncompressedSize: 200},
|
||||||
|
{Hash: "unreferenced", CompressedSize: 40, UncompressedSize: 400},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, blob := range blobs {
|
||||||
|
blob.ID = types.NewBlobID()
|
||||||
|
blob.CreatedTS = time.Now().Truncate(time.Second)
|
||||||
|
|
||||||
|
err = repos.Blobs.Create(ctx, nil, blob)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create blob %s: %v", blob.Hash, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, blob := range blobs[:2] {
|
||||||
|
err = repos.Snapshots.AddBlob(ctx, nil, snapshot.ID.String(),
|
||||||
|
blob.ID, blob.Hash)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to add blob %s to snapshot: %v", blob.Hash, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compressed, uncompressed, err := repos.Snapshots.GetSnapshotBlobSizes(
|
||||||
|
ctx, snapshot.ID.String())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to get snapshot blob sizes: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if compressed != 30 || uncompressed != 300 {
|
||||||
|
t.Errorf("blob sizes: got %d and %d, want 30 and 300",
|
||||||
|
compressed, uncompressed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSnapshotRepositoryListRecent(t *testing.T) {
|
func TestSnapshotRepositoryListRecent(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -363,3 +423,52 @@ func TestSnapshotRepositoryDuplicate(t *testing.T) {
|
|||||||
t.Error("expected error for duplicate snapshot")
|
t.Error("expected error for duplicate snapshot")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Deleting a snapshot from the local index deletes the mount points its
|
||||||
|
// backup recorded, and no other snapshot's. See
|
||||||
|
// https://git.eeqj.de/sneak/vaultik/issues/395.
|
||||||
|
func TestSnapshotRepositoryDeleteRemovesMountPoints(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
db, cleanup := setupTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
repo := database.NewSnapshotRepository(db)
|
||||||
|
|
||||||
|
for _, id := range []types.SnapshotID{"kept", "deleted"} {
|
||||||
|
err := repo.Create(ctx, nil, &database.Snapshot{
|
||||||
|
ID: id,
|
||||||
|
Hostname: testHostname,
|
||||||
|
VaultikVersion: testVersion,
|
||||||
|
StartedAt: time.Now().Truncate(time.Second),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create snapshot: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = repo.AddMountPoint(ctx, nil, id.String(), "/data/nas")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to add mount point: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err := repo.Delete(ctx, "deleted")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to delete snapshot: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for id, want := range map[string][]string{
|
||||||
|
"kept": {"/data/nas"},
|
||||||
|
"deleted": nil,
|
||||||
|
} {
|
||||||
|
got, err := repo.GetMountPoints(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to read mount points: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slices.Equal(got, want) {
|
||||||
|
t.Errorf("mount points of %s: got %v, want %v", id, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -158,19 +158,3 @@ type UploadStats struct {
|
|||||||
MinDurationMs int64
|
MinDurationMs int64
|
||||||
MaxDurationMs int64
|
MaxDurationMs int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetCountBySnapshot returns the count of uploads for a specific snapshot
|
|
||||||
func (r *UploadRepository) GetCountBySnapshot(
|
|
||||||
ctx context.Context, snapshotID string,
|
|
||||||
) (int64, error) {
|
|
||||||
query := `SELECT COUNT(*) FROM uploads WHERE snapshot_id = ?`
|
|
||||||
|
|
||||||
var count int64
|
|
||||||
|
|
||||||
err := r.conn.QueryRowContext(ctx, query, snapshotID).Scan(&count)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return count, nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// Package exclude compiles exclude patterns into globs.
|
||||||
|
package exclude
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gobwas/glob"
|
||||||
|
)
|
||||||
|
|
||||||
|
var errBadExcludePattern = errors.New("is not a valid exclude pattern")
|
||||||
|
|
||||||
|
// Compile compiles one exclude pattern into the globs that match it.
|
||||||
|
// anchored reports whether the pattern matches only from the root of the
|
||||||
|
// source directory. An empty pattern yields no globs. Config.Validate and
|
||||||
|
// the scanner both compile patterns with it, so a pattern that loads is one
|
||||||
|
// the scanner can use.
|
||||||
|
func Compile(pattern string) ([]glob.Glob, bool, error) {
|
||||||
|
if pattern == "" {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// A leading "/" anchors the pattern to the source directory.
|
||||||
|
trimmed, anchored := strings.CutPrefix(pattern, "/")
|
||||||
|
|
||||||
|
// A trailing "/" marks a directory and is not matched.
|
||||||
|
trimmed = strings.TrimSuffix(trimmed, "/")
|
||||||
|
|
||||||
|
// A leading "**/" demands a "/" before the name and so misses an
|
||||||
|
// entry directly under the source path. It means "at every depth",
|
||||||
|
// which is what an unanchored pattern already does, so drop the
|
||||||
|
// prefix and match unanchored: as in gitignore, "**/x" and
|
||||||
|
// "/**/x" then also match a top-level "x".
|
||||||
|
if rest, found := strings.CutPrefix(trimmed, "**/"); found {
|
||||||
|
trimmed = rest
|
||||||
|
anchored = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Likewise "/**/" inside a pattern demands two slashes, so
|
||||||
|
// "a/**/*.log" misses "a/x.log". As in gitignore it stands for
|
||||||
|
// zero or more directories, so also compile the pattern with it
|
||||||
|
// made a single "/". The glob library's {a,b} is no help: with a
|
||||||
|
// "**" inside it in mid-pattern, it misses paths it should match.
|
||||||
|
var globs []glob.Glob
|
||||||
|
|
||||||
|
for _, variant := range doubleStarVariants(trimmed) {
|
||||||
|
g, err := glob.Compile(variant, '/')
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, fmt.Errorf("%q %w: %w",
|
||||||
|
pattern, errBadExcludePattern, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
globs = append(globs, g)
|
||||||
|
}
|
||||||
|
|
||||||
|
return globs, anchored, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// doubleStarVariants returns pattern once for every way of keeping each
|
||||||
|
// "/**/" in it or making it a single "/".
|
||||||
|
func doubleStarVariants(pattern string) []string {
|
||||||
|
const doubleStar = "/**/"
|
||||||
|
|
||||||
|
before, after, found := strings.Cut(pattern, doubleStar)
|
||||||
|
if !found {
|
||||||
|
return []string{pattern}
|
||||||
|
}
|
||||||
|
|
||||||
|
var variants []string
|
||||||
|
|
||||||
|
for _, rest := range doubleStarVariants(after) {
|
||||||
|
variants = append(variants, before+doubleStar+rest, before+"/"+rest)
|
||||||
|
}
|
||||||
|
|
||||||
|
return variants
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package exclude_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gobwas/glob"
|
||||||
|
"sneak.berlin/go/vaultik/internal/exclude"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestCompile checks the error, the anchoring and the globs that Compile
|
||||||
|
// returns for one exclude pattern.
|
||||||
|
func TestCompile(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
pattern string
|
||||||
|
wantErr string
|
||||||
|
wantAnchored bool
|
||||||
|
// wantMatches lists paths that one of the globs must match. When
|
||||||
|
// it is empty, Compile must return no globs.
|
||||||
|
wantMatches []string
|
||||||
|
}{
|
||||||
|
{name: "does not compile", pattern: "build[",
|
||||||
|
wantErr: `"build[" is not a valid exclude pattern`},
|
||||||
|
{name: "empty", pattern: ""},
|
||||||
|
{name: "leading slash anchors", pattern: "/build",
|
||||||
|
wantAnchored: true, wantMatches: []string{"build"}},
|
||||||
|
{name: "double star after the slash clears anchoring",
|
||||||
|
pattern: "/**/build", wantMatches: []string{"build"}},
|
||||||
|
{name: "double star in the middle", pattern: "a/**/*.log",
|
||||||
|
wantMatches: []string{"a/x.log", "a/b/x.log"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
globs, anchored, err := exclude.Compile(tt.pattern)
|
||||||
|
if tt.wantErr == "" && err != nil {
|
||||||
|
t.Fatalf("Compile(%q) error = %v, want none", tt.pattern, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tt.wantErr != "" &&
|
||||||
|
(err == nil || !strings.HasPrefix(err.Error(), tt.wantErr)) {
|
||||||
|
t.Fatalf("Compile(%q) error = %v, want one starting with %q",
|
||||||
|
tt.pattern, err, tt.wantErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if anchored != tt.wantAnchored {
|
||||||
|
t.Errorf("Compile(%q) anchored = %t, want %t",
|
||||||
|
tt.pattern, anchored, tt.wantAnchored)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(tt.wantMatches) == 0 && len(globs) != 0 {
|
||||||
|
t.Errorf("Compile(%q) returned %d globs, want none",
|
||||||
|
tt.pattern, len(globs))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, path := range tt.wantMatches {
|
||||||
|
matched := slices.ContainsFunc(globs, func(g glob.Glob) bool {
|
||||||
|
return g.Match(path)
|
||||||
|
})
|
||||||
|
if !matched {
|
||||||
|
t.Errorf("Compile(%q) globs do not match %q",
|
||||||
|
tt.pattern, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,24 @@
|
|||||||
// Package globals holds application-wide metadata (name, version,
|
// Package globals holds application-wide metadata (name, version,
|
||||||
// commit) that is populated at build time via linker flags.
|
// commit) that is populated at build time via linker flags, or from the
|
||||||
|
// build info Go records in the binary when the linker flags set none.
|
||||||
package globals
|
package globals
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/mod/module"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Appname is the application name, populated from main().
|
// Appname is the application name, populated from main().
|
||||||
var Appname = "vaultik" //nolint:gochecknoglobals // set via -ldflags at build time
|
var Appname = "vaultik" //nolint:gochecknoglobals // set via -ldflags at build time
|
||||||
|
|
||||||
// DevVersion is the version a binary reports when it was built without
|
// DevVersion is the version a binary reports when it was built without
|
||||||
// git metadata: script/version emits it outside a git checkout, and an
|
// git metadata: script/version emits it outside a git checkout, and a
|
||||||
// unstamped `go build` keeps it. goreleaser's snapshot template stamps
|
// binary keeps it when neither its linker flags nor its Go build info
|
||||||
|
// name a version. goreleaser's snapshot template stamps
|
||||||
// it followed by "-" and the commit it was built from. It is
|
// it followed by "-" and the commit it was built from. It is
|
||||||
// deliberately not a number.
|
// deliberately not a number.
|
||||||
const DevVersion = "dev"
|
const DevVersion = "dev"
|
||||||
@@ -32,6 +37,54 @@ var Commit = Unknown //nolint:gochecknoglobals // set via -ldflags at build time
|
|||||||
// CommitDate is the ISO-8601 date of the commit, populated from main().
|
// CommitDate is the ISO-8601 date of the commit, populated from main().
|
||||||
var CommitDate = Unknown //nolint:gochecknoglobals // set via -ldflags at build time
|
var CommitDate = Unknown //nolint:gochecknoglobals // set via -ldflags at build time
|
||||||
|
|
||||||
|
// develVersion is the main module version Go records when it cannot
|
||||||
|
// tell which version it built.
|
||||||
|
const develVersion = "(devel)"
|
||||||
|
|
||||||
|
// FillUnsetFromBuildInfo applies FillUnset to Version, Commit and
|
||||||
|
// CommitDate, with the build info of the running binary.
|
||||||
|
func FillUnsetFromBuildInfo() {
|
||||||
|
info, ok := debug.ReadBuildInfo()
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Version, Commit, CommitDate = FillUnset(
|
||||||
|
info, Version, Commit, CommitDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FillUnset returns version, commit and commitDate. Each one that
|
||||||
|
// still holds its default ("dev" or empty for the version, "unknown"
|
||||||
|
// for the others) is replaced by the value Go recorded in info. A
|
||||||
|
// `go install` of a tag sets no linker flags, but Go records the tag
|
||||||
|
// as the main module's version. Go records the commit and its time
|
||||||
|
// only when it builds from a git checkout. The time is cut to a date,
|
||||||
|
// as the Makefile stamps it.
|
||||||
|
func FillUnset(
|
||||||
|
info *debug.BuildInfo, version, commit, commitDate string,
|
||||||
|
) (string, string, string) {
|
||||||
|
if (version == "" || version == DevVersion) &&
|
||||||
|
info.Main.Version != "" && info.Main.Version != develVersion {
|
||||||
|
version = info.Main.Version
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, s := range info.Settings {
|
||||||
|
switch s.Key {
|
||||||
|
case "vcs.revision":
|
||||||
|
if commit == Unknown {
|
||||||
|
commit = s.Value
|
||||||
|
}
|
||||||
|
case "vcs.time":
|
||||||
|
t, err := time.Parse(time.RFC3339, s.Value)
|
||||||
|
if commitDate == Unknown && err == nil {
|
||||||
|
commitDate = t.UTC().Format(time.DateOnly)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return version, commit, commitDate
|
||||||
|
}
|
||||||
|
|
||||||
// Author identifies the upstream author of vaultik.
|
// Author identifies the upstream author of vaultik.
|
||||||
const Author = "Jeffrey Paul <sneak@sneak.berlin>"
|
const Author = "Jeffrey Paul <sneak@sneak.berlin>"
|
||||||
|
|
||||||
@@ -68,8 +121,10 @@ func New() (*Globals, error) {
|
|||||||
// a release. "dev" and goreleaser's snapshot "dev-<sha>" count, and so
|
// a release. "dev" and goreleaser's snapshot "dev-<sha>" count, and so
|
||||||
// does what `git describe --tags --always --dirty` gives a make or
|
// does what `git describe --tags --always --dirty` gives a make or
|
||||||
// docker build of an untagged commit: the bare short commit, or
|
// docker build of an untagged commit: the bare short commit, or
|
||||||
// tag-N-gHASH on a commit after a tag. Any version ending in "-dirty"
|
// tag-N-gHASH on a commit after a tag. A Go pseudo-version counts: Go
|
||||||
// counts, a modified checkout of a tag ("v1.0.0-dirty") included.
|
// records one for a build of an untagged commit without linker flags.
|
||||||
|
// Any version ending in "-dirty" or "+dirty" counts, a modified
|
||||||
|
// checkout of a tag ("v1.0.0-dirty", "v1.0.0+dirty") included.
|
||||||
// A plain tag such as "v1.0.0" or "1.0.0" is a release.
|
// A plain tag such as "v1.0.0" or "1.0.0" is a release.
|
||||||
//
|
//
|
||||||
// The empty string counts too. Nothing that knows its version reports
|
// The empty string counts too. Nothing that knows its version reports
|
||||||
@@ -82,7 +137,8 @@ func New() (*Globals, error) {
|
|||||||
func IsDevVersion(v string) bool {
|
func IsDevVersion(v string) bool {
|
||||||
if v == "" || v == Unknown || v == DevVersion ||
|
if v == "" || v == Unknown || v == DevVersion ||
|
||||||
strings.HasPrefix(v, DevVersion+"-") ||
|
strings.HasPrefix(v, DevVersion+"-") ||
|
||||||
strings.HasSuffix(v, "-dirty") {
|
strings.HasSuffix(v, "-dirty") || strings.HasSuffix(v, "+dirty") ||
|
||||||
|
module.IsPseudoVersion(v) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package globals_test
|
package globals_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"runtime/debug"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"sneak.berlin/go/vaultik/internal/globals"
|
"sneak.berlin/go/vaultik/internal/globals"
|
||||||
@@ -59,12 +60,20 @@ func TestIsDevVersion(t *testing.T) {
|
|||||||
{"1.0.0-rc.1-12-g877eb2f", true},
|
{"1.0.0-rc.1-12-g877eb2f", true},
|
||||||
// A tagged commit with uncommitted changes is not that tag.
|
// A tagged commit with uncommitted changes is not that tag.
|
||||||
{"v1.0.0-dirty", true},
|
{"v1.0.0-dirty", true},
|
||||||
|
// What Go records for a build without linker flags: a
|
||||||
|
// pseudo-version for an untagged commit, "+dirty" for a
|
||||||
|
// modified checkout.
|
||||||
|
{"v1.0.0-rc3.0.20261111001226-abcdefabcdef", true},
|
||||||
|
{"v0.0.0-20261111001226-abcdefabcdef", true},
|
||||||
|
{"v1.0.1-0.20261111001226-abcdefabcdef", true},
|
||||||
|
{"v1.0.0+dirty", true},
|
||||||
// What a tagged build produces (goreleaser's .Version strips
|
// What a tagged build produces (goreleaser's .Version strips
|
||||||
// the leading "v"; script/version keeps it).
|
// the leading "v"; script/version keeps it).
|
||||||
{"1.0.0", false},
|
{"1.0.0", false},
|
||||||
{"0.1.0", false},
|
{"0.1.0", false},
|
||||||
{"1.0.0-rc.1", false},
|
{"1.0.0-rc.1", false},
|
||||||
{"v1.0.0", false},
|
{"v1.0.0", false},
|
||||||
|
{"v1.0.0-rc3", false},
|
||||||
// A release must not be mistaken for a dev build just because
|
// A release must not be mistaken for a dev build just because
|
||||||
// the string happens to contain "dev".
|
// the string happens to contain "dev".
|
||||||
{"1.0.0-dev", false},
|
{"1.0.0-dev", false},
|
||||||
@@ -86,10 +95,9 @@ func TestIsDevVersion(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestDefaultVersionIsDev pins the linker-flag contract: an unstamped
|
// TestDefaultVersionIsDev pins the default: a binary whose linker flags
|
||||||
// binary (no -ldflags at all, which is what `go build ./...` and `go
|
// and build info name no version must report itself as a development
|
||||||
// install` produce) must report itself as a development build rather
|
// build rather than as some default release number.
|
||||||
// than as some default release number.
|
|
||||||
func TestDefaultVersionIsDev(t *testing.T) {
|
func TestDefaultVersionIsDev(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -98,3 +106,104 @@ func TestDefaultVersionIsDev(t *testing.T) {
|
|||||||
globals.DevVersion)
|
globals.DevVersion)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// buildInfo returns build info with the given main module version and,
|
||||||
|
// when revision is not empty, the commit settings Go records for a
|
||||||
|
// build from a git checkout.
|
||||||
|
func buildInfo(version, revision string) *debug.BuildInfo {
|
||||||
|
info := &debug.BuildInfo{
|
||||||
|
Main: debug.Module{Path: "sneak.berlin/go/vaultik", Version: version},
|
||||||
|
}
|
||||||
|
|
||||||
|
if revision != "" {
|
||||||
|
info.Settings = []debug.BuildSetting{
|
||||||
|
{Key: "vcs.revision", Value: revision},
|
||||||
|
{Key: "vcs.time", Value: "2026-11-10T23:12:26Z"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFillUnset covers a binary from `go install` of a tag, which
|
||||||
|
// carries no linker flags: it must report the tag. Values the linker
|
||||||
|
// flags set are kept.
|
||||||
|
func TestFillUnset(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const (
|
||||||
|
tag = "v1.0.0-rc3"
|
||||||
|
rev = "0123456789abcdef0123456789abcdef01234567"
|
||||||
|
)
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
info *debug.BuildInfo
|
||||||
|
version, commit, date string
|
||||||
|
wantVersion, wantCommit string
|
||||||
|
wantDate string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "go install of a tag",
|
||||||
|
info: buildInfo(tag, ""),
|
||||||
|
version: globals.DevVersion,
|
||||||
|
commit: globals.Unknown,
|
||||||
|
date: globals.Unknown,
|
||||||
|
wantVersion: tag,
|
||||||
|
wantCommit: globals.Unknown,
|
||||||
|
wantDate: globals.Unknown,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty version",
|
||||||
|
info: buildInfo(tag, ""),
|
||||||
|
version: "",
|
||||||
|
commit: globals.Unknown,
|
||||||
|
date: globals.Unknown,
|
||||||
|
wantVersion: tag,
|
||||||
|
wantCommit: globals.Unknown,
|
||||||
|
wantDate: globals.Unknown,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "go build in a git checkout",
|
||||||
|
info: buildInfo(tag, rev),
|
||||||
|
version: globals.DevVersion,
|
||||||
|
commit: globals.Unknown,
|
||||||
|
date: globals.Unknown,
|
||||||
|
wantVersion: tag,
|
||||||
|
wantCommit: rev,
|
||||||
|
wantDate: "2026-11-10",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Go could not tell the version",
|
||||||
|
info: buildInfo("(devel)", ""),
|
||||||
|
version: globals.DevVersion,
|
||||||
|
commit: globals.Unknown,
|
||||||
|
date: globals.Unknown,
|
||||||
|
wantVersion: globals.DevVersion,
|
||||||
|
wantCommit: globals.Unknown,
|
||||||
|
wantDate: globals.Unknown,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "linker flags set",
|
||||||
|
info: buildInfo(tag, rev),
|
||||||
|
version: "v1.0.0-rc2-4-gabcdef1",
|
||||||
|
commit: "abcdef1",
|
||||||
|
date: "2026-11-01",
|
||||||
|
wantVersion: "v1.0.0-rc2-4-gabcdef1",
|
||||||
|
wantCommit: "abcdef1",
|
||||||
|
wantDate: "2026-11-01",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range cases {
|
||||||
|
version, commit, date := globals.FillUnset(
|
||||||
|
tc.info, tc.version, tc.commit, tc.date)
|
||||||
|
|
||||||
|
if version != tc.wantVersion || commit != tc.wantCommit ||
|
||||||
|
date != tc.wantDate {
|
||||||
|
t.Errorf("%s: got %q, %q, %q; want %q, %q, %q", tc.name,
|
||||||
|
version, commit, date,
|
||||||
|
tc.wantVersion, tc.wantCommit, tc.wantDate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
|
"github.com/dustin/go-humanize"
|
||||||
)
|
)
|
||||||
|
|
||||||
// groupSeparator joins an open group path to an attribute key. This
|
// groupSeparator joins an open group path to an attribute key. This
|
||||||
@@ -304,18 +306,13 @@ func formatDuration(d time.Duration) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatBytes formats bytes in a human-readable way
|
// formatBytes formats a byte count with humanize.Bytes, as every command
|
||||||
|
// prints one. humanize.Bytes takes no negative count, so one is printed
|
||||||
|
// as it is.
|
||||||
func formatBytes(b int64) string {
|
func formatBytes(b int64) string {
|
||||||
const unit = 1024
|
if b < 0 {
|
||||||
if b < unit {
|
|
||||||
return fmt.Sprintf("%d B", b)
|
return fmt.Sprintf("%d B", b)
|
||||||
}
|
}
|
||||||
|
|
||||||
div, exp := int64(unit), 0
|
return humanize.Bytes(uint64(b))
|
||||||
for n := b / unit; n >= unit; n /= unit {
|
|
||||||
div *= unit
|
|
||||||
exp++
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGTPE"[exp])
|
|
||||||
}
|
}
|
||||||
@@ -200,7 +200,8 @@ func TestTTYHandlerWithGroupQualifiesKeys(t *testing.T) {
|
|||||||
func TestTTYHandlerByteFormattingSurvivesGrouping(t *testing.T) {
|
func TestTTYHandlerByteFormattingSurvivesGrouping(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
const oneAndAHalfKiB = 1536
|
// Printed as "1.0 MB", in powers of 1000 like every other byte count.
|
||||||
|
const oneMegabyte = 1_000_000
|
||||||
|
|
||||||
for name, testCase := range map[string]struct {
|
for name, testCase := range map[string]struct {
|
||||||
derive func(*slog.Logger) *slog.Logger
|
derive func(*slog.Logger) *slog.Logger
|
||||||
@@ -223,13 +224,13 @@ func TestTTYHandlerByteFormattingSurvivesGrouping(t *testing.T) {
|
|||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
|
||||||
logger := slog.New(log.NewTTYHandler(&buf, debugHandlerOptions()))
|
logger := slog.New(log.NewTTYHandler(&buf, debugHandlerOptions()))
|
||||||
testCase.derive(logger).Info("uploaded", "bytes", oneAndAHalfKiB)
|
testCase.derive(logger).Info("uploaded", "bytes", oneMegabyte)
|
||||||
|
|
||||||
line := ansiEscape.ReplaceAllString(buf.String(), "")
|
line := ansiEscape.ReplaceAllString(buf.String(), "")
|
||||||
|
|
||||||
assert.Contains(t, line, testCase.key+"=1.5 KB",
|
assert.Contains(t, line, testCase.key+"=1.0 MB",
|
||||||
"a byte count must be human-readable however it is qualified")
|
"a byte count must be human-readable however it is qualified")
|
||||||
assert.NotContains(t, line, strconv.Itoa(oneAndAHalfKiB),
|
assert.NotContains(t, line, strconv.Itoa(oneMegabyte),
|
||||||
"the raw number must not survive the formatting")
|
"the raw number must not survive the formatting")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+81
-53
@@ -10,15 +10,19 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
|
||||||
|
"github.com/adrg/xdg"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrAlreadyRunning indicates another vaultik instance is running.
|
// ErrAlreadyRunning indicates another vaultik instance is running.
|
||||||
var ErrAlreadyRunning = errors.New("another vaultik instance is already running")
|
var ErrAlreadyRunning = errors.New("another vaultik instance is already running")
|
||||||
|
|
||||||
// Lock represents an acquired PID lock.
|
// Lock represents an acquired PID lock: an flock(2) on the PID file,
|
||||||
|
// held while the file stays open. The kernel drops it when the process
|
||||||
|
// exits, however it exits, so a crashed run never leaves the lock held.
|
||||||
type Lock struct {
|
type Lock struct {
|
||||||
path string
|
file *os.File
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -26,13 +30,24 @@ const (
|
|||||||
lockDirPerm = 0o700
|
lockDirPerm = 0o700
|
||||||
// pidFilePerm is the mode for the PID file (owner-only).
|
// pidFilePerm is the mode for the PID file (owner-only).
|
||||||
pidFilePerm = 0o600
|
pidFilePerm = 0o600
|
||||||
|
// pidFileName is the name of the PID file in the lock directory.
|
||||||
|
pidFileName = "vaultik.pid"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Dir returns the directory that holds vaultik's PID file.
|
||||||
|
func Dir() string {
|
||||||
|
return filepath.Join(xdg.DataHome, "vaultik")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Path returns the path of the PID file that Acquire uses in lockDir.
|
||||||
|
func Path(lockDir string) string {
|
||||||
|
return filepath.Join(lockDir, pidFileName)
|
||||||
|
}
|
||||||
|
|
||||||
// Acquire attempts to acquire a PID lock in the specified directory.
|
// Acquire attempts to acquire a PID lock in the specified directory.
|
||||||
// If the lock file exists and the process is still running, it returns
|
// If another process holds the lock, it returns ErrAlreadyRunning with
|
||||||
// ErrAlreadyRunning with details about the existing process.
|
// that process's PID. On success, it writes the current PID to the lock
|
||||||
// On success, it writes the current PID to the lock file and returns
|
// file and returns a Lock that must be released with Release().
|
||||||
// a Lock that must be released with Release().
|
|
||||||
func Acquire(lockDir string) (*Lock, error) {
|
func Acquire(lockDir string) (*Lock, error) {
|
||||||
// Ensure lock directory exists
|
// Ensure lock directory exists
|
||||||
err := os.MkdirAll(lockDir, lockDirPerm)
|
err := os.MkdirAll(lockDir, lockDirPerm)
|
||||||
@@ -40,58 +55,84 @@ func Acquire(lockDir string) (*Lock, error) {
|
|||||||
return nil, fmt.Errorf("creating lock directory: %w", err)
|
return nil, fmt.Errorf("creating lock directory: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
lockPath := filepath.Join(lockDir, "vaultik.pid")
|
lockPath := Path(lockDir)
|
||||||
|
|
||||||
// Check for existing lock
|
// No O_TRUNC: the file may hold the PID of the process that has the
|
||||||
existingPID, err := readPIDFile(lockPath)
|
// lock, which the error below reports.
|
||||||
if err == nil {
|
file, err := os.OpenFile( //nolint:gosec // G304: path is our own lock file
|
||||||
// Lock file exists, check if process is running
|
lockPath, os.O_RDWR|os.O_CREATE, pidFilePerm)
|
||||||
if isProcessRunning(existingPID) {
|
|
||||||
return nil, fmt.Errorf("%w (PID %d)", ErrAlreadyRunning, existingPID)
|
|
||||||
}
|
|
||||||
// Process is not running, stale lock file - we can take over
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write our PID
|
|
||||||
pid := os.Getpid()
|
|
||||||
|
|
||||||
err = os.WriteFile(lockPath, []byte(strconv.Itoa(pid)), pidFilePerm)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("writing PID file: %w", err)
|
return nil, fmt.Errorf("opening PID file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Lock{path: lockPath}, nil
|
err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
|
||||||
|
if err != nil {
|
||||||
|
_ = file.Close()
|
||||||
|
|
||||||
|
if errors.Is(err, unix.EWOULDBLOCK) {
|
||||||
|
return nil, alreadyRunningError(lockPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("locking PID file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = writePID(file)
|
||||||
|
if err != nil {
|
||||||
|
_ = file.Close()
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Lock{file: file}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Release removes the PID lock file.
|
// Release empties the PID file and closes it, which drops the lock.
|
||||||
// It is safe to call Release multiple times.
|
// It is safe to call Release multiple times.
|
||||||
func (l *Lock) Release() error {
|
func (l *Lock) Release() error {
|
||||||
if l == nil || l.path == "" {
|
if l == nil || l.file == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify we still own the lock (our PID is in the file)
|
file := l.file
|
||||||
existingPID, err := readPIDFile(l.path)
|
l.file = nil
|
||||||
|
|
||||||
|
// Do not remove the file here. A process that opened it a moment
|
||||||
|
// earlier could then lock the removed file while another creates and
|
||||||
|
// locks a new one, and both would run.
|
||||||
|
truncateErr := file.Truncate(0)
|
||||||
|
closeErr := file.Close()
|
||||||
|
|
||||||
|
return errors.Join(truncateErr, closeErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// writePID replaces the contents of the locked PID file with the current
|
||||||
|
// PID.
|
||||||
|
func writePID(file *os.File) error {
|
||||||
|
err := file.Truncate(0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// File already gone or unreadable - that's fine
|
return fmt.Errorf("truncating PID file: %w", err)
|
||||||
return nil //nolint:nilerr // unreadable lock file means nothing to release
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if existingPID != os.Getpid() {
|
_, err = file.WriteAt([]byte(strconv.Itoa(os.Getpid())), 0)
|
||||||
// Someone else wrote to our lock file - don't remove it
|
if err != nil {
|
||||||
return nil
|
return fmt.Errorf("writing PID file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = os.Remove(l.path)
|
|
||||||
if err != nil && !os.IsNotExist(err) {
|
|
||||||
return fmt.Errorf("removing PID file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
l.path = "" // Prevent double-release
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// alreadyRunningError reports that another process holds the lock,
|
||||||
|
// naming its PID when the file holds one. The holder writes its PID just
|
||||||
|
// after it locks, so the file can briefly be empty.
|
||||||
|
func alreadyRunningError(lockPath string) error {
|
||||||
|
pid, err := readPIDFile(lockPath)
|
||||||
|
if err != nil {
|
||||||
|
return ErrAlreadyRunning
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("%w (PID %d)", ErrAlreadyRunning, pid)
|
||||||
|
}
|
||||||
|
|
||||||
// readPIDFile reads and parses the PID from a lock file.
|
// readPIDFile reads and parses the PID from a lock file.
|
||||||
func readPIDFile(path string) (int, error) {
|
func readPIDFile(path string) (int, error) {
|
||||||
data, err := os.ReadFile(path) //nolint:gosec // G304: path is our own lock file
|
data, err := os.ReadFile(path) //nolint:gosec // G304: path is our own lock file
|
||||||
@@ -106,16 +147,3 @@ func readPIDFile(path string) (int, error) {
|
|||||||
|
|
||||||
return pid, nil
|
return pid, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// isProcessRunning checks if a process with the given PID is running.
|
|
||||||
func isProcessRunning(pid int) bool {
|
|
||||||
process, err := os.FindProcess(pid)
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// On Unix, FindProcess always succeeds. We need to send signal 0 to check.
|
|
||||||
err = process.Signal(syscall.Signal(0))
|
|
||||||
|
|
||||||
return err == nil
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -33,9 +34,10 @@ func TestAcquireAndRelease(t *testing.T) {
|
|||||||
err = lock.Release()
|
err = lock.Release()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
// Verify PID file is gone
|
// Verify PID file is empty
|
||||||
_, err = os.Stat(pidPath)
|
data, err = os.ReadFile(pidPath) //nolint:gosec // G304: test's own temp file
|
||||||
assert.True(t, os.IsNotExist(err))
|
require.NoError(t, err)
|
||||||
|
assert.Empty(t, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAcquireBlocksSecondInstance(t *testing.T) {
|
func TestAcquireBlocksSecondInstance(t *testing.T) {
|
||||||
@@ -55,6 +57,64 @@ func TestAcquireBlocksSecondInstance(t *testing.T) {
|
|||||||
lock2, err := pidlock.Acquire(tmpDir)
|
lock2, err := pidlock.Acquire(tmpDir)
|
||||||
require.ErrorIs(t, err, pidlock.ErrAlreadyRunning)
|
require.ErrorIs(t, err, pidlock.ErrAlreadyRunning)
|
||||||
assert.Nil(t, lock2)
|
assert.Nil(t, lock2)
|
||||||
|
|
||||||
|
// Once the first lock is released, the next Acquire succeeds
|
||||||
|
require.NoError(t, lock1.Release())
|
||||||
|
|
||||||
|
lock3, err := pidlock.Acquire(tmpDir)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, lock3.Release())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConcurrentAcquireAdmitsOne starts many Acquire calls at the same
|
||||||
|
// moment, as two cron entries firing together would, and checks that
|
||||||
|
// exactly one of them gets the lock.
|
||||||
|
func TestConcurrentAcquireAdmitsOne(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const callers = 50
|
||||||
|
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
start := make(chan struct{})
|
||||||
|
|
||||||
|
var (
|
||||||
|
mu sync.Mutex
|
||||||
|
acquired []*pidlock.Lock
|
||||||
|
failures []error
|
||||||
|
wg sync.WaitGroup
|
||||||
|
)
|
||||||
|
|
||||||
|
for range callers {
|
||||||
|
wg.Go(func() {
|
||||||
|
<-start
|
||||||
|
|
||||||
|
lock, err := pidlock.Acquire(tmpDir)
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
failures = append(failures, err)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
acquired = append(acquired, lock)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
close(start)
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
for _, lock := range acquired {
|
||||||
|
require.NoError(t, lock.Release())
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Len(t, acquired, 1, "exactly one caller should hold the lock")
|
||||||
|
|
||||||
|
for _, err := range failures {
|
||||||
|
require.ErrorIs(t, err, pidlock.ErrAlreadyRunning)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAcquireWithStaleLock(t *testing.T) {
|
func TestAcquireWithStaleLock(t *testing.T) {
|
||||||
|
|||||||
+71
-11
@@ -6,7 +6,9 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
|
"strings"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/aws/aws-sdk-go-v2/aws"
|
"github.com/aws/aws-sdk-go-v2/aws"
|
||||||
"github.com/aws/aws-sdk-go-v2/config"
|
"github.com/aws/aws-sdk-go-v2/config"
|
||||||
@@ -17,6 +19,13 @@ import (
|
|||||||
"github.com/aws/smithy-go/logging"
|
"github.com/aws/smithy-go/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrNoContinuationToken is returned by ListObjects and ListObjectsStream
|
||||||
|
// when the server marks a page of a listing truncated but sends no
|
||||||
|
// continuation token to fetch the rest with, as a server answering V2
|
||||||
|
// listings V1-style does.
|
||||||
|
var ErrNoContinuationToken = errors.New(
|
||||||
|
"server marked the listing truncated but sent no continuation token")
|
||||||
|
|
||||||
// Client wraps the AWS S3 client for vaultik operations.
|
// Client wraps the AWS S3 client for vaultik operations.
|
||||||
// It provides a simplified interface for S3 operations with automatic
|
// It provides a simplified interface for S3 operations with automatic
|
||||||
// prefix handling and connection management. All operations are performed
|
// prefix handling and connection management. All operations are performed
|
||||||
@@ -26,10 +35,14 @@ type Client struct {
|
|||||||
bucket string
|
bucket string
|
||||||
prefix string
|
prefix string
|
||||||
endpoint string
|
endpoint string
|
||||||
|
partSize int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config contains S3 client configuration.
|
// Config contains S3 client configuration.
|
||||||
// All fields are required except Prefix, which defaults to an empty string.
|
// All fields are required except Prefix, which defaults to an empty string,
|
||||||
|
// and PartSize, where zero means the SDK default of 5 MiB.
|
||||||
|
// A non-empty Prefix is joined to every key with one "/", whether or not
|
||||||
|
// it ends with one.
|
||||||
// The Endpoint field should include the protocol (http:// or https://).
|
// The Endpoint field should include the protocol (http:// or https://).
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Endpoint string
|
Endpoint string
|
||||||
@@ -38,6 +51,9 @@ type Config struct {
|
|||||||
AccessKeyID string
|
AccessKeyID string
|
||||||
SecretAccessKey string
|
SecretAccessKey string
|
||||||
Region string
|
Region string
|
||||||
|
// PartSize is the size in bytes of each part of a multipart upload.
|
||||||
|
// An upload too large for S3's limit of 10,000 parts gets larger parts.
|
||||||
|
PartSize int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// nopLogger is a logger that discards all output.
|
// nopLogger is a logger that discards all output.
|
||||||
@@ -75,11 +91,19 @@ func NewClient(ctx context.Context, cfg Config) (*Client, error) {
|
|||||||
|
|
||||||
s3Client := s3.NewFromConfig(awsCfg, s3Opts)
|
s3Client := s3.NewFromConfig(awsCfg, s3Opts)
|
||||||
|
|
||||||
|
// Every method below builds a key as prefix + key, so the prefix
|
||||||
|
// must carry its own trailing "/".
|
||||||
|
prefix := strings.TrimRight(cfg.Prefix, "/")
|
||||||
|
if prefix != "" {
|
||||||
|
prefix += "/"
|
||||||
|
}
|
||||||
|
|
||||||
return &Client{
|
return &Client{
|
||||||
s3Client: s3Client,
|
s3Client: s3Client,
|
||||||
bucket: cfg.Bucket,
|
bucket: cfg.Bucket,
|
||||||
prefix: cfg.Prefix,
|
prefix: prefix,
|
||||||
endpoint: cfg.Endpoint,
|
endpoint: cfg.Endpoint,
|
||||||
|
partSize: cfg.PartSize,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,12 +137,9 @@ func (c *Client) PutObjectWithProgress(
|
|||||||
) error {
|
) error {
|
||||||
fullKey := c.prefix + key
|
fullKey := c.prefix + key
|
||||||
|
|
||||||
// uploadPartSize is 10MB for better progress granularity.
|
|
||||||
const uploadPartSize = 10 * 1024 * 1024
|
|
||||||
|
|
||||||
// Create an uploader with the S3 client
|
// Create an uploader with the S3 client
|
||||||
uploader := manager.NewUploader(c.s3Client, func(u *manager.Uploader) {
|
uploader := manager.NewUploader(c.s3Client, func(u *manager.Uploader) {
|
||||||
u.PartSize = uploadPartSize
|
u.PartSize = uploadPartSize(c.partSize, size)
|
||||||
})
|
})
|
||||||
|
|
||||||
// Create a progress reader that tracks upload progress
|
// Create a progress reader that tracks upload progress
|
||||||
@@ -139,6 +160,21 @@ func (c *Client) PutObjectWithProgress(
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// uploadPartSize returns the part size for an upload of size bytes: the
|
||||||
|
// configured part size (the SDK default when zero), raised where needed so
|
||||||
|
// the upload fits in S3's limit of 10,000 parts. The uploader cannot raise
|
||||||
|
// it itself, because it cannot seek the progress reader to learn its size.
|
||||||
|
func uploadPartSize(configured, size int64) int64 {
|
||||||
|
if configured == 0 {
|
||||||
|
configured = manager.DefaultUploadPartSize
|
||||||
|
}
|
||||||
|
|
||||||
|
maxParts := int64(manager.MaxUploadParts)
|
||||||
|
smallestThatFits := (size + maxParts - 1) / maxParts // rounded up
|
||||||
|
|
||||||
|
return max(configured, smallestThatFits)
|
||||||
|
}
|
||||||
|
|
||||||
// GetObject downloads an object from S3 with the specified key.
|
// GetObject downloads an object from S3 with the specified key.
|
||||||
// The key is automatically prefixed with the configured prefix.
|
// The key is automatically prefixed with the configured prefix.
|
||||||
// Returns a ReadCloser containing the object data. The caller must
|
// Returns a ReadCloser containing the object data. The caller must
|
||||||
@@ -186,7 +222,7 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro
|
|||||||
})
|
})
|
||||||
|
|
||||||
for paginator.HasMorePages() {
|
for paginator.HasMorePages() {
|
||||||
page, err := paginator.NextPage(ctx)
|
page, err := nextListPage(ctx, paginator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -207,6 +243,26 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro
|
|||||||
return keys, nil
|
return keys, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nextListPage fetches the next page of a listing. The SDK paginator takes
|
||||||
|
// a page marked truncated without a continuation token for the last page
|
||||||
|
// and stops without an error, so such a page is ErrNoContinuationToken
|
||||||
|
// here instead.
|
||||||
|
func nextListPage(
|
||||||
|
ctx context.Context, paginator *s3.ListObjectsV2Paginator,
|
||||||
|
) (*s3.ListObjectsV2Output, error) {
|
||||||
|
page, err := paginator.NextPage(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
truncated := aws.ToBool(page.IsTruncated)
|
||||||
|
if truncated && aws.ToString(page.NextContinuationToken) == "" {
|
||||||
|
return nil, ErrNoContinuationToken
|
||||||
|
}
|
||||||
|
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
|
|
||||||
// HeadObject checks if an object exists in S3.
|
// HeadObject checks if an object exists in S3.
|
||||||
// Returns true if the object exists, false otherwise.
|
// Returns true if the object exists, false otherwise.
|
||||||
// The key is automatically prefixed with the configured prefix.
|
// The key is automatically prefixed with the configured prefix.
|
||||||
@@ -247,7 +303,10 @@ func IsNotFound(err error) bool {
|
|||||||
type ObjectInfo struct {
|
type ObjectInfo struct {
|
||||||
Key string
|
Key string
|
||||||
Size int64
|
Size int64
|
||||||
Err error
|
// ModTime is the object's LastModified time. Only ListObjectsStream
|
||||||
|
// sets it.
|
||||||
|
ModTime time.Time
|
||||||
|
Err error
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListObjectsStream lists objects with the given prefix and returns a channel.
|
// ListObjectsStream lists objects with the given prefix and returns a channel.
|
||||||
@@ -272,7 +331,7 @@ func (c *Client) ListObjectsStream(
|
|||||||
})
|
})
|
||||||
|
|
||||||
for paginator.HasMorePages() {
|
for paginator.HasMorePages() {
|
||||||
page, err := paginator.NextPage(ctx)
|
page, err := nextListPage(ctx, paginator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ch <- ObjectInfo{Err: err}
|
ch <- ObjectInfo{Err: err}
|
||||||
|
|
||||||
@@ -288,8 +347,9 @@ func (c *Client) ListObjectsStream(
|
|||||||
}
|
}
|
||||||
|
|
||||||
ch <- ObjectInfo{
|
ch <- ObjectInfo{
|
||||||
Key: key,
|
Key: key,
|
||||||
Size: *obj.Size,
|
Size: *obj.Size,
|
||||||
|
ModTime: aws.ToTime(obj.LastModified),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package s3
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// TestUploadPartSize checks that an upload too large for 10,000 parts of the
|
||||||
|
// configured size gets parts just large enough to fit in 10,000.
|
||||||
|
func TestUploadPartSize(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const mib = 1024 * 1024
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
configured int64
|
||||||
|
size int64
|
||||||
|
want int64
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "an upload that fits keeps the configured size",
|
||||||
|
configured: 5 * mib,
|
||||||
|
size: 10 * 1024 * mib,
|
||||||
|
want: 5 * mib,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "exactly 10,000 parts keeps the configured size",
|
||||||
|
configured: 6 * mib,
|
||||||
|
size: 10_000 * 6 * mib,
|
||||||
|
want: 6 * mib,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "one byte more than 10,000 parts adds a byte to each",
|
||||||
|
configured: 6 * mib,
|
||||||
|
size: 10_000*6*mib + 1,
|
||||||
|
want: 6*mib + 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "zero means the SDK default of 5MiB",
|
||||||
|
configured: 0,
|
||||||
|
size: 1,
|
||||||
|
want: 5 * mib,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
got := uploadPartSize(tt.configured, tt.size)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("uploadPartSize(%d, %d) = %d, want %d",
|
||||||
|
tt.configured, tt.size, got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,7 @@ func provideClient(lc fx.Lifecycle, cfg *config.Config) (*Client, error) {
|
|||||||
AccessKeyID: cfg.S3.AccessKeyID,
|
AccessKeyID: cfg.S3.AccessKeyID,
|
||||||
SecretAccessKey: cfg.S3.SecretAccessKey,
|
SecretAccessKey: cfg.S3.SecretAccessKey,
|
||||||
Region: cfg.S3.Region,
|
Region: cfg.S3.Region,
|
||||||
|
PartSize: cfg.S3.PartSize.Int64(),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ func verifyBackupFiles(
|
|||||||
) {
|
) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
files, err := repos.Files.ListByPrefix(ctx, "")
|
files, err := repos.Files.ListAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to list files: %v", err)
|
t.Fatalf("Failed to list files: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
//nolint:testpackage // exercises the unexported cleanupBlobTempFile
|
||||||
|
package snapshot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/afero"
|
||||||
|
"sneak.berlin/go/vaultik/internal/blob"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A blob temp file that cannot be closed or removed must make the cleanup
|
||||||
|
// return an error, not end the process.
|
||||||
|
func TestCleanupBlobTempFileReturnsErrors(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
fs := afero.NewOsFs()
|
||||||
|
s := &Scanner{fs: fs}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
// prepare runs before the cleanup and makes its close or remove
|
||||||
|
// fail.
|
||||||
|
prepare func(tempFile afero.File) error
|
||||||
|
want error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "close fails",
|
||||||
|
prepare: func(tempFile afero.File) error { return tempFile.Close() },
|
||||||
|
want: os.ErrClosed,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "remove fails",
|
||||||
|
prepare: func(tempFile afero.File) error {
|
||||||
|
return fs.Remove(tempFile.Name())
|
||||||
|
},
|
||||||
|
want: os.ErrNotExist,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tempFile, err := afero.TempFile(fs, t.TempDir(), "blob-*.tmp")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tt.prepare(tempFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = s.cleanupBlobTempFile(&blob.WithReader{TempFile: tempFile})
|
||||||
|
if !errors.Is(err, tt.want) {
|
||||||
|
t.Fatalf("expected an error wrapping %v, got: %v", tt.want, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
//nolint:testpackage // exercises the unexported deviceNumberFromStat
|
||||||
|
package snapshot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The device number a real backup reads is the same for a directory and
|
||||||
|
// a file in it, and differs between the temp directory and /dev.
|
||||||
|
// Without it no mount point is ever found. See
|
||||||
|
// https://git.eeqj.de/sneak/vaultik/issues/395.
|
||||||
|
func TestDeviceNumberFromStat(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
file := filepath.Join(dir, "file.txt")
|
||||||
|
require.NoError(t, os.WriteFile(file, nil, 0o600))
|
||||||
|
|
||||||
|
deviceOf := func(path string) uint64 {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
device, ok := deviceNumberFromStat(info)
|
||||||
|
require.True(t, ok, "no device number read for %s", path)
|
||||||
|
|
||||||
|
return device
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, deviceOf(dir), deviceOf(file))
|
||||||
|
|
||||||
|
// /dev is a different filesystem from the temp dir on Linux, macOS and in Docker.
|
||||||
|
assert.NotEqual(t, deviceOf(dir), deviceOf("/dev"))
|
||||||
|
}
|
||||||
@@ -531,3 +531,101 @@ func TestExcludePatterns_UnanchoredPatternFile(t *testing.T) {
|
|||||||
require.Equal(t, 1, result.FilesScanned,
|
require.Equal(t, 1, result.FilesScanned,
|
||||||
"Unanchored pattern for file should match anywhere")
|
"Unanchored pattern for file should match anywhere")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExcludePatterns_DoubleStarDirectoryAtEveryDepth(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// As in gitignore, a leading **/ also matches directly under the source dir
|
||||||
|
fs := setupAnchoredTestFS(t)
|
||||||
|
|
||||||
|
scanner, repos, cleanup := createTestScanner(t, fs, []string{"**/projectname"})
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
createSnapshotRecord(ctx, t, repos, "test-snapshot")
|
||||||
|
|
||||||
|
result, err := scanner.Scan(ctx, "/backup", "test-snapshot")
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// **/projectname should exclude BOTH:
|
||||||
|
// - /backup/projectname/file.txt
|
||||||
|
// - /backup/otherproject/projectname/file.txt
|
||||||
|
// Total files: 4, excluded: 2
|
||||||
|
require.Equal(t, 2, result.FilesScanned,
|
||||||
|
"**/ directory pattern should match at the top level and nested")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExcludePatterns_DoubleStarFileAtEveryDepth(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// As in gitignore, a leading **/ also matches directly under the source dir
|
||||||
|
fs := setupAnchoredTestFS(t)
|
||||||
|
|
||||||
|
scanner, repos, cleanup := createTestScanner(t, fs, []string{"**/*.txt"})
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
createSnapshotRecord(ctx, t, repos, "test-snapshot")
|
||||||
|
|
||||||
|
result, err := scanner.Scan(ctx, "/backup", "test-snapshot")
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// **/*.txt should exclude ALL .txt files:
|
||||||
|
// - /backup/file.txt
|
||||||
|
// - /backup/projectname/file.txt
|
||||||
|
// - /backup/otherproject/projectname/file.txt
|
||||||
|
// Total files: 4, excluded: 3
|
||||||
|
require.Equal(t, 1, result.FilesScanned,
|
||||||
|
"**/ file pattern should match at the top level and nested")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExcludePatterns_AnchoredDoubleStarAtEveryDepth(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// As in gitignore, /**/ also matches directly under the source dir
|
||||||
|
fs := setupAnchoredTestFS(t)
|
||||||
|
|
||||||
|
scanner, repos, cleanup := createTestScanner(t, fs, []string{"/**/projectname"})
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
createSnapshotRecord(ctx, t, repos, "test-snapshot")
|
||||||
|
|
||||||
|
result, err := scanner.Scan(ctx, "/backup", "test-snapshot")
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// /**/projectname should exclude BOTH:
|
||||||
|
// - /backup/projectname/file.txt
|
||||||
|
// - /backup/otherproject/projectname/file.txt
|
||||||
|
// Total files: 4, excluded: 2
|
||||||
|
require.Equal(t, 2, result.FilesScanned,
|
||||||
|
"/**/ pattern should match at the top level and nested")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExcludePatterns_DoubleStarInMiddleMatchesZeroDirectories(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// As in gitignore, a/**/b matches a/b as well as a/c/b. The last part
|
||||||
|
// is a glob: with a plain name the glob library already matched a/b.
|
||||||
|
fs := &afero.MemMapFs{}
|
||||||
|
files := []string{"/backup/a/x.log", "/backup/a/c/y.log", "/backup/a/c/kept.txt"}
|
||||||
|
|
||||||
|
for _, path := range files {
|
||||||
|
require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0755))
|
||||||
|
require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0644))
|
||||||
|
}
|
||||||
|
|
||||||
|
scanner, repos, cleanup := createTestScanner(t, fs, []string{"a/**/*.log"})
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
createSnapshotRecord(ctx, t, repos, "test-snapshot")
|
||||||
|
|
||||||
|
result, err := scanner.Scan(ctx, "/backup", "test-snapshot")
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
// a/**/*.log should exclude /backup/a/x.log and /backup/a/c/y.log
|
||||||
|
// Total files: 3, excluded: 2
|
||||||
|
require.Equal(t, 1, result.FilesScanned,
|
||||||
|
"a/**/*.log should match a/x.log as well as a/c/y.log")
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package snapshot_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/afero"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A backup of the directory that holds vaultik's index and PID file
|
||||||
|
// stores neither, with no exclude pattern set, and still stores the
|
||||||
|
// files beside them. See https://git.eeqj.de/sneak/vaultik/issues/421.
|
||||||
|
func TestScanSkipsIndexAndLockFiles(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const dataDir = "/home/user/.local/share/vaultik"
|
||||||
|
|
||||||
|
indexAndLockFiles := append(database.IndexFiles(dataDir+"/index.sqlite"),
|
||||||
|
dataDir+"/vaultik.pid")
|
||||||
|
|
||||||
|
fs := afero.NewMemMapFs()
|
||||||
|
for _, p := range append(indexAndLockFiles, dataDir+"/notes.txt") {
|
||||||
|
require.NoError(t, afero.WriteFile(fs, p, []byte("data"), 0o600))
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := database.NewTestDB()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
defer func() { _ = db.Close() }()
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
scanner := snapshot.NewScanner(snapshot.ScannerConfig{
|
||||||
|
FS: fs,
|
||||||
|
ChunkSize: 64 * 1024,
|
||||||
|
Repositories: repos,
|
||||||
|
MaxBlobSize: 1024 * 1024,
|
||||||
|
CompressionLevel: 3,
|
||||||
|
AgeRecipients: []string{
|
||||||
|
"age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p"},
|
||||||
|
IndexAndLockFiles: indexAndLockFiles,
|
||||||
|
})
|
||||||
|
require.NotNil(t, scanner)
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
createSnapshotRecord(ctx, t, repos, "test-snapshot")
|
||||||
|
|
||||||
|
result, err := scanner.Scan(ctx, "/home/user", "test-snapshot")
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
require.Equal(t, 1, result.FilesScanned)
|
||||||
|
|
||||||
|
stored, err := repos.Files.GetByPath(ctx, dataDir+"/notes.txt")
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, stored, "a file beside the index is stored")
|
||||||
|
|
||||||
|
for _, p := range indexAndLockFiles {
|
||||||
|
f, err := repos.Files.GetByPath(ctx, p)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Nil(t, f, "%s is not stored", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
+66
-11
@@ -1,10 +1,14 @@
|
|||||||
package snapshot
|
package snapshot
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/spf13/afero"
|
"github.com/spf13/afero"
|
||||||
"go.uber.org/fx"
|
"go.uber.org/fx"
|
||||||
"sneak.berlin/go/vaultik/internal/config"
|
"sneak.berlin/go/vaultik/internal/config"
|
||||||
"sneak.berlin/go/vaultik/internal/database"
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/pidlock"
|
||||||
"sneak.berlin/go/vaultik/internal/storage"
|
"sneak.berlin/go/vaultik/internal/storage"
|
||||||
"sneak.berlin/go/vaultik/internal/ui"
|
"sneak.berlin/go/vaultik/internal/ui"
|
||||||
)
|
)
|
||||||
@@ -16,6 +20,12 @@ type ScannerParams struct {
|
|||||||
Fs afero.Fs
|
Fs afero.Fs
|
||||||
Exclude []string // Exclude patterns (combined global + snapshot-specific)
|
Exclude []string // Exclude patterns (combined global + snapshot-specific)
|
||||||
SkipErrors bool // Skip file read errors (log loudly but continue)
|
SkipErrors bool // Skip file read errors (log loudly but continue)
|
||||||
|
// PreviousSnapshotID is the most recent completed snapshot of the
|
||||||
|
// same name, "" for none.
|
||||||
|
PreviousSnapshotID string
|
||||||
|
// DeviceNumber is ScannerConfig.DeviceNumber; nil reads it from the
|
||||||
|
// file's stat.
|
||||||
|
DeviceNumber func(info os.FileInfo) (uint64, bool)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Module exports backup functionality as an fx module.
|
// Module exports backup functionality as an fx module.
|
||||||
@@ -44,17 +54,62 @@ func provideScannerFactory(
|
|||||||
}
|
}
|
||||||
|
|
||||||
return NewScanner(ScannerConfig{
|
return NewScanner(ScannerConfig{
|
||||||
FS: params.Fs,
|
FS: params.Fs,
|
||||||
ChunkSize: cfg.ChunkSize.Int64(),
|
ChunkSize: cfg.ChunkSize.Int64(),
|
||||||
Repositories: repos,
|
Repositories: repos,
|
||||||
Storage: storer,
|
Storage: storer,
|
||||||
MaxBlobSize: cfg.BlobSizeLimit.Int64(),
|
MaxBlobSize: cfg.BlobSizeLimit.Int64(),
|
||||||
CompressionLevel: cfg.CompressionLevel,
|
CompressionLevel: cfg.CompressionLevel,
|
||||||
AgeRecipients: cfg.AgeRecipients,
|
AgeRecipients: cfg.AgeRecipients,
|
||||||
EnableProgress: params.EnableProgress,
|
EnableProgress: params.EnableProgress,
|
||||||
UI: params.UI,
|
UI: params.UI,
|
||||||
Exclude: excludes,
|
Exclude: excludes,
|
||||||
SkipErrors: params.SkipErrors,
|
IndexAndLockFiles: indexAndLockFiles(cfg.IndexPath, pidlock.Dir()),
|
||||||
|
SkipErrors: params.SkipErrors,
|
||||||
|
PreviousSnapshotID: params.PreviousSnapshotID,
|
||||||
|
DeviceNumber: params.DeviceNumber,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// indexAndLockFiles returns the paths of the index at indexPath, its side
|
||||||
|
// files and the PID file in lockDir. Symlinks in their directories are
|
||||||
|
// resolved, as they are in the snapshot's source paths, so the scan finds
|
||||||
|
// them under the same names. If indexPath is a symlink, the file it points
|
||||||
|
// to and that file's side files are returned too.
|
||||||
|
func indexAndLockFiles(indexPath, lockDir string) []string {
|
||||||
|
paths := append(database.IndexFiles(indexPath), pidlock.Path(lockDir))
|
||||||
|
for i, p := range paths {
|
||||||
|
paths[i] = resolveParentDir(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SQLite writes the file a symlinked index points to and keeps the
|
||||||
|
// side files beside that file. The database package creates the index
|
||||||
|
// before the scanner is built, so the link resolves.
|
||||||
|
index := resolveParentDir(indexPath)
|
||||||
|
|
||||||
|
target, err := filepath.EvalSymlinks(index)
|
||||||
|
if err == nil && target != index {
|
||||||
|
paths = append(paths, database.IndexFiles(target)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveParentDir returns the absolute form of path with the symlinks in
|
||||||
|
// its parent directory resolved. If the parent directory cannot be
|
||||||
|
// resolved, it returns the absolute form unresolved. If path has no
|
||||||
|
// absolute form, it returns path.
|
||||||
|
func resolveParentDir(path string) string {
|
||||||
|
abs, err := filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
dir, err := filepath.EvalSymlinks(filepath.Dir(abs))
|
||||||
|
if err != nil {
|
||||||
|
return abs
|
||||||
|
}
|
||||||
|
|
||||||
|
return filepath.Join(dir, filepath.Base(abs))
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
//nolint:testpackage // exercises the unexported indexAndLockFiles helper
|
||||||
|
package snapshot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The scan walks source paths with symlinks resolved, so vaultik's own
|
||||||
|
// files are named the same way, or a symlinked home would back them up.
|
||||||
|
func TestIndexAndLockFilesResolvesSymlinkedDirectory(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
realDir, err := filepath.EvalSymlinks(t.TempDir())
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
link := filepath.Join(t.TempDir(), "link")
|
||||||
|
require.NoError(t, os.Symlink(realDir, link))
|
||||||
|
|
||||||
|
paths := indexAndLockFiles(filepath.Join(link, "index.sqlite"), link)
|
||||||
|
|
||||||
|
require.Equal(t, []string{
|
||||||
|
filepath.Join(realDir, "index.sqlite"),
|
||||||
|
filepath.Join(realDir, "index.sqlite-wal"),
|
||||||
|
filepath.Join(realDir, "index.sqlite-shm"),
|
||||||
|
filepath.Join(realDir, "index.sqlite-journal"),
|
||||||
|
filepath.Join(realDir, "vaultik.pid"),
|
||||||
|
}, paths)
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
package snapshot_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/afero"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A scan records with the snapshot each directory on a different device
|
||||||
|
// from its parent directory that the walk found an entry in, as a mount
|
||||||
|
// point is, the scanned path included. A filesystem that gives no device
|
||||||
|
// numbers, as the in-memory one, records none. See
|
||||||
|
// https://git.eeqj.de/sneak/vaultik/issues/395.
|
||||||
|
func TestScanRecordsMountPoints(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const (
|
||||||
|
scannedPath = "/data/source"
|
||||||
|
snapshotID = "mount-points"
|
||||||
|
)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
// onVolume names the directories on the volume's device; every
|
||||||
|
// other directory is on another one. nil leaves the device
|
||||||
|
// numbers to the in-memory filesystem, which has none.
|
||||||
|
onVolume []string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "volume below the scanned path",
|
||||||
|
onVolume: []string{"nas"},
|
||||||
|
want: []string{scannedPath + "/nas"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "volume at the scanned path",
|
||||||
|
onVolume: []string{"source", "nas"},
|
||||||
|
want: []string{scannedPath},
|
||||||
|
},
|
||||||
|
{name: "no device numbers", want: nil},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
fs := afero.NewMemMapFs()
|
||||||
|
|
||||||
|
for _, path := range []string{
|
||||||
|
scannedPath + "/notes.txt", scannedPath + "/nas/a.txt",
|
||||||
|
} {
|
||||||
|
require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755))
|
||||||
|
require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0o644))
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := database.NewTestDB()
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = db.Close() })
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
createTestSnapshotRecord(ctx, t, repos, snapshotID)
|
||||||
|
|
||||||
|
cfg := snapshot.ScannerConfig{
|
||||||
|
FS: fs,
|
||||||
|
ChunkSize: int64(1024 * 16),
|
||||||
|
Repositories: repos,
|
||||||
|
MaxBlobSize: int64(1024 * 1024),
|
||||||
|
CompressionLevel: 3,
|
||||||
|
AgeRecipients: []string{testAgePublicKey},
|
||||||
|
}
|
||||||
|
if tt.onVolume != nil {
|
||||||
|
cfg.DeviceNumber = func(info os.FileInfo) (uint64, bool) {
|
||||||
|
if slices.Contains(tt.onVolume, info.Name()) {
|
||||||
|
return 2, true
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = snapshot.NewScanner(cfg).Scan(ctx, scannedPath, snapshotID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
got, err := repos.Snapshots.GetMountPoints(ctx, snapshotID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, tt.want, got)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// automountFs is an in-memory filesystem with a volume at mountPoint
|
||||||
|
// that is mounted on first access: opening mountPoint to list it mounts
|
||||||
|
// the volume or, if it cannot be mounted, fails with "no such file or
|
||||||
|
// directory", as with the autofs daemon. Stat records the device an
|
||||||
|
// entry is on at that moment, as a real stat does: unmountedDevice for
|
||||||
|
// mountPoint until the volume is mounted; the volume's, 2, for
|
||||||
|
// mountPoint once it is and for everything in it; 1 for everything else.
|
||||||
|
type automountFs struct {
|
||||||
|
afero.Fs
|
||||||
|
|
||||||
|
mountPoint string
|
||||||
|
unmountedDevice uint64
|
||||||
|
canMount bool
|
||||||
|
mounted bool
|
||||||
|
}
|
||||||
|
|
||||||
|
//nolint:ireturn // afero.Fs.Open is defined to return the interface.
|
||||||
|
func (fs *automountFs) Open(name string) (afero.File, error) {
|
||||||
|
if name == fs.mountPoint && !fs.canMount {
|
||||||
|
return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT}
|
||||||
|
}
|
||||||
|
|
||||||
|
if name == fs.mountPoint {
|
||||||
|
fs.mounted = true
|
||||||
|
}
|
||||||
|
|
||||||
|
return fs.Fs.Open(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fs *automountFs) Stat(name string) (os.FileInfo, error) {
|
||||||
|
info, err := fs.Fs.Stat(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
device := uint64(1)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case name == fs.mountPoint && !fs.mounted:
|
||||||
|
device = fs.unmountedDevice
|
||||||
|
case name == fs.mountPoint || strings.HasPrefix(name, fs.mountPoint+"/"):
|
||||||
|
device = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
return statWithDevice{FileInfo: info, device: device}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// statWithDevice is an entry automountFs.Stat looked up, with the device
|
||||||
|
// it was on then.
|
||||||
|
type statWithDevice struct {
|
||||||
|
os.FileInfo
|
||||||
|
|
||||||
|
device uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
// deviceAtLookup returns the device automountFs.Stat recorded for info.
|
||||||
|
func deviceAtLookup(info os.FileInfo) (uint64, bool) {
|
||||||
|
stat, ok := info.(statWithDevice)
|
||||||
|
|
||||||
|
return stat.device, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// A volume mounted on first access is mounted when the walk lists its
|
||||||
|
// mount point. Until then the mount point is on the automounter's own
|
||||||
|
// device (a systemd automount) or on its parent's (an autofs map that
|
||||||
|
// shows its mount points before mounting them). Either way only the
|
||||||
|
// mount point is recorded, by the backup that mounts the volume and by a
|
||||||
|
// later one that finds it mounted. Listing an automount point whose
|
||||||
|
// volume cannot be mounted fails; it is not recorded, because the walk
|
||||||
|
// finds no entry in it. See https://git.eeqj.de/sneak/vaultik/issues/395.
|
||||||
|
func TestScanRecordsOnlyTheMountPointOfAnAutomountedVolume(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const scannedPath = "/data/source"
|
||||||
|
|
||||||
|
mountPoint := scannedPath + "/nas"
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
unmountedDevice uint64
|
||||||
|
canMount bool
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "on the automounter's device until listed",
|
||||||
|
unmountedDevice: 3, canMount: true, want: []string{mountPoint},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "on its parent's device until listed",
|
||||||
|
unmountedDevice: 1, canMount: true, want: []string{mountPoint},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "volume that cannot be mounted",
|
||||||
|
unmountedDevice: 1, canMount: false, want: nil,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
fs := &automountFs{
|
||||||
|
Fs: afero.NewMemMapFs(), mountPoint: mountPoint,
|
||||||
|
unmountedDevice: tt.unmountedDevice, canMount: tt.canMount,
|
||||||
|
}
|
||||||
|
|
||||||
|
require.NoError(t, fs.MkdirAll(mountPoint+"/photos", 0o755))
|
||||||
|
|
||||||
|
for _, path := range []string{
|
||||||
|
scannedPath + "/notes.txt", mountPoint + "/photos/a.jpg",
|
||||||
|
} {
|
||||||
|
require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0o644))
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := database.NewTestDB()
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = db.Close() })
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
for _, snapshotID := range []string{"first", "later"} {
|
||||||
|
createTestSnapshotRecord(ctx, t, repos, snapshotID)
|
||||||
|
|
||||||
|
scanner := snapshot.NewScanner(snapshot.ScannerConfig{
|
||||||
|
FS: fs,
|
||||||
|
ChunkSize: int64(1024 * 16),
|
||||||
|
Repositories: repos,
|
||||||
|
MaxBlobSize: int64(1024 * 1024),
|
||||||
|
CompressionLevel: 3,
|
||||||
|
AgeRecipients: []string{testAgePublicKey},
|
||||||
|
DeviceNumber: deviceAtLookup,
|
||||||
|
})
|
||||||
|
|
||||||
|
_, err = scanner.Scan(ctx, scannedPath, snapshotID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
got, err := repos.Snapshots.GetMountPoints(ctx, snapshotID)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, tt.want, got, "mount points of the %s backup", snapshotID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -56,24 +56,27 @@ const (
|
|||||||
|
|
||||||
// ProgressStats holds atomic counters for progress tracking
|
// ProgressStats holds atomic counters for progress tracking
|
||||||
type ProgressStats struct {
|
type ProgressStats struct {
|
||||||
FilesScanned atomic.Int64 // Total files seen during scan (includes skipped)
|
FilesScanned atomic.Int64 // Total files seen during scan (includes skipped)
|
||||||
FilesProcessed atomic.Int64 // Files actually processed in phase 2
|
FilesProcessed atomic.Int64 // Files actually processed in phase 2
|
||||||
FilesSkipped atomic.Int64 // Files skipped due to no changes
|
FilesSkipped atomic.Int64 // Files skipped due to no changes
|
||||||
BytesScanned atomic.Int64 // Bytes from new/changed files only
|
BytesScanned atomic.Int64 // Bytes from new/changed files only
|
||||||
BytesSkipped atomic.Int64 // Bytes from unchanged files
|
BytesSkipped atomic.Int64 // Bytes from unchanged files
|
||||||
BytesProcessed atomic.Int64 // Actual bytes processed (for ETA calculation)
|
BytesProcessed atomic.Int64 // Actual bytes processed (for ETA calculation)
|
||||||
ChunksCreated atomic.Int64
|
ChunksCreated atomic.Int64
|
||||||
BlobsCreated atomic.Int64
|
BlobsCreated atomic.Int64
|
||||||
BlobsUploaded atomic.Int64
|
BlobsUploaded atomic.Int64
|
||||||
BytesUploaded atomic.Int64
|
BytesUploaded atomic.Int64
|
||||||
UploadDurationMs atomic.Int64 // Total milliseconds spent uploading
|
CurrentFile atomic.Value // stores string
|
||||||
CurrentFile atomic.Value // stores string
|
TotalSize atomic.Int64 // Size to process in the paths scanned so far
|
||||||
TotalSize atomic.Int64 // Total size to process (set after scan phase)
|
TotalFiles atomic.Int64 // Files to process in the paths scanned so far
|
||||||
TotalFiles atomic.Int64 // Total files to process in phase 2
|
StartTime time.Time
|
||||||
ProcessStartTime atomic.Value // stores time.Time when processing starts
|
mu sync.RWMutex
|
||||||
StartTime time.Time
|
lastDetailTime time.Time
|
||||||
mu sync.RWMutex
|
|
||||||
lastDetailTime time.Time
|
// Guarded by mu: when the last scan phase ended, and
|
||||||
|
// BytesProcessed at that moment.
|
||||||
|
processStartTime time.Time
|
||||||
|
processStartBytes int64
|
||||||
|
|
||||||
// Upload tracking
|
// Upload tracking
|
||||||
CurrentUpload atomic.Value // stores *UploadInfo
|
CurrentUpload atomic.Value // stores *UploadInfo
|
||||||
@@ -149,10 +152,36 @@ func (pr *ProgressReporter) GetStats() *ProgressStats {
|
|||||||
return pr.stats
|
return pr.stats
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTotalSize sets the total size to process (after scan phase)
|
// AddTotalSize adds the size one path of the snapshot has to process to
|
||||||
func (pr *ProgressReporter) SetTotalSize(size int64) {
|
// the total, once that path's scan phase is done, and starts measuring
|
||||||
pr.stats.TotalSize.Store(size)
|
// the processing rate again. The processed counts run across every path,
|
||||||
pr.stats.ProcessStartTime.Store(time.Now().UTC())
|
// so the total does too. Restarting the rate keeps a path's scan phase,
|
||||||
|
// which processes nothing, out of the rate while that path is processed.
|
||||||
|
// During a later path's scan phase the rate is still the previous
|
||||||
|
// path's, and falls as that scan goes on.
|
||||||
|
func (pr *ProgressReporter) AddTotalSize(size int64) {
|
||||||
|
pr.stats.TotalSize.Add(size)
|
||||||
|
|
||||||
|
pr.stats.mu.Lock()
|
||||||
|
defer pr.stats.mu.Unlock()
|
||||||
|
|
||||||
|
pr.stats.processStartTime = time.Now().UTC()
|
||||||
|
pr.stats.processStartBytes = pr.stats.BytesProcessed.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// processRate returns the bytes processed per second since the last scan
|
||||||
|
// phase ended, or 0 before the first path's scan phase is done.
|
||||||
|
func (s *ProgressStats) processRate() float64 {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
|
||||||
|
if s.processStartTime.IsZero() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
processed := s.BytesProcessed.Load() - s.processStartBytes
|
||||||
|
|
||||||
|
return float64(processed) / time.Since(s.processStartTime).Seconds()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper functions
|
// Helper functions
|
||||||
@@ -231,9 +260,6 @@ func (pr *ProgressReporter) ReportUploadComplete(
|
|||||||
// Clear current upload
|
// Clear current upload
|
||||||
pr.stats.CurrentUpload.Store((*UploadInfo)(nil))
|
pr.stats.CurrentUpload.Store((*UploadInfo)(nil))
|
||||||
|
|
||||||
// Add to total upload duration
|
|
||||||
pr.stats.UploadDurationMs.Add(duration.Milliseconds())
|
|
||||||
|
|
||||||
// Calculate speed
|
// Calculate speed
|
||||||
if duration < time.Millisecond {
|
if duration < time.Millisecond {
|
||||||
duration = time.Millisecond
|
duration = time.Millisecond
|
||||||
@@ -361,19 +387,12 @@ func (pr *ProgressReporter) printSummaryStatus() {
|
|||||||
// Calculate ETA if we have total size and are processing
|
// Calculate ETA if we have total size and are processing
|
||||||
etaStr := ""
|
etaStr := ""
|
||||||
|
|
||||||
if totalSize > 0 && bytesProcessed > 0 {
|
processRate := pr.stats.processRate()
|
||||||
processStart, ok := pr.stats.ProcessStartTime.Load().(time.Time)
|
if totalSize > 0 && processRate > 0 {
|
||||||
if ok && !processStart.IsZero() {
|
remainingBytes := totalSize - bytesProcessed
|
||||||
processElapsed := time.Since(processStart)
|
remainingSeconds := float64(remainingBytes) / processRate
|
||||||
|
eta := time.Duration(remainingSeconds * float64(time.Second))
|
||||||
rate := float64(bytesProcessed) / processElapsed.Seconds()
|
etaStr = " | ETA: " + formatDuration(eta)
|
||||||
if rate > 0 {
|
|
||||||
remainingBytes := totalSize - bytesProcessed
|
|
||||||
remainingSeconds := float64(remainingBytes) / rate
|
|
||||||
eta := time.Duration(remainingSeconds * float64(time.Second))
|
|
||||||
etaStr = " | ETA: " + formatDuration(eta)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rate := float64(bytesScanned+bytesSkipped) / elapsed.Seconds()
|
rate := float64(bytesScanned+bytesSkipped) / elapsed.Seconds()
|
||||||
@@ -425,25 +444,18 @@ func (pr *ProgressReporter) printDetailedStatus() {
|
|||||||
log.Info("Elapsed time", "duration", formatDuration(elapsed))
|
log.Info("Elapsed time", "duration", formatDuration(elapsed))
|
||||||
|
|
||||||
// Calculate and show ETA if we have data
|
// Calculate and show ETA if we have data
|
||||||
if totalSize > 0 && bytesProcessed > 0 {
|
processRate := pr.stats.processRate()
|
||||||
processStart, ok := pr.stats.ProcessStartTime.Load().(time.Time)
|
if totalSize > 0 && processRate > 0 {
|
||||||
if ok && !processStart.IsZero() {
|
remainingBytes := totalSize - bytesProcessed
|
||||||
processElapsed := time.Since(processStart)
|
remainingSeconds := float64(remainingBytes) / processRate
|
||||||
|
eta := time.Duration(remainingSeconds * float64(time.Second))
|
||||||
processRate := float64(bytesProcessed) / processElapsed.Seconds()
|
percentComplete := float64(bytesProcessed) / float64(totalSize) * percentScale
|
||||||
if processRate > 0 {
|
log.Info("Overall progress",
|
||||||
remainingBytes := totalSize - bytesProcessed
|
"percent", fmt.Sprintf("%.1f%%", percentComplete),
|
||||||
remainingSeconds := float64(remainingBytes) / processRate
|
"processed", humanize.Bytes(safeUint64(bytesProcessed)),
|
||||||
eta := time.Duration(remainingSeconds * float64(time.Second))
|
"total", humanize.Bytes(safeUint64(totalSize)),
|
||||||
percentComplete := float64(bytesProcessed) / float64(totalSize) * percentScale
|
"rate", humanize.Bytes(uint64(processRate))+"/s",
|
||||||
log.Info("Overall progress",
|
"eta", formatDuration(eta))
|
||||||
"percent", fmt.Sprintf("%.1f%%", percentComplete),
|
|
||||||
"processed", humanize.Bytes(safeUint64(bytesProcessed)),
|
|
||||||
"total", humanize.Bytes(safeUint64(totalSize)),
|
|
||||||
"rate", humanize.Bytes(uint64(processRate))+"/s",
|
|
||||||
"eta", formatDuration(eta))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info("Files processed",
|
log.Info("Files processed",
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
//nolint:testpackage // exercises the unexported processRate helper
|
||||||
|
package snapshot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestProcessRateNotLoweredByLaterScanPhase feeds the reporter two paths
|
||||||
|
// that each take 10 seconds to process, the second after a 30-second scan
|
||||||
|
// phase. That scan phase processes nothing, so the rate while the second
|
||||||
|
// path is processed must be that path's own.
|
||||||
|
func TestProcessRateNotLoweredByLaterScanPhase(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const (
|
||||||
|
pathSize = 1000
|
||||||
|
processingTime = 10 * time.Second
|
||||||
|
scanTime = 30 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// Never started, but Stop releases its tickers and signal handler.
|
||||||
|
progress := NewProgressReporter()
|
||||||
|
defer progress.Stop()
|
||||||
|
|
||||||
|
stats := progress.GetStats()
|
||||||
|
|
||||||
|
// Moves the processing start time back instead of sleeping.
|
||||||
|
elapse := func(d time.Duration) {
|
||||||
|
stats.mu.Lock()
|
||||||
|
defer stats.mu.Unlock()
|
||||||
|
|
||||||
|
stats.processStartTime = stats.processStartTime.Add(-d)
|
||||||
|
}
|
||||||
|
|
||||||
|
progress.AddTotalSize(pathSize)
|
||||||
|
stats.BytesProcessed.Add(pathSize)
|
||||||
|
elapse(processingTime)
|
||||||
|
|
||||||
|
elapse(scanTime)
|
||||||
|
progress.AddTotalSize(pathSize)
|
||||||
|
stats.BytesProcessed.Add(pathSize)
|
||||||
|
elapse(processingTime)
|
||||||
|
|
||||||
|
want := pathSize / processingTime.Seconds()
|
||||||
|
got := stats.processRate()
|
||||||
|
|
||||||
|
// The test's own run time adds to the elapsed time, so got is a hair
|
||||||
|
// under want.
|
||||||
|
if got > want || got < want*0.99 {
|
||||||
|
t.Errorf("rate while the second path is processed is %.1f bytes/s, "+
|
||||||
|
"want %.1f", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package snapshot_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/afero"
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
"sneak.berlin/go/vaultik/internal/snapshot"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestProgressPercentWithSecondPathSmaller backs up two paths with one
|
||||||
|
// scanner, as a snapshot with two paths does, the second path smaller
|
||||||
|
// than the first. The progress line divides the bytes processed by the
|
||||||
|
// total size, so both must count both paths to stay within 100%.
|
||||||
|
func TestProgressPercentWithSecondPathSmaller(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
fs := afero.NewMemMapFs()
|
||||||
|
files := map[string]string{
|
||||||
|
"/large/one.txt": strings.Repeat("1", 4000),
|
||||||
|
"/large/two.txt": strings.Repeat("2", 4000),
|
||||||
|
"/small/three.txt": strings.Repeat("3", 1000),
|
||||||
|
}
|
||||||
|
|
||||||
|
for path, content := range files {
|
||||||
|
err := fs.MkdirAll(filepath.Dir(path), 0755)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("mkdir: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = afero.WriteFile(fs, path, []byte(content), 0644)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("write %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := database.NewTestDB()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create test db: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
cerr := db.Close()
|
||||||
|
if cerr != nil {
|
||||||
|
t.Errorf("close db: %v", cerr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
repos := database.NewRepositories(db)
|
||||||
|
|
||||||
|
scanner := snapshot.NewScanner(snapshot.ScannerConfig{
|
||||||
|
FS: fs,
|
||||||
|
ChunkSize: int64(1024 * 16),
|
||||||
|
Repositories: repos,
|
||||||
|
MaxBlobSize: int64(1024 * 1024),
|
||||||
|
CompressionLevel: 3,
|
||||||
|
AgeRecipients: []string{testAgePublicKey},
|
||||||
|
EnableProgress: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Never started, but Stop releases its tickers and signal handler.
|
||||||
|
progress := scanner.GetProgress()
|
||||||
|
defer progress.Stop()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
snapshotID := "test-snapshot-progress"
|
||||||
|
createTestSnapshotRecord(ctx, t, repos, snapshotID)
|
||||||
|
|
||||||
|
for _, path := range []string{"/large", "/small"} {
|
||||||
|
_, err := scanner.Scan(ctx, path, snapshotID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("scanning %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stats := progress.GetStats()
|
||||||
|
|
||||||
|
// With both paths counted, the percentage must not exceed 100%.
|
||||||
|
percent := float64(stats.BytesProcessed.Load()) /
|
||||||
|
float64(stats.TotalSize.Load()) * 100
|
||||||
|
if percent > 100 {
|
||||||
|
t.Errorf("progress after both paths is %.1f%%, want at most 100%%",
|
||||||
|
percent)
|
||||||
|
}
|
||||||
|
|
||||||
|
if stats.FilesProcessed.Load() != stats.TotalFiles.Load() {
|
||||||
|
t.Errorf("progress after both paths is %d of %d files, want all",
|
||||||
|
stats.FilesProcessed.Load(), stats.TotalFiles.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
+585
-261
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
|||||||
|
//nolint:testpackage // exercises the unexported countNonDirectories helper
|
||||||
|
package snapshot
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"sneak.berlin/go/vaultik/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The walk counts regular files and symlinks, not directories, so the
|
||||||
|
// estimate of its count made from the local index's records leaves the
|
||||||
|
// directories out. See https://git.eeqj.de/sneak/vaultik/issues/305.
|
||||||
|
func TestCountNonDirectories(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
known := map[string]*database.File{
|
||||||
|
"/src": {Mode: uint32(os.ModeDir | 0o755)},
|
||||||
|
"/src/sub": {Mode: uint32(os.ModeDir | 0o755)},
|
||||||
|
"/src/a.txt": {Mode: 0o644},
|
||||||
|
"/src/link": {Mode: uint32(os.ModeSymlink | 0o777), LinkTarget: "a.txt"},
|
||||||
|
}
|
||||||
|
|
||||||
|
got := countNonDirectories(known)
|
||||||
|
if got != 2 {
|
||||||
|
t.Errorf("countNonDirectories = %d, want 2", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user