mirror of
https://github.com/restic/restic.git
synced 2026-12-04 15:44:46 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6b8187e10 | ||
|
|
b21617d3dc | ||
|
|
ed922942fc | ||
|
|
9a2accfdde | ||
|
|
337b8f15ab | ||
|
|
06ac4df5a9 | ||
|
|
1c55b6cec7 | ||
|
|
71f804a929 | ||
|
|
3f52603ef2 | ||
|
|
33b2785d90 | ||
|
|
12073885f7 | ||
|
|
4a9941c1e1 | ||
|
|
0cd0df6346 | ||
|
|
7a1ac9bda0 | ||
|
|
03e4060791 | ||
|
|
1227b2ab7e | ||
|
|
152c2720bb | ||
|
|
d156f3b5f1 | ||
|
|
ab38c42497 | ||
|
|
fc85e9eb9b | ||
|
|
79b676aa98 | ||
|
|
057a5c65d2 | ||
|
|
84a75fc09e | ||
|
|
76925aeb63 | ||
|
|
2518cd4a75 | ||
|
|
584ec23160 | ||
|
|
15e1e33a19 | ||
|
|
0e50a959d5 | ||
|
|
43f00195bd | ||
|
|
5769abd0ea | ||
|
|
93ed73cdd2 | ||
|
|
1f76eb6a2e | ||
|
|
e63cb63ba6 | ||
|
|
1d0668f656 | ||
|
|
4ea95e8de3 | ||
|
|
2f0fbaa136 | ||
|
|
780cb97523 | ||
|
|
00ab2da0e4 | ||
|
|
d7b184f4ce | ||
|
|
00b2f19c3d | ||
|
|
814ef968d9 | ||
|
|
4797768ba9 | ||
|
|
885519b1ba | ||
|
|
f25ec9a5ab | ||
|
|
8f4873d5d7 | ||
|
|
1d80020e28 | ||
|
|
79f17ac895 | ||
|
|
30de2d9211 | ||
|
|
4718be1aee | ||
|
|
2991718398 | ||
|
|
3446754c41 | ||
|
|
b7e20f3aa2 | ||
|
|
8af83234f2 | ||
|
|
ea9a3f6801 | ||
|
|
69ddfc4676 | ||
|
|
a8492c778e | ||
|
|
e6a3b7b299 | ||
|
|
d7cdb55ebf | ||
|
|
25751a5856 | ||
|
|
7745986c6d | ||
|
|
b35ef9c203 | ||
|
|
09cf44557e | ||
|
|
4729a99ebf | ||
|
|
db81226395 | ||
|
|
e2a3f7bd75 | ||
|
|
d66a3f4fe7 |
No files matched your search
@@ -29,7 +29,7 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
|
||||
+2
-2
@@ -96,8 +96,8 @@ restic users. The changes are ordered by importance.
|
||||
Restic now rejects trees whose node names are not strictly increasing during
|
||||
restore and reports an error instead of restoring such a snapshot.
|
||||
|
||||
Thanks to Mario Ramos (@marrionesa), Zachariah Mithani (AploSec), Manuel Riel
|
||||
(@m3nu) and calif.io for reporting this.
|
||||
Thanks to Mario Ramos (@marrionesa), calif.io, Zachariah Mithani (AploSec) and
|
||||
Manuel Riel (@m3nu) for reporting this.
|
||||
|
||||
https://github.com/restic/restic/issues/22180
|
||||
https://github.com/restic/restic/pull/22190
|
||||
|
||||
@@ -6,8 +6,8 @@ A tree containing a symlink and a directory with the same name could let
|
||||
Restic now rejects trees whose node names are not strictly increasing
|
||||
during restore and reports an error instead of restoring such a snapshot.
|
||||
|
||||
Thanks to Mario Ramos (@marrionesa), Zachariah Mithani (AploSec),
|
||||
Manuel Riel (@m3nu) and calif.io for reporting this.
|
||||
Thanks to Mario Ramos (@marrionesa), calif.io, Zachariah Mithani (AploSec) and
|
||||
Manuel Riel (@m3nu) for reporting this.
|
||||
|
||||
https://github.com/restic/restic/issues/22180
|
||||
https://github.com/restic/restic/pull/22190
|
||||
@@ -0,0 +1,32 @@
|
||||
Enhancement: More flexible formats for backup and rewrite time related options
|
||||
|
||||
Restic backup --time allowed in the past only the format "2006-01-02 15:04:05".
|
||||
|
||||
`backup --time` and `rewrite --new-time` can now use the following range of date/time
|
||||
formats:
|
||||
|
||||
```
|
||||
y-m-d
|
||||
y-m-d HH:MM
|
||||
y-m-d HH:MM:SS
|
||||
|
||||
d.m.y
|
||||
d.m.y HH:MM
|
||||
d.m.y HH:MM:SS
|
||||
```
|
||||
|
||||
With additional modifiers for timezone name and timezone offset:
|
||||
|
||||
```
|
||||
y-m-d HH:MM:SS MST
|
||||
y-m-d HH:MM:SS -0700
|
||||
y-m-d HH:MM:SS-0700
|
||||
|
||||
d.m.y HH:MM:SS MST
|
||||
d.m.y HH:MM:SS -0700
|
||||
d.m.y HH:MM:SS-0700
|
||||
```
|
||||
|
||||
https://github.com/restic/restic/issues/2065
|
||||
https://github.com/restic/restic/pull/21867
|
||||
https://github.com/restic/restic/pull/22220
|
||||
@@ -0,0 +1,12 @@
|
||||
Enhancement: Add options to configure SSH keepalive for SFTP backend
|
||||
|
||||
SFTP connections could be interrupted when no data was sent for a long time,
|
||||
for example while restic processes large amounts of unchanged data. The new
|
||||
`sftp.server-alive-interval` and `sftp.server-alive-count-max` options set the
|
||||
corresponding `ServerAliveInterval` and `ServerAliveCountMax` SSH options to
|
||||
keep the connection alive. If unset, the values from the SSH configuration
|
||||
are used.
|
||||
|
||||
https://github.com/restic/restic/issues/5313
|
||||
https://github.com/restic/restic/pull/5314
|
||||
https://forum.restic.net/t/robustness-of-repository-issue-resolved/1475
|
||||
@@ -0,0 +1,12 @@
|
||||
Bugfix: Fix damaged repository after concurrent `init` on REST backend
|
||||
|
||||
When two `restic init` runs raced against the same empty repository on
|
||||
the REST backend, the repository could end up with a leftover key file
|
||||
that did not belong to the stored config. Clients that happened to pick
|
||||
that key failed with a "config or key ... is damaged" error.
|
||||
|
||||
Restic now stores the config file before the key file during `init`, so
|
||||
the losing run no longer leaves a key file behind.
|
||||
|
||||
https://github.com/restic/restic/issues/5717
|
||||
https://github.com/restic/restic/pull/21944
|
||||
@@ -0,0 +1,5 @@
|
||||
Enhancement: Add version-specific docs URLs to help output
|
||||
|
||||
Updated the help message to use version-specific documentation URLs or else just use latest.
|
||||
|
||||
https://github.com/restic/restic/pull/21795
|
||||
@@ -0,0 +1,9 @@
|
||||
Enhancement: Filter out-of-order entries in `check`, `dump` and `mount`
|
||||
|
||||
Only the `restore` command filtered out-of-order directory entries. Now,
|
||||
also the `dump` and `mount` commands filter out-of-order directory entries.
|
||||
The `check` command warns about such damaged directories. The `repair snapshots`
|
||||
command can now remove such invalid directory entries while keeping the
|
||||
remaining snapshot.
|
||||
|
||||
https://github.com/restic/restic/pull/22209
|
||||
@@ -0,0 +1,13 @@
|
||||
Bugfix: Quote non-printable characters in text output
|
||||
|
||||
Filenames and other printed text, such as hostnames, tags, and error
|
||||
messages, could contain newlines or terminal control characters. Restic
|
||||
printed many of those strings verbatim, which could mangle the status output
|
||||
or change the terminal state.
|
||||
|
||||
Text output now quotes strings that contain non-printable or invalid UTF-8
|
||||
characters. JSON output escapes control and format characters using standard
|
||||
JSON escape sequences so it remains valid and decodes identically. The `cat`
|
||||
command and `dump` commands still output data verbatim.
|
||||
|
||||
https://github.com/restic/restic/pull/22216
|
||||
@@ -0,0 +1,5 @@
|
||||
Enhancement: Speed up index decoding by 50%
|
||||
|
||||
Loading the repository index is now roughly 50% faster.
|
||||
|
||||
https://github.com/restic/restic/pull/22221
|
||||
@@ -0,0 +1,15 @@
|
||||
Bugfix: Correctly apply a `--tag` filter that contains an empty tag
|
||||
|
||||
The empty tag in a `--tag` or `--keep-tag` list selects snapshots without
|
||||
any tags. Restic stopped looking at a tag list once it reached the empty
|
||||
tag, so a list like `,foo` matched every untagged snapshot instead of
|
||||
matching nothing, while the equivalent `foo,` matched nothing. For
|
||||
`forget` that meant snapshots outside the filter were considered for
|
||||
removal.
|
||||
|
||||
Restic now requires an empty tag to be the only tag in its list. A list
|
||||
that combines it with another tag, such as `,foo` or `foo,`, is rejected
|
||||
when the command line is parsed, instead of quietly selecting either the
|
||||
wrong snapshots or none at all.
|
||||
|
||||
https://github.com/restic/restic/pull/22222
|
||||
@@ -0,0 +1,6 @@
|
||||
Enhancement: snapshots: Add --reverse option to reverse sort order
|
||||
|
||||
The `snapshots` command now supports a `--reverse` option, which lists
|
||||
snapshots newest first instead of the default oldest first.
|
||||
|
||||
https://github.com/restic/restic/pull/5677
|
||||
@@ -187,9 +187,9 @@ func filterExisting(items []string, warnf func(msg string, args ...any)) (result
|
||||
_, err := fs.Lstat(item)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
warnf("%v does not exist, skipping\n", item)
|
||||
warnf("%v does not exist, skipping\n", ui.Quote(item))
|
||||
} else {
|
||||
warnf("%v cannot be accessed, skipping\n", item)
|
||||
warnf("%v cannot be accessed, skipping\n", ui.Quote(item))
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -424,7 +424,7 @@ func collectTargets(opts BackupOptions, args []string, warnf func(msg string, ar
|
||||
var expanded []string
|
||||
expanded, err := filepath.Glob(line)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("pattern: %s: %w", line, err)
|
||||
return nil, fmt.Errorf("pattern: %q: %w", line, err)
|
||||
}
|
||||
if len(expanded) == 0 {
|
||||
warnf("pattern %q does not match any files, skipping\n", line)
|
||||
@@ -528,7 +528,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
|
||||
timeStamp := time.Now()
|
||||
backupStart := timeStamp
|
||||
if opts.TimeStamp != "" {
|
||||
timeStamp, err = time.ParseInLocation(global.TimeFormat, opts.TimeStamp, time.Local)
|
||||
timeStamp, err = ui.ParseTime(opts.TimeStamp)
|
||||
if err != nil {
|
||||
return errors.Fatalf("error in time option: %v", err)
|
||||
}
|
||||
@@ -646,7 +646,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
|
||||
sc.Result = progressReporter.ReportTotal
|
||||
|
||||
if !gopts.JSON {
|
||||
printer.V("start scan on %v", targets)
|
||||
printer.V("start scan on %v", ui.QuoteSlice(targets))
|
||||
}
|
||||
wg.Go(func() error { return sc.Scan(cancelCtx, targets) })
|
||||
}
|
||||
@@ -692,7 +692,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
|
||||
}
|
||||
|
||||
if !gopts.JSON {
|
||||
printer.V("start backup on %v", targets)
|
||||
printer.V("start backup on %v", ui.QuoteSlice(targets))
|
||||
}
|
||||
_, id, summary, err := arch.Snapshot(ctx, targets, snapshotOpts)
|
||||
|
||||
|
||||
+21
-12
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
@@ -92,16 +93,17 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
|
||||
return err
|
||||
}
|
||||
|
||||
printer.S(string(buf))
|
||||
return nil
|
||||
return writeWithNewline(term.OutputRaw(), buf)
|
||||
|
||||
case "index":
|
||||
buf, err := repo.LoadUnpacked(ctx, restic.IndexFile, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
printer.S(string(buf))
|
||||
return nil
|
||||
_, err = term.OutputRaw().Write(buf)
|
||||
return err
|
||||
|
||||
case "snapshot":
|
||||
sn, _, err := data.FindSnapshot(ctx, repo, repo, args[1])
|
||||
if err != nil {
|
||||
@@ -113,8 +115,8 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
|
||||
return err
|
||||
}
|
||||
|
||||
printer.S(string(buf))
|
||||
return nil
|
||||
return writeWithNewline(term.OutputRaw(), buf)
|
||||
|
||||
case "key":
|
||||
key, err := repository.LoadKey(ctx, repo, id)
|
||||
if err != nil {
|
||||
@@ -126,16 +128,16 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
|
||||
return err
|
||||
}
|
||||
|
||||
printer.S(string(buf))
|
||||
return nil
|
||||
return writeWithNewline(term.OutputRaw(), buf)
|
||||
|
||||
case "masterkey":
|
||||
buf, err := json.MarshalIndent(repo.Key(), "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
printer.S(string(buf))
|
||||
return nil
|
||||
return writeWithNewline(term.OutputRaw(), buf)
|
||||
|
||||
case "lock":
|
||||
lock, err := repository.LoadLock(ctx, repo, id)
|
||||
if err != nil {
|
||||
@@ -147,8 +149,7 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
|
||||
return err
|
||||
}
|
||||
|
||||
printer.S(string(buf))
|
||||
return nil
|
||||
return writeWithNewline(term.OutputRaw(), buf)
|
||||
|
||||
case "pack":
|
||||
buf, err := repo.LoadRaw(ctx, restic.PackFile, id)
|
||||
@@ -214,3 +215,11 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
|
||||
return errors.Fatal("invalid type")
|
||||
}
|
||||
}
|
||||
|
||||
func writeWithNewline(w io.Writer, buf []byte) error {
|
||||
if _, err := w.Write(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := w.Write([]byte{'\n'})
|
||||
return err
|
||||
}
|
||||
@@ -97,6 +97,10 @@ func NewChange(path string, mode string) *Change {
|
||||
return &Change{MessageType: "change", Path: path, Modifier: mode}
|
||||
}
|
||||
|
||||
func printTextDiffChange(S func(string, ...any), change *Change) {
|
||||
S("%-5s%v", change.Modifier, ui.Quote(change.Path))
|
||||
}
|
||||
|
||||
// DiffStat collects stats for all types of items.
|
||||
type DiffStat struct {
|
||||
Files int `json:"files"`
|
||||
@@ -412,7 +416,7 @@ func runDiff(ctx context.Context, opts DiffOptions, gopts global.Options, args [
|
||||
opts: opts,
|
||||
printError: printer.E,
|
||||
printChange: func(change *Change) {
|
||||
printer.S("%-5s%v", change.Modifier, change.Path)
|
||||
printTextDiffChange(printer.S, change)
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
"github.com/restic/restic/internal/ui/progress"
|
||||
)
|
||||
|
||||
func TestPrintTextDiffChangeQuotesPath(t *testing.T) {
|
||||
term := &ui.MockTerminal{}
|
||||
printer := progress.NewTerminalPrinter(false, 1, term)
|
||||
printTextDiffChange(printer.S, NewChange("dir\nfile", "+"))
|
||||
rtest.Equals(t, []string{"+ " + strconv.Quote("dir\nfile")}, term.Output)
|
||||
|
||||
term.Output = nil
|
||||
printTextDiffChange(printer.S, NewChange("/ordinary/file", "+"))
|
||||
rtest.Equals(t, []string{"+ /ordinary/file"}, term.Output)
|
||||
}
|
||||
+20
-1
@@ -93,8 +93,16 @@ func printFromTree(ctx context.Context, tree data.TreeNodeIterator, repo restic.
|
||||
|
||||
item := filepath.Join(prefix, pathComponents[0])
|
||||
l := len(pathComponents)
|
||||
for it := range tree {
|
||||
// Track the first out-of-order node for the requested name.
|
||||
var skipped error
|
||||
for it := range data.EnforceTreeOrder(tree) {
|
||||
if it.Error != nil {
|
||||
if errors.Is(it.Error, data.ErrTreeNotOrdered) {
|
||||
if skipped == nil && it.Node.Name == pathComponents[0] {
|
||||
skipped = it.Error
|
||||
}
|
||||
continue
|
||||
}
|
||||
return it.Error
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
@@ -129,6 +137,9 @@ func printFromTree(ctx context.Context, tree data.TreeNodeIterator, repo restic.
|
||||
}
|
||||
}
|
||||
}
|
||||
if skipped != nil {
|
||||
return fmt.Errorf("path %q not found in snapshot: %w", item, skipped)
|
||||
}
|
||||
return fmt.Errorf("path %q not found in snapshot", item)
|
||||
}
|
||||
|
||||
@@ -195,10 +206,18 @@ func runDump(ctx context.Context, opts DumpOptions, gopts global.Options, args [
|
||||
}
|
||||
|
||||
d := dump.New(opts.Archive, repo, outputFileWriter)
|
||||
totalErrors := 0
|
||||
d.Error = func(nodePath string, err error) {
|
||||
totalErrors++
|
||||
printer.E("ignoring error for %s: %s\n", ui.Quote(nodePath), err)
|
||||
}
|
||||
err = printFromTree(ctx, tree, repo, "/", splittedPath, d, canWriteArchiveFunc)
|
||||
if err != nil {
|
||||
return errors.Fatalf("cannot dump file: %v", err)
|
||||
}
|
||||
if totalErrors > 0 {
|
||||
return errors.Fatalf("ignored %d directory entries", totalErrors)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/dump"
|
||||
"github.com/restic/restic/internal/errors"
|
||||
"github.com/restic/restic/internal/repository"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
)
|
||||
|
||||
@@ -25,3 +32,43 @@ func TestDumpSplitPath(t *testing.T) {
|
||||
rtest.Equals(t, path.result, parts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintFromTreeSkipsUnorderedNodes(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
repo := repository.TestRepository(t)
|
||||
|
||||
var rootID restic.ID
|
||||
rtest.OK(t, repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
|
||||
rootID = data.TestSaveUnorderedSampleTree(t, ctx, uploader)
|
||||
return nil
|
||||
}))
|
||||
|
||||
load := func() data.TreeNodeIterator {
|
||||
t.Helper()
|
||||
tree, err := data.LoadTree(ctx, repo, rootID)
|
||||
rtest.OK(t, err)
|
||||
return tree
|
||||
}
|
||||
dumpFile := func(tree data.TreeNodeIterator, parts []string) (reported []string, err error) {
|
||||
t.Helper()
|
||||
d := dump.New("tar", repo, &bytes.Buffer{})
|
||||
d.Error = func(nodePath string, err error) {
|
||||
rtest.Assert(t, errors.Is(err, data.ErrTreeNotOrdered), "unexpected error %v", err)
|
||||
reported = append(reported, nodePath)
|
||||
}
|
||||
err = printFromTree(ctx, tree, repo, "/", parts, d, func() error { return nil })
|
||||
return reported, err
|
||||
}
|
||||
|
||||
reported, err := dumpFile(load(), []string{"a"})
|
||||
rtest.Assert(t, errors.Is(err, data.ErrTreeNotOrdered), "missing unordered file: %v", err)
|
||||
rtest.Assert(t, len(reported) == 0, "lookup failure was reported via Error: %v", reported)
|
||||
|
||||
reported, err = dumpFile(load(), []string{"z"})
|
||||
rtest.OK(t, err)
|
||||
rtest.Assert(t, len(reported) == 0, "in-order match reported unordered siblings: %v", reported)
|
||||
|
||||
reported, err = dumpFile(load(), []string{"missing"})
|
||||
rtest.Assert(t, err != nil && !errors.Is(err, data.ErrTreeNotOrdered), "missing path: %v", err)
|
||||
rtest.Assert(t, len(reported) == 0, "unrelated unordered nodes were reported: %v", reported)
|
||||
}
|
||||
+11
-35
@@ -103,30 +103,6 @@ type findPattern struct {
|
||||
ignoreCase bool
|
||||
}
|
||||
|
||||
var timeFormats = []string{
|
||||
"2006-01-02",
|
||||
"2006-01-02 15:04",
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02 15:04:05 -0700",
|
||||
"2006-01-02 15:04:05 MST",
|
||||
"02.01.2006",
|
||||
"02.01.2006 15:04",
|
||||
"02.01.2006 15:04:05",
|
||||
"02.01.2006 15:04:05 -0700",
|
||||
"02.01.2006 15:04:05 MST",
|
||||
"Mon Jan 2 15:04:05 -0700 MST 2006",
|
||||
}
|
||||
|
||||
func parseTime(str string) (time.Time, error) {
|
||||
for _, fmt := range timeFormats {
|
||||
if t, err := time.ParseInLocation(fmt, str, time.Local); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
|
||||
return time.Time{}, errors.Fatalf("unable to parse time: %q", str)
|
||||
}
|
||||
|
||||
type statefulOutput struct {
|
||||
ListLong bool
|
||||
HumanReadable bool
|
||||
@@ -183,7 +159,7 @@ func (s *statefulOutput) PrintPatternJSON(path string, node *data.Node) {
|
||||
if s.hits > 0 {
|
||||
_, _ = s.stdout.Write([]byte(","))
|
||||
}
|
||||
_, _ = s.stdout.Write(b)
|
||||
_, _ = io.WriteString(s.stdout, ui.EscapeControls(string(b)))
|
||||
s.hits++
|
||||
}
|
||||
|
||||
@@ -195,7 +171,7 @@ func (s *statefulOutput) PrintPatternNormal(path string, node *data.Node) {
|
||||
s.oldsn = s.newsn
|
||||
s.printer.P("Found matching entries in snapshot %s from %s", s.oldsn.ID().Str(), s.oldsn.Time.Local().Format(global.TimeFormat))
|
||||
}
|
||||
s.printer.S(formatNode(path, node, s.ListLong, s.HumanReadable))
|
||||
s.printer.S("%s", formatNode(path, node, s.ListLong, s.HumanReadable))
|
||||
}
|
||||
|
||||
func (s *statefulOutput) PrintPattern(path string, node *data.Node) {
|
||||
@@ -234,17 +210,17 @@ func (s *statefulOutput) PrintObjectJSON(kind, id, nodepath, treeID string, sn *
|
||||
if s.hits > 0 {
|
||||
_, _ = s.stdout.Write([]byte(","))
|
||||
}
|
||||
_, _ = s.stdout.Write(b)
|
||||
_, _ = io.WriteString(s.stdout, ui.EscapeControls(string(b)))
|
||||
s.hits++
|
||||
}
|
||||
|
||||
func (s *statefulOutput) PrintObjectNormal(kind, id, nodepath, treeID string, sn *data.Snapshot) {
|
||||
s.printer.S("Found %s %s", kind, id)
|
||||
if kind == "blob" {
|
||||
s.printer.S(" ... in file %s", nodepath)
|
||||
s.printer.S(" ... in file %s", ui.Quote(nodepath))
|
||||
s.printer.S(" (tree %s)", treeID)
|
||||
} else {
|
||||
s.printer.S(" ... path %s", nodepath)
|
||||
s.printer.S(" ... path %s", ui.Quote(nodepath))
|
||||
}
|
||||
s.printer.S(" ... in snapshot %s (%s)", sn.ID().Str(), sn.Time.Local().Format(global.TimeFormat))
|
||||
}
|
||||
@@ -530,7 +506,10 @@ func (f *Finder) indexPacksToBlobs(ctx context.Context, packIDs map[string]struc
|
||||
|
||||
// remember which packs were found in the index
|
||||
indexPackIDs := make(map[string]struct{})
|
||||
err := f.repo.ListBlobs(wctx, func(pb restic.PackBlob) {
|
||||
for pb := range f.repo.ListBlobs() {
|
||||
if err := wctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packID := pb.PackID()
|
||||
idStr := packID.String()
|
||||
// keep entry in packIDs as Each() returns individual index entries
|
||||
@@ -549,9 +528,6 @@ func (f *Finder) indexPacksToBlobs(ctx context.Context, packIDs map[string]struc
|
||||
f.addBlobHandle(pb.Handle())
|
||||
indexPackIDs[idStr] = struct{}{}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for id := range indexPackIDs {
|
||||
@@ -610,13 +586,13 @@ func runFind(ctx context.Context, opts FindOptions, gopts global.Options, args [
|
||||
}
|
||||
|
||||
if opts.Oldest != "" {
|
||||
if pat.oldest, err = parseTime(opts.Oldest); err != nil {
|
||||
if pat.oldest, err = ui.ParseTime(opts.Oldest); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if opts.Newest != "" {
|
||||
if pat.newest, err = parseTime(opts.Newest); err != nil {
|
||||
if pat.newest, err = ui.ParseTime(opts.Newest); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,15 +180,14 @@ func TestFindPackfile(t *testing.T) {
|
||||
|
||||
packID := restic.ID{}
|
||||
done := false
|
||||
err = repo.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
for pb := range repo.ListBlobs() {
|
||||
rtest.OK(t, ctx.Err())
|
||||
h := pb.Handle()
|
||||
if !done && h.Type == restic.TreeBlob {
|
||||
packID = pb.PackID()
|
||||
done = true
|
||||
}
|
||||
})
|
||||
|
||||
rtest.OK(t, err)
|
||||
}
|
||||
rtest.Assert(t, !packID.IsNull(), "expected a tree packfile ID")
|
||||
findOptions := FindOptions{PackID: true}
|
||||
results := testRunFind(t, true, findOptions, env.gopts, packID.String())
|
||||
@@ -238,14 +237,15 @@ func TestFindPackID(t *testing.T) {
|
||||
// load Index
|
||||
rtest.OK(t, repo.LoadIndex(ctx, restic.NoopTerminalCounterFactory))
|
||||
// go through all index entries and collect data and tree packfile(s)
|
||||
rtest.OK(t, repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
for blob := range repo.ListBlobs() {
|
||||
rtest.OK(t, ctx.Err())
|
||||
switch blob.Handle().Type {
|
||||
case restic.DataBlob:
|
||||
dataPackID = blob.PackID()
|
||||
case restic.TreeBlob:
|
||||
treePackID = blob.PackID()
|
||||
}
|
||||
}))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
"github.com/restic/restic/internal/ui/progress"
|
||||
)
|
||||
|
||||
func TestPrintObjectQuotesPath(t *testing.T) {
|
||||
term := &ui.MockTerminal{}
|
||||
out := &statefulOutput{
|
||||
printer: progress.NewTerminalPrinter(false, 1, term),
|
||||
}
|
||||
out.PrintObjectNormal("file", "abcd", "dir\nfile", "", &data.Snapshot{})
|
||||
|
||||
rtest.Equals(t, " ... path "+strconv.Quote("dir\nfile"), term.Output[1])
|
||||
for _, line := range term.Output {
|
||||
rtest.Assert(t, !strings.Contains(line, "\n"), "raw newline in %q", line)
|
||||
}
|
||||
|
||||
term = &ui.MockTerminal{}
|
||||
out.printer = progress.NewTerminalPrinter(false, 1, term)
|
||||
out.PrintObjectNormal("blob", "abcd", "/ordinary/file", "tree", &data.Snapshot{})
|
||||
rtest.Equals(t, " ... in file /ordinary/file", term.Output[1])
|
||||
}
|
||||
|
||||
type fakeSnapshotLoader struct{}
|
||||
|
||||
func (fakeSnapshotLoader) Connections() uint { return 1 }
|
||||
func (fakeSnapshotLoader) LoadUnpacked(_ context.Context, _ restic.FileType, _ restic.ID) ([]byte, error) {
|
||||
return []byte("{}"), nil
|
||||
}
|
||||
|
||||
func TestFindJSONEscapesControls(t *testing.T) {
|
||||
hostilePath := "/dir/c1\u009b2J_del\x7f_tag\U000e0067"
|
||||
sn, err := data.LoadSnapshot(t.Context(), fakeSnapshotLoader{}, restic.NewRandomID())
|
||||
rtest.OK(t, err)
|
||||
|
||||
t.Run("pattern", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
out := &statefulOutput{
|
||||
JSON: true,
|
||||
newsn: sn,
|
||||
printer: progress.NewTerminalPrinter(true, 1, &ui.MockTerminal{}),
|
||||
stdout: &buf,
|
||||
}
|
||||
out.PrintPatternJSON(hostilePath, &data.Node{Name: "file"})
|
||||
out.Finish()
|
||||
|
||||
got := buf.String()
|
||||
rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got)
|
||||
rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got)
|
||||
rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got)
|
||||
|
||||
var parsed []struct {
|
||||
Matches []struct {
|
||||
Path string `json:"path"`
|
||||
} `json:"matches"`
|
||||
}
|
||||
rtest.OK(t, json.Unmarshal(buf.Bytes(), &parsed))
|
||||
rtest.Equals(t, 1, len(parsed))
|
||||
rtest.Equals(t, 1, len(parsed[0].Matches))
|
||||
rtest.Equals(t, hostilePath, parsed[0].Matches[0].Path)
|
||||
})
|
||||
|
||||
t.Run("object", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
out := &statefulOutput{
|
||||
JSON: true,
|
||||
printer: progress.NewTerminalPrinter(true, 1, &ui.MockTerminal{}),
|
||||
stdout: &buf,
|
||||
}
|
||||
out.PrintObjectJSON("file", "abcd", hostilePath, "tree", sn)
|
||||
out.Finish()
|
||||
|
||||
got := buf.String()
|
||||
rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got)
|
||||
rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got)
|
||||
rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got)
|
||||
|
||||
var parsed []struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
rtest.OK(t, json.Unmarshal(buf.Bytes(), &parsed))
|
||||
rtest.Equals(t, 1, len(parsed))
|
||||
rtest.Equals(t, hostilePath, parsed[0].Path)
|
||||
})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
@@ -279,7 +280,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
|
||||
keep, remove, reasons := data.ApplyPolicy(snapshotGroup, policy)
|
||||
|
||||
if !policy.Empty() && len(keep) == 0 {
|
||||
return fmt.Errorf("refusing to delete last snapshot of snapshot group \"%v\"", key.String())
|
||||
return fmt.Errorf("refusing to delete last snapshot of snapshot group [%s]", key.String())
|
||||
}
|
||||
if len(keep) != 0 && !gopts.Quiet && !gopts.JSON {
|
||||
printer.P("keep %d snapshots:\n", len(keep))
|
||||
@@ -363,6 +364,13 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrintSnapshots prints a text table of the snapshots in list to stdout.
|
||||
// The list is sorted so that the newest snapshot is listed last.
|
||||
func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepReason, compact bool) error {
|
||||
sort.Stable(sort.Reverse(list))
|
||||
return printSnapshotsTable(stdout, list, reasons, compact)
|
||||
}
|
||||
|
||||
// ForgetGroup helps to print what is forgotten in JSON.
|
||||
type ForgetGroup struct {
|
||||
Tags []string `json:"tags"`
|
||||
|
||||
@@ -42,7 +42,7 @@ func TestRunForgetSafetyNet(t *testing.T) {
|
||||
KeepTags: data.TagLists{data.TagList{"invalid"}},
|
||||
GroupBy: data.SnapshotGroupByOptions{Host: true, Path: true},
|
||||
})
|
||||
rtest.Assert(t, strings.Contains(err.Error(), `refusing to delete last snapshot of snapshot group "host example, path`), "wrong error message got %v", err)
|
||||
rtest.Assert(t, strings.Contains(err.Error(), `refusing to delete last snapshot of snapshot group [host example, path`), "wrong error message got %v", err)
|
||||
|
||||
// disallow `forget --unsafe-allow-remove-all`
|
||||
err = testRunForgetMayFail(t, env.gopts, ForgetOptions{
|
||||
|
||||
@@ -87,7 +87,8 @@ func runInit(ctx context.Context, opts InitOptions, gopts global.Options, args [
|
||||
}
|
||||
|
||||
if !gopts.JSON {
|
||||
printer.P("created restic repository %v at %s", s.Config().ID[:10], location.StripPassword(gopts.Backends, gopts.Repo))
|
||||
id := s.Config().ID
|
||||
printer.P("created restic repository %v at %s", id.Str(), location.StripPassword(gopts.Backends, gopts.Repo))
|
||||
if opts.CopyChunkerParameters && chunkerPolynomial != nil {
|
||||
printer.P(" with chunker parameters copied from secondary repository")
|
||||
}
|
||||
@@ -99,7 +100,7 @@ func runInit(ctx context.Context, opts InitOptions, gopts global.Options, args [
|
||||
} else {
|
||||
status := initSuccess{
|
||||
MessageType: "initialized",
|
||||
ID: s.Config().ID,
|
||||
ID: s.Config().ID.String(),
|
||||
Repository: location.StripPassword(gopts.Backends, gopts.Repo),
|
||||
}
|
||||
return json.NewEncoder(gopts.Term.OutputWriter()).Encode(status)
|
||||
|
||||
@@ -99,6 +99,11 @@ func listKeys(ctx context.Context, s *repository.Repository, gopts global.Option
|
||||
return json.NewEncoder(gopts.Term.OutputWriter()).Encode(keys)
|
||||
}
|
||||
|
||||
for i := range keys {
|
||||
keys[i].UserName = ui.Quote(keys[i].UserName)
|
||||
keys[i].HostName = ui.Quote(keys[i].HostName)
|
||||
}
|
||||
|
||||
tab := table.New()
|
||||
tab.AddColumn(" ID", "{{if .Current}}*{{else}} {{end}}{{ .ShortID }}")
|
||||
tab.AddColumn("User", "{{ .UserName }}")
|
||||
|
||||
@@ -48,6 +48,10 @@ func parseIDsFromReader(t testing.TB, rd io.Reader) restic.IDs {
|
||||
}
|
||||
}
|
||||
|
||||
if err := sc.Err(); err != nil {
|
||||
t.Fatalf("failed to scan list output (parsed %d IDs before error): %v", len(IDs), err)
|
||||
}
|
||||
|
||||
return IDs
|
||||
}
|
||||
|
||||
@@ -71,9 +75,10 @@ func testListBlobs(t testing.TB, gopts global.Options) (blobSetFromIndex restic.
|
||||
|
||||
// get blobs from index
|
||||
blobSetFromIndex = restic.NewIDSet()
|
||||
rtest.OK(t, repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
for blob := range repo.ListBlobs() {
|
||||
rtest.OK(t, ctx.Err())
|
||||
blobSetFromIndex.Insert(blob.Handle().ID)
|
||||
}))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
|
||||
@@ -296,7 +296,7 @@ type textLsPrinter struct {
|
||||
}
|
||||
|
||||
func (p *textLsPrinter) Snapshot(sn *data.Snapshot) error {
|
||||
p.termPrinter.P("%v filtered by %v:", sn, p.dirs)
|
||||
p.termPrinter.P("%v filtered by %v:", sn, ui.QuoteSlice(p.dirs))
|
||||
return nil
|
||||
}
|
||||
func (p *textLsPrinter) NodeOutput(node lsNodeOutput, isPrefixDirectory bool) error {
|
||||
|
||||
@@ -154,7 +154,7 @@ func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args
|
||||
return err
|
||||
}
|
||||
|
||||
fuseMountName := fmt.Sprintf("restic:%s", repo.Config().ID[:10])
|
||||
fuseMountName := fmt.Sprintf("restic:%s", repo.Config().ID.String()[:10])
|
||||
|
||||
mountOptions := []systemFuse.MountOption{
|
||||
systemFuse.ReadOnly(),
|
||||
@@ -201,7 +201,7 @@ func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args
|
||||
err = fusefs.Serve(c, root)
|
||||
}()
|
||||
|
||||
printer.S("Now serving the repository at %s", mountpoint)
|
||||
printer.S("Now serving the repository at %s", ui.Quote(mountpoint))
|
||||
printer.S("Use another terminal or tool to browse the contents of this folder.")
|
||||
printer.S("When finished, quit with Ctrl-c here or umount the mountpoint.")
|
||||
debug.Log("serving mount at %v", mountpoint)
|
||||
@@ -227,16 +227,16 @@ func validateMountpoint(mountpoint string, gopts global.Options) error {
|
||||
// prevent unnecessary computations while opening the repository.
|
||||
stat, err := os.Stat(mountpoint)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s does not exist", mountpoint))
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %q does not exist", mountpoint))
|
||||
} else if err != nil {
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s is inaccessible: %v", mountpoint, err))
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %q is inaccessible: %v", mountpoint, err))
|
||||
} else if !stat.IsDir() {
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s is not a directory", mountpoint))
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %q is not a directory", mountpoint))
|
||||
}
|
||||
|
||||
err = unix.Access(mountpoint, unix.W_OK|unix.X_OK)
|
||||
if err != nil {
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s is not writeable or not executable", mountpoint))
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %q is not writeable or not executable", mountpoint))
|
||||
}
|
||||
|
||||
// Refuse to mount onto (or under, or over) the local repository directory.
|
||||
@@ -271,11 +271,11 @@ func checkMountpointOverlap(repoPath, mountpoint string) error {
|
||||
const tail = "; refusing to mount to avoid deadlocking the FUSE server"
|
||||
switch {
|
||||
case rp == mp:
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s is the local repository directory%s", mp, tail))
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %q is the local repository directory%s", mp, tail))
|
||||
case fs.HasPathPrefix(rp, mp):
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s is inside the local repository directory %s%s", mp, rp, tail))
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %q is inside the local repository directory %q%s", mp, rp, tail))
|
||||
case fs.HasPathPrefix(mp, rp):
|
||||
return errors.Fatal(fmt.Sprintf("local repository directory %s is inside the mountpoint %s%s", rp, mp, tail))
|
||||
return errors.Fatal(fmt.Sprintf("local repository directory %q is inside the mountpoint %q%s", rp, mp, tail))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ func runPrune(ctx context.Context, opts PruneOptions, gopts global.Options, term
|
||||
defer unlock()
|
||||
|
||||
if opts.UnsafeNoSpaceRecovery != "" {
|
||||
repoID := repo.Config().ID
|
||||
repoID := repo.Config().ID.String()
|
||||
if opts.UnsafeNoSpaceRecovery != repoID {
|
||||
return errors.Fatalf("must pass id '%s' to --unsafe-recover-no-free-space", repoID)
|
||||
}
|
||||
|
||||
@@ -75,14 +75,14 @@ func runRecover(ctx context.Context, gopts global.Options, term ui.Terminal) err
|
||||
// tree. If it is not referenced, we have a root tree.
|
||||
trees := make(map[restic.ID]bool)
|
||||
|
||||
err = repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
for blob := range repo.ListBlobs() {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
h := blob.Handle()
|
||||
if h.Type == restic.TreeBlob {
|
||||
trees[h.ID] = false
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
printer.P("load %d trees\n", len(trees))
|
||||
|
||||
@@ -40,13 +40,12 @@ func TestRunRepairPackfiles(t *testing.T) {
|
||||
|
||||
rtest.OK(t, repo.LoadIndex(ctx, printer))
|
||||
// load packfiles from master index
|
||||
err = repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
for blob := range repo.ListBlobs() {
|
||||
rtest.OK(t, ctx.Err())
|
||||
if blob.Handle().Type == restic.DataBlob {
|
||||
packfileID = blob.PackID()
|
||||
return
|
||||
}
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"slices"
|
||||
|
||||
"github.com/restic/restic/internal/data"
|
||||
@@ -176,6 +177,10 @@ func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOp
|
||||
return slices.Values([]data.NodeOrError{}), nil
|
||||
},
|
||||
AllowUnstableSerialization: true,
|
||||
ReportDroppedNode: func(parent string, node *data.Node, err error) {
|
||||
target := path.Join(parent, node.Name)
|
||||
printer.E("warning: dropping directory entry %q: %v", target, err)
|
||||
},
|
||||
})
|
||||
|
||||
changedCount := 0
|
||||
|
||||
@@ -243,7 +243,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
|
||||
}
|
||||
|
||||
if !gopts.JSON {
|
||||
printer.P("restoring %s to %s\n", res.Snapshot(), opts.Target)
|
||||
printer.P("restoring %s to %s\n", res.Snapshot(), ui.Quote(opts.Target))
|
||||
}
|
||||
|
||||
countRestoredFiles, err := res.RestoreTo(ctx, opts.Target)
|
||||
@@ -259,7 +259,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
|
||||
|
||||
if opts.Verify {
|
||||
if !gopts.JSON {
|
||||
printer.P("verifying files in %s\n", opts.Target)
|
||||
printer.P("verifying files in %s\n", ui.Quote(opts.Target))
|
||||
}
|
||||
var count int
|
||||
t0 := time.Now()
|
||||
@@ -273,7 +273,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
|
||||
}
|
||||
|
||||
if !gopts.JSON {
|
||||
printer.P("finished verifying %d files in %s (took %s)\n", count, opts.Target,
|
||||
printer.P("finished verifying %d files in %s (took %s)\n", count, ui.Quote(opts.Target),
|
||||
time.Since(t0).Round(time.Millisecond))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ func (sma snapshotMetadataArgs) convert() (*snapshotMetadata, error) {
|
||||
|
||||
var timeStamp *time.Time
|
||||
if sma.Time != "" {
|
||||
t, err := time.ParseInLocation(global.TimeFormat, sma.Time, time.Local)
|
||||
t, err := ui.ParseTime(sma.Time)
|
||||
if err != nil {
|
||||
return nil, errors.Fatalf("error in time option: %v", err)
|
||||
}
|
||||
@@ -163,7 +163,7 @@ func rewriteSnapshot(ctx context.Context, repo *repository.Repository, sn *data.
|
||||
rewriteNode = gatherExcludeFilters(rejectByNameFuncs, printer)
|
||||
}
|
||||
|
||||
rewriter, querySize := walker.NewSnapshotSizeRewriter(rewriteNode, keepEmptyDirectoryFunc)
|
||||
rewriter, querySize := walker.NewSnapshotSizeRewriter(rewriteNode, keepEmptyDirectoryFunc, nil)
|
||||
|
||||
filter = func(ctx context.Context, sn *data.Snapshot, uploader restic.BlobSaver) (restic.ID, *data.SnapshotSummary, error) {
|
||||
id, err := rewriter.RewriteTree(ctx, repo, uploader, "/", *sn.Tree)
|
||||
@@ -245,7 +245,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d
|
||||
}
|
||||
|
||||
if newMetadata != nil && newMetadata.Hostname != "" {
|
||||
printer.P("would set hostname to %s", newMetadata.Hostname)
|
||||
printer.P("would set hostname to %s", ui.Quote(newMetadata.Hostname))
|
||||
}
|
||||
|
||||
return true, nil
|
||||
@@ -268,7 +268,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d
|
||||
}
|
||||
|
||||
if newMetadata != nil && newMetadata.Hostname != "" {
|
||||
printer.P("setting host to %s", newMetadata.Hostname)
|
||||
printer.P("setting host to %s", ui.Quote(newMetadata.Hostname))
|
||||
sn.Hostname = newMetadata.Hostname
|
||||
}
|
||||
|
||||
|
||||
@@ -372,7 +372,7 @@ func TestRewriteWrongMetadata(t *testing.T) {
|
||||
},
|
||||
}
|
||||
err := testRunRewriteOutput(t, opts, env.gopts, []string{})
|
||||
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "error in time option: parsing time"),
|
||||
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "unable to parse time:"),
|
||||
"expected time string related errors, got %v", err)
|
||||
}
|
||||
|
||||
|
||||
+18
-15
@@ -59,6 +59,7 @@ type SnapshotOptions struct {
|
||||
last bool // Deprecated in favour of Latest.
|
||||
Latest int
|
||||
GroupBy data.SnapshotGroupByOptions
|
||||
Reverse bool
|
||||
}
|
||||
|
||||
func (opts *SnapshotOptions) AddFlags(f *pflag.FlagSet) {
|
||||
@@ -72,6 +73,7 @@ func (opts *SnapshotOptions) AddFlags(f *pflag.FlagSet) {
|
||||
}
|
||||
f.IntVar(&opts.Latest, "latest", 0, "only show the last `n` snapshots for each host and path")
|
||||
f.VarP(&opts.GroupBy, "group-by", "g", "`group` snapshots by host, paths and/or tags, separated by comma")
|
||||
f.BoolVar(&opts.Reverse, "reverse", false, "reverse sort order of snapshots, newest first")
|
||||
}
|
||||
|
||||
func (opts *SnapshotOptions) Finalize() error {
|
||||
@@ -118,7 +120,11 @@ func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts global.Option
|
||||
list = filterLatestSnapshots(list, opts.Latest)
|
||||
}
|
||||
}
|
||||
sort.Sort(sort.Reverse(list))
|
||||
if opts.Reverse {
|
||||
sort.Stable(list)
|
||||
} else {
|
||||
sort.Stable(sort.Reverse(list))
|
||||
}
|
||||
snapshotGroups[k] = list
|
||||
}
|
||||
|
||||
@@ -141,7 +147,7 @@ func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts global.Option
|
||||
return err
|
||||
}
|
||||
}
|
||||
err := PrintSnapshots(gopts.Term.OutputWriter(), list, nil, opts.Compact)
|
||||
err := printSnapshotsTable(gopts.Term.OutputWriter(), list, nil, opts.Compact)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -199,8 +205,9 @@ func filterLatestSnapshotsInGroup(list data.Snapshots, limit int) data.Snapshots
|
||||
return list[:min(limit, len(list))]
|
||||
}
|
||||
|
||||
// PrintSnapshots prints a text table of the snapshots in list to stdout.
|
||||
func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepReason, compact bool) error {
|
||||
// printSnapshotsTable prints a text table of the snapshots in list to stdout,
|
||||
// in the order the list is given. The caller is responsible for sorting it beforehand.
|
||||
func printSnapshotsTable(stdout io.Writer, list data.Snapshots, reasons []data.KeepReason, compact bool) error {
|
||||
// keep the reasons a snasphot is being kept in a map, so that it doesn't
|
||||
// get lost when the list of snapshots is sorted
|
||||
keepReasons := make(map[restic.ID]data.KeepReason, len(reasons))
|
||||
@@ -216,11 +223,6 @@ func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepRe
|
||||
hasSize = hasSize || (sn.Summary != nil)
|
||||
}
|
||||
|
||||
// always sort the snapshots so that the newer ones are listed last
|
||||
sort.SliceStable(list, func(i, j int) bool {
|
||||
return list[i].Time.Before(list[j].Time)
|
||||
})
|
||||
|
||||
// Determine the max widths for host and tag.
|
||||
maxHost, maxTag := 10, 6
|
||||
for _, sn := range list {
|
||||
@@ -273,9 +275,9 @@ func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepRe
|
||||
data := snapshot{
|
||||
ID: sn.ID().Str(),
|
||||
Timestamp: sn.Time.Local().Format(global.TimeFormat),
|
||||
Hostname: sn.Hostname,
|
||||
Tags: sn.Tags,
|
||||
Paths: sn.Paths,
|
||||
Hostname: ui.Quote(sn.Hostname),
|
||||
Tags: ui.QuoteSlice(sn.Tags),
|
||||
Paths: ui.QuoteSlice(sn.Paths),
|
||||
}
|
||||
|
||||
if len(reasons) > 0 {
|
||||
@@ -342,13 +344,13 @@ func PrintSnapshotGroupHeader(stdout io.Writer, groupKeyJSON string) error {
|
||||
header := "snapshots"
|
||||
var infoStrings []string
|
||||
if key.Hostname != "" {
|
||||
infoStrings = append(infoStrings, "host ["+key.Hostname+"]")
|
||||
infoStrings = append(infoStrings, "host ["+ui.Quote(key.Hostname)+"]")
|
||||
}
|
||||
if key.Tags != nil {
|
||||
infoStrings = append(infoStrings, "tags ["+strings.Join(key.Tags, ", ")+"]")
|
||||
infoStrings = append(infoStrings, "tags ["+strings.Join(ui.QuoteSlice(key.Tags), ", ")+"]")
|
||||
}
|
||||
if key.Paths != nil {
|
||||
infoStrings = append(infoStrings, "paths ["+strings.Join(key.Paths, ", ")+"]")
|
||||
infoStrings = append(infoStrings, "paths ["+strings.Join(ui.QuoteSlice(key.Paths), ", ")+"]")
|
||||
}
|
||||
if infoStrings != nil {
|
||||
header += " for (" + strings.Join(infoStrings, ", ") + ")"
|
||||
@@ -373,6 +375,7 @@ type SnapshotGroup struct {
|
||||
}
|
||||
|
||||
// printSnapshotGroupJSON writes the JSON representation of list to stdout.
|
||||
// The snapshots in snGroups are expected to already be sorted; the order is preserved as-is.
|
||||
func printSnapshotGroupJSON(stdout io.Writer, snGroups map[string]data.Snapshots, grouped bool) error {
|
||||
if grouped {
|
||||
snapshotGroups := []SnapshotGroup{}
|
||||
|
||||
@@ -93,3 +93,28 @@ func TestSnapshotsLatest(t *testing.T) {
|
||||
rtest.Assert(t, len(snapshots) == 1, "expected only one snapshot, got %d", len(snapshots))
|
||||
rtest.Equals(t, snapshots[0].ID.String(), secondSnapshotID, "unexpected snapshot ID")
|
||||
}
|
||||
|
||||
func TestSnapshotsReverse(t *testing.T) {
|
||||
env, cleanup := withTestEnvironment(t)
|
||||
defer cleanup()
|
||||
|
||||
secondSnapshotID := snapshotsGroupTestData(t, env, true)
|
||||
|
||||
for _, reverse := range []bool{false, true} {
|
||||
buf, err := withCaptureStdout(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
|
||||
gopts.JSON = true
|
||||
opts := SnapshotOptions{Reverse: reverse}
|
||||
return runSnapshots(ctx, opts, gopts, []string{}, gopts.Term)
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
snapshots := []Snapshot{}
|
||||
rtest.OK(t, json.Unmarshal(buf.Bytes(), &snapshots))
|
||||
rtest.Assert(t, len(snapshots) == 2, "expected two snapshots, got %d", len(snapshots))
|
||||
|
||||
if reverse {
|
||||
rtest.Equals(t, secondSnapshotID, snapshots[0].ID.String(), "expected newest snapshot first with --reverse")
|
||||
} else {
|
||||
rtest.Equals(t, secondSnapshotID, snapshots[1].ID.String(), "expected newest snapshot last by default")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/restic/restic/internal/data"
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Regression test for #2979: no snapshots should print as [], not null.
|
||||
func TestEmptySnapshotGroupJSON(t *testing.T) {
|
||||
func TestSnapshotsEmptySnapshotGroupJSON(t *testing.T) {
|
||||
for _, grouped := range []bool{false, true} {
|
||||
var w strings.Builder
|
||||
err := printSnapshotGroupJSON(&w, nil, grouped)
|
||||
@@ -17,3 +21,29 @@ func TestEmptySnapshotGroupJSON(t *testing.T) {
|
||||
rtest.Equals(t, "[]", strings.TrimSpace(w.String()))
|
||||
}
|
||||
}
|
||||
|
||||
// TestSnapshotsPrintSnapshotsSortsAscending verifies that PrintSnapshots always sorts its
|
||||
// input so that the oldest snapshot is listed first, regardless of the given order.
|
||||
func TestSnapshotsPrintSnapshotsSortsAscending(t *testing.T) {
|
||||
now := time.Now()
|
||||
list := data.Snapshots{
|
||||
{Time: now.Add(2 * time.Hour), Hostname: "host1", Paths: []string{"/data"}},
|
||||
{Time: now, Hostname: "host1", Paths: []string{"/data"}},
|
||||
{Time: now.Add(1 * time.Hour), Hostname: "host1", Paths: []string{"/data"}},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := PrintSnapshots(&buf, list, nil, true)
|
||||
rtest.OK(t, err)
|
||||
|
||||
rtest.Assert(t, list[0].Time.Equal(now), "expected oldest snapshot first, got %v", list[0].Time)
|
||||
rtest.Assert(t, list[1].Time.Equal(now.Add(1*time.Hour)), "expected second-oldest snapshot second, got %v", list[1].Time)
|
||||
rtest.Assert(t, list[2].Time.Equal(now.Add(2*time.Hour)), "expected newest snapshot last, got %v", list[2].Time)
|
||||
}
|
||||
|
||||
// TestSnapshotsReverseFlag verifies that the --reverse flag defaults to false.
|
||||
func TestSnapshotsReverseFlag(t *testing.T) {
|
||||
var opts SnapshotOptions
|
||||
opts.AddFlags(pflag.NewFlagSet("snapshots", pflag.ContinueOnError))
|
||||
rtest.Equals(t, false, opts.Reverse)
|
||||
}
|
||||
@@ -419,11 +419,14 @@ func statsDebugBlobs(ctx context.Context, repo restic.Repository) ([restic.NumBl
|
||||
hist[i] = newSizeHistogram(2 * chunker.MaxSize)
|
||||
}
|
||||
|
||||
err := repo.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
for pb := range repo.ListBlobs() {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return hist, err
|
||||
}
|
||||
hist[pb.Handle().Type].Add(uint64(pb.CiphertextLength()))
|
||||
})
|
||||
}
|
||||
|
||||
return hist, err
|
||||
return hist, nil
|
||||
}
|
||||
|
||||
type sizeClass struct {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
func formatNodeOutput(n lsNodeOutput, long bool, human bool) string {
|
||||
if !long {
|
||||
return n.Path
|
||||
return ui.Quote(n.Path)
|
||||
}
|
||||
|
||||
var mode os.FileMode
|
||||
@@ -31,7 +31,7 @@ func formatNodeOutput(n lsNodeOutput, long bool, human bool) string {
|
||||
mode = os.ModeDir
|
||||
case data.NodeTypeSymlink:
|
||||
mode = os.ModeSymlink
|
||||
target = fmt.Sprintf(" -> %v", n.LinkTarget)
|
||||
target = fmt.Sprintf(" -> %s", ui.Quote(n.LinkTarget))
|
||||
case data.NodeTypeDev:
|
||||
mode = os.ModeDevice
|
||||
case data.NodeTypeCharDev:
|
||||
@@ -44,7 +44,7 @@ func formatNodeOutput(n lsNodeOutput, long bool, human bool) string {
|
||||
|
||||
return fmt.Sprintf("%s %5d %5d %s %s %s%s",
|
||||
mode|n.Mode, n.UID, n.GID, size,
|
||||
n.ModTime.Local().Format(global.TimeFormat), n.Path,
|
||||
n.ModTime.Local().Format(global.TimeFormat), ui.Quote(n.Path),
|
||||
target)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -54,6 +56,26 @@ func TestFormatNode(t *testing.T) {
|
||||
human: true,
|
||||
expect: "---------- 1000 2000 14.000 MiB 2020-01-02 03:04:05 " + testPath,
|
||||
},
|
||||
{
|
||||
path: "dir\nfile",
|
||||
Node: node,
|
||||
long: false,
|
||||
expect: strconv.Quote("dir\nfile"),
|
||||
},
|
||||
{
|
||||
path: "dir\nfile",
|
||||
Node: data.Node{
|
||||
Name: "link",
|
||||
Type: data.NodeTypeSymlink,
|
||||
Mode: os.ModeSymlink | 0777,
|
||||
LinkTarget: "target\x1b",
|
||||
UID: 1000,
|
||||
GID: 2000,
|
||||
ModTime: time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC),
|
||||
},
|
||||
long: true,
|
||||
expect: "Lrwxrwxrwx 1000 2000 0 2020-01-02 03:04:05 " + strconv.Quote("dir\nfile") + " -> " + strconv.Quote("target\x1b"),
|
||||
},
|
||||
} {
|
||||
r := formatNode(c.path, &c.Node, c.long, c.human)
|
||||
rtest.Equals(t, c.expect, r)
|
||||
|
||||
@@ -273,11 +273,15 @@ func listTreePacks(gopts global.Options, t *testing.T) restic.IDSet {
|
||||
|
||||
rtest.OK(t, r.LoadIndex(ctx, restic.NoopTerminalCounterFactory))
|
||||
treePacks = restic.NewIDSet()
|
||||
return r.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
for pb := range r.ListBlobs() {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if pb.Handle().Type == restic.TreeBlob {
|
||||
treePacks.Insert(pb.PackID())
|
||||
}
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
return treePacks
|
||||
@@ -322,11 +326,12 @@ func removePacksExcept(gopts global.Options, t testing.TB, keep restic.IDSet, re
|
||||
rtest.OK(t, r.LoadIndex(ctx, restic.NoopTerminalCounterFactory))
|
||||
|
||||
treePacks := restic.NewIDSet()
|
||||
rtest.OK(t, r.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
for pb := range r.ListBlobs() {
|
||||
rtest.OK(t, ctx.Err())
|
||||
if pb.Handle().Type == restic.TreeBlob {
|
||||
treePacks.Insert(pb.PackID())
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
// remove all packs containing data blobs
|
||||
return r.List(ctx, restic.PackFile, func(id restic.ID, size int64) error {
|
||||
|
||||
+47
-7
@@ -8,18 +8,22 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
"runtime"
|
||||
godebug "runtime/debug"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"go.uber.org/automaxprocs/maxprocs"
|
||||
|
||||
"github.com/restic/restic/internal/backend/all"
|
||||
"github.com/restic/restic/internal/backend/location"
|
||||
"github.com/restic/restic/internal/debug"
|
||||
"github.com/restic/restic/internal/errors"
|
||||
"github.com/restic/restic/internal/feature"
|
||||
"github.com/restic/restic/internal/global"
|
||||
"github.com/restic/restic/internal/repository"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
"github.com/restic/restic/internal/ui/termstatus"
|
||||
)
|
||||
|
||||
@@ -37,12 +41,12 @@ func newRootCommand(globalOptions *global.Options) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "restic",
|
||||
Short: "Backup and restore files",
|
||||
Long: `
|
||||
Long: fmt.Sprintf(`
|
||||
restic is a backup program which allows saving multiple revisions of files and
|
||||
directories in an encrypted repository stored on different backends.
|
||||
|
||||
The full documentation can be found at https://restic.readthedocs.io/ .
|
||||
`,
|
||||
The full documentation can be found at %s.
|
||||
`, docsURL(global.Version)),
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
DisableAutoGenTag: true,
|
||||
@@ -132,6 +136,24 @@ func tweakGoGC() {
|
||||
}
|
||||
}
|
||||
|
||||
func docsURL(version string) string {
|
||||
baseURL := "https://restic.readthedocs.io/en/"
|
||||
|
||||
if version == "" || version == "unknown" {
|
||||
return baseURL + "latest"
|
||||
}
|
||||
|
||||
if strings.Contains(version, "dev") || strings.Contains(version, "compiled") {
|
||||
return baseURL + "latest"
|
||||
}
|
||||
|
||||
if matches := regexp.MustCompile(`^(\d+\.\d+\.\d+)`).FindStringSubmatch(version); len(matches) == 2 {
|
||||
return fmt.Sprintf(baseURL+"v%s", matches[1])
|
||||
}
|
||||
|
||||
return baseURL + "latest"
|
||||
}
|
||||
|
||||
func printExitError(globalOptions global.Options, code int, message string) {
|
||||
if globalOptions.JSON {
|
||||
type jsonExitError struct {
|
||||
@@ -146,18 +168,35 @@ func printExitError(globalOptions global.Options, code int, message string) {
|
||||
Message: message,
|
||||
}
|
||||
|
||||
err := json.NewEncoder(os.Stderr).Encode(jsonS)
|
||||
b, err := json.Marshal(jsonS)
|
||||
if err != nil {
|
||||
// ignore error as there's no good way to handle it
|
||||
_, _ = fmt.Fprintf(os.Stderr, "JSON encode failed: %v\n", err)
|
||||
debug.Log("JSON encode failed: %v\n", err)
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprintf(os.Stderr, "%s\n", ui.EscapeControls(string(b)))
|
||||
} else {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "%v\n", message)
|
||||
_, _ = fmt.Fprintf(os.Stderr, "%s\n", ui.EscapeControls(message))
|
||||
}
|
||||
}
|
||||
|
||||
// redactLoggedArgs heuristically hides repository passwords from the debug log.
|
||||
func redactLoggedArgs(args []string, registry *location.Registry) []string {
|
||||
redacted := make([]string, 0, len(args))
|
||||
for _, arg := range args {
|
||||
var cleaned string
|
||||
if flag, value, ok := strings.Cut(arg, "="); ok && strings.HasPrefix(flag, "-") {
|
||||
cleaned = flag + "=" + location.StripPassword(registry, value)
|
||||
} else {
|
||||
cleaned = location.StripPassword(registry, arg)
|
||||
}
|
||||
|
||||
redacted = append(redacted, cleaned)
|
||||
}
|
||||
return redacted
|
||||
}
|
||||
|
||||
func main() {
|
||||
tweakGoGC()
|
||||
// install custom global logger into a buffer, if an error occurs
|
||||
@@ -173,12 +212,13 @@ func main() {
|
||||
Exit(1)
|
||||
}
|
||||
|
||||
debug.Log("main %#v", os.Args)
|
||||
backends := all.Backends()
|
||||
debug.Log("main %#v", redactLoggedArgs(os.Args, backends))
|
||||
debug.Log("restic %s compiled with %v on %v/%v",
|
||||
global.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
|
||||
|
||||
globalOptions := global.Options{
|
||||
Backends: all.Backends(),
|
||||
Backends: backends,
|
||||
}
|
||||
func() {
|
||||
term, cancel := termstatus.Setup(os.Stdin, os.Stdout, os.Stderr, globalOptions.Quiet)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/backend/all"
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
)
|
||||
|
||||
func TestRedactLoggedArgs(t *testing.T) {
|
||||
registry := all.Backends()
|
||||
args := []string{
|
||||
"restic",
|
||||
"-r",
|
||||
"rest:https://user:secret@example.com/repo",
|
||||
"--repo=rest:https://user:secret@example.com/repo",
|
||||
"backup",
|
||||
"/srv/data",
|
||||
}
|
||||
copy := slices.Clone(args)
|
||||
got := redactLoggedArgs(args, registry)
|
||||
rtest.Equals(t, []string{
|
||||
"restic",
|
||||
"-r",
|
||||
"rest:https://user:***@example.com/repo/",
|
||||
"--repo=rest:https://user:***@example.com/repo/",
|
||||
"backup",
|
||||
"/srv/data",
|
||||
}, got)
|
||||
// ensure that the original arguments are not modified
|
||||
rtest.Equals(t, copy, args)
|
||||
}
|
||||
@@ -179,13 +179,23 @@ setting the arguments passed to the default SSH command (ignored when
|
||||
|
||||
.. note:: Please be aware that SFTP servers close connections when no data is
|
||||
received by the client. This can happen when restic is processing huge
|
||||
amounts of unchanged data. To avoid this issue add the following lines
|
||||
to the client's .ssh/config file:
|
||||
amounts of unchanged data. To keep the connection alive, set the
|
||||
``ServerAliveInterval`` and ``ServerAliveCountMax`` SSH options using
|
||||
restic's ``sftp.server-alive-interval`` and ``sftp.server-alive-count-max``
|
||||
options. For example, the following sends a keepalive message every
|
||||
60 seconds and closes the connection after 5 unanswered messages:
|
||||
|
||||
::
|
||||
::
|
||||
|
||||
ServerAliveInterval 60
|
||||
ServerAliveCountMax 240
|
||||
$ restic -o sftp.server-alive-interval=60 -o sftp.server-alive-count-max=5 -r sftp:user@host:/srv/restic-repo backup ~/work
|
||||
|
||||
Alternatively, add the following lines to the client's ``.ssh/config``
|
||||
file:
|
||||
|
||||
::
|
||||
|
||||
ServerAliveInterval 60
|
||||
ServerAliveCountMax 5
|
||||
|
||||
|
||||
REST Server
|
||||
|
||||
+85
-8
@@ -183,6 +183,21 @@ Now is a good time to run ``restic check`` to verify that all data
|
||||
is properly stored in the repository. You should run this command regularly
|
||||
to make sure the internal structure of the repository is free of errors.
|
||||
|
||||
Backup summary
|
||||
**************
|
||||
|
||||
The ``Files:`` and ``Dirs:`` lines at the end of a backup count each file and
|
||||
directory in the new snapshot exactly once, compared to the parent snapshot
|
||||
(see `File change detection`_ for how the parent is selected):
|
||||
|
||||
* ``new``: the item did not exist in the parent snapshot.
|
||||
* ``changed``: the item existed in the parent snapshot, but its content or
|
||||
metadata differs. A directory counts as changed if anything inside it changed.
|
||||
* ``unmodified``: the item is the same as in the parent snapshot.
|
||||
|
||||
If there is no parent snapshot, for example on the first backup, every item is
|
||||
``new``, and both other counts are zero.
|
||||
|
||||
File change detection
|
||||
*********************
|
||||
|
||||
@@ -771,15 +786,77 @@ snapshot.
|
||||
Scheduling backups
|
||||
******************
|
||||
|
||||
Restic does not have a built-in way of scheduling backups, as it's a tool
|
||||
that runs when executed rather than a daemon. There are plenty of different
|
||||
ways to schedule backup runs on various different platforms, e.g. systemd
|
||||
and cron on Linux/BSD and Task Scheduler in Windows, depending on one's
|
||||
needs and requirements. If you don't want to implement your own scheduling,
|
||||
you can use `resticprofile <https://github.com/creativeprojects/resticprofile/#resticprofile>`__.
|
||||
.. admonition:: Design note
|
||||
|
||||
Restic intentionally does not provide built-in scheduling or job management.
|
||||
It is designed to run when executed, rather than as a daemon. Scheduling and
|
||||
orchestration are therefore considered out of scope and are delegated to the
|
||||
operating system or external tools.
|
||||
|
||||
This design keeps the restic core simpler, more reliable, and easier to audit,
|
||||
while allowing it to integrate cleanly into a wide range of environments.
|
||||
|
||||
Scheduling mechanisms
|
||||
=====================
|
||||
|
||||
Backup scheduling depends on the platform and environment:
|
||||
|
||||
- On Linux systems that use ``systemd``, ``systemd`` timers are generally preferred when available,
|
||||
as they provide better error handling, logging, dependency management, and
|
||||
integration with the system lifecycle.
|
||||
|
||||
- On Unix-like systems without ``systemd`` (including BSD and macOS), ``cron`` remains a widely
|
||||
supported and portable option. On macOS, ``launchd`` is another common native option.
|
||||
|
||||
- On Windows, Task Scheduler can be used to run restic commands at defined
|
||||
intervals.
|
||||
|
||||
The choice of scheduler depends on the operating system and local constraints,
|
||||
rather than on restic itself.
|
||||
|
||||
External orchestration tools
|
||||
============================
|
||||
|
||||
Several community-maintained tools exist to orchestrate restic backups by
|
||||
combining configuration, scheduling, hooks, and retention policies. These tools
|
||||
are optional and not required to use restic.
|
||||
|
||||
Using such tools can reduce boilerplate for some setups, but they are not part
|
||||
of restic itself and are not required for correct operation.
|
||||
|
||||
.. note::
|
||||
|
||||
Restic is not affiliated with, nor does it endorse, any third-party
|
||||
orchestration or automation tools, even if such tools are mentioned explicitly in the
|
||||
documentation.
|
||||
|
||||
If you don't want to implement your own scheduling, you can use third-party
|
||||
orchestration tools such as `resticprofile <https://creativeprojects.github.io/resticprofile/>`__.
|
||||
|
||||
Avoiding lock conflicts
|
||||
=======================
|
||||
|
||||
.. caution::
|
||||
|
||||
Avoid running scheduled maintenance commands that require exclusive
|
||||
repository access while other restic commands are using the same repository.
|
||||
|
||||
Restic allows concurrent access to a repository. For example, ``backup`` and
|
||||
commands that only read from the repository can run at the same time. The
|
||||
``check``, ``forget`` and ``prune`` commands require exclusive access and
|
||||
will conflict with other running restic commands.
|
||||
|
||||
When scheduling restic to run automatically, make sure that exclusive
|
||||
maintenance commands do not overlap with backups or other repository operations.
|
||||
Common strategies include:
|
||||
|
||||
- scheduling maintenance jobs in a separate time window
|
||||
- using ``--retry-lock`` so a command waits for a conflicting lock to clear
|
||||
- using scheduler-level locking or dependency mechanisms
|
||||
- relying on the scheduler's own guarantees (such as systemd unit semantics on Linux).
|
||||
|
||||
See :ref:`locks-design` for details.
|
||||
|
||||
When scheduling restic to run recurringly, please make sure to detect already
|
||||
running instances before starting the backup.
|
||||
|
||||
Space requirements
|
||||
******************
|
||||
|
||||
@@ -594,6 +594,8 @@ As can be seen from the output of the program ``sha256sum``, the hash
|
||||
matches the plaintext hash from the map included in the tree above, so
|
||||
the correct data has been returned.
|
||||
|
||||
.. _locks-design:
|
||||
|
||||
Locks
|
||||
=====
|
||||
|
||||
|
||||
@@ -8,9 +8,9 @@ godebug winsymlink=0
|
||||
|
||||
require (
|
||||
cloud.google.com/go/storage v1.69.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3
|
||||
github.com/Backblaze/blazer v0.9.0
|
||||
github.com/Microsoft/go-winio v0.6.2
|
||||
github.com/ProtonMail/go-crypto v1.5.2
|
||||
@@ -27,18 +27,18 @@ require (
|
||||
github.com/peterbourgon/unixtransport v0.0.7
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/profile v1.7.0
|
||||
github.com/pkg/sftp v1.13.11
|
||||
github.com/pkg/sftp v1.13.13
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/restic/chunker v0.5.0
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/pflag v1.0.10
|
||||
github.com/spf13/pflag v1.1.0
|
||||
go.uber.org/automaxprocs v1.6.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/oauth2 v0.38.0
|
||||
golang.org/x/sync v0.25.0
|
||||
golang.org/x/sys v0.49.0
|
||||
golang.org/x/term v0.47.0
|
||||
golang.org/x/text v0.43.0
|
||||
golang.org/x/sys v0.50.0
|
||||
golang.org/x/term v0.48.0
|
||||
golang.org/x/text v0.44.0
|
||||
golang.org/x/time v0.16.0
|
||||
google.golang.org/api v0.313.0
|
||||
)
|
||||
@@ -51,7 +51,8 @@ require (
|
||||
cloud.google.com/go/compute/metadata v0.10.0 // indirect
|
||||
cloud.google.com/go/iam v1.14.0 // indirect
|
||||
cloud.google.com/go/monitoring v1.30.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 // indirect
|
||||
@@ -102,7 +103,7 @@ require (
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.6 // indirect
|
||||
golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941 // indirect
|
||||
|
||||
@@ -20,18 +20,20 @@ cloud.google.com/go/storage v1.69.0 h1:jAAMC1411HEh78nKsU0Zns+eFj3TnhjAWIhg5Ud/X
|
||||
cloud.google.com/go/storage v1.69.0/go.mod h1:PELYsxTYm2peE4mwLEC1+mS1dA/kUSRUxNv56rOy44g=
|
||||
cloud.google.com/go/trace v1.16.0 h1:GmQovzFc5F0CNfl0VLgL64aoTtu7xsM0YajW2GlG9+E=
|
||||
cloud.google.com/go/trace v1.16.0/go.mod h1:r+bdAn16dKLSV1G2D5v3e58IlQlizfxWrUfjx7kM7X0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 h1:zvXfGJCWvywnCA814d8ZiVyt+fm9nnTE8xSb99zRyfo=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 h1:5H6YRLGMoC8z5aXpxqcD6FfswI8mwoVNHSecvIoazt4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0/go.mod h1:Sk63W6X/TElfcE2BknMYg0Q9JuCpebgjnHcbs5md4NM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 h1:u93s+zU2JD62im61Bm5CZIc1ZrOJaIAWEg0WOrMVkEo=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 h1:Terj1CMW4+NY5CpWjSRkqLoxh2DkYDdv/FH2z0897Uc=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 h1:/Zt+cDPnpC3OVDm/JKLOs7M2DKmLRIIp3XIx9pHHiig=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1/go.mod h1:Ng3urmn6dYe8gnbCMoHHVl5APYz2txho3koEkV2o2HA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.1 h1:gkBLVmB3Z/HnGP/Jo4o12/RDpi0agnKav6sCKsX5Vu0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.1/go.mod h1:e3/1P5K+jIUi9JevDRklq/tFeTvbBb75bNAjU4xd31w=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3 h1:zoPQ7KXGgzqeUmNWl+b6IwVAqsb5lROEJhqAmqXQtm0=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3/go.mod h1:ei/sDx/dwDIUtZE3PQP1u8+qrA+CRy4q7qW+A2MbgB4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 h1:X/bTwe0qpvmvPPutc+LWo7T4cKMqDP9JHP4k+Co9ZB4=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0/go.mod h1:+kX7ahyFelQ42F3RScM2CFgHJljp0phc/FieKLYVpFI=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 h1:Nljr4q1GRA/5vCrMONS+g4u4LRHNgOXVSh3O43J2CnI=
|
||||
@@ -183,8 +185,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA=
|
||||
github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo=
|
||||
github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE=
|
||||
github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0=
|
||||
github.com/pkg/sftp v1.13.13 h1:lfbNTnT3zEilT8XxmwBBb5sdqJJBTunll5OVNCZPwrs=
|
||||
github.com/pkg/sftp v1.13.13/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0=
|
||||
github.com/pkg/xattr v0.4.12 h1:rRTkSyFNTRElv6pkA3zpjHpQ90p/OdHQC1GmGh1aTjM=
|
||||
github.com/pkg/xattr v0.4.12/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
|
||||
@@ -205,8 +207,8 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
|
||||
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
github.com/stephens2424/writerset v1.0.2/go.mod h1:aS2JhsMn6eA7e82oNmW4rfsgAOp9COBTTl8mzkwADnc=
|
||||
@@ -260,13 +262,13 @@ go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08u
|
||||
go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
|
||||
go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/exp v0.0.0-20220428152302-39d4317da171/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
|
||||
golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297 h1:YXnL44eJ77R+ji4/ooy8UsXIhz+lbi2Qgdlc8iRN0gY=
|
||||
golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297/go.mod h1:Mkmymgv+uMpSQ/XxJ/7GpdrdYoqm3u72jEbpCLiJmNk=
|
||||
@@ -303,20 +305,20 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
|
||||
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
|
||||
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
|
||||
golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk=
|
||||
golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
|
||||
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
|
||||
@@ -222,7 +222,7 @@ func createChangelogRelease() {
|
||||
|
||||
err := os.Rename(src, dest)
|
||||
if err != nil {
|
||||
die("rename %v -> %v failed: %w", src, dest, err)
|
||||
die("rename %v -> %v failed: %v", src, dest, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"path"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -203,8 +204,9 @@ func (arch *Archiver) error(item string, err error) error {
|
||||
}
|
||||
|
||||
// not all errors include the filepath, thus add it if it is missing
|
||||
if !strings.Contains(err.Error(), item) {
|
||||
err = fmt.Errorf("%v: %w", item, err)
|
||||
// errors include quoted file path, so we need to quote it too
|
||||
if !strings.Contains(err.Error(), item) && !strings.Contains(err.Error(), strconv.Quote(item)) {
|
||||
err = fmt.Errorf("%q: %w", item, err)
|
||||
}
|
||||
|
||||
errf := arch.Error(item, err)
|
||||
@@ -272,7 +274,7 @@ func (arch *Archiver) nodeFromFileInfo(snPath, filename string, meta toNoder, ig
|
||||
node.Name = path.Base(snPath)
|
||||
// do not filter error for nodes of irregular or invalid type
|
||||
if node.Type != data.NodeTypeIrregular && node.Type != data.NodeTypeInvalid && err != nil {
|
||||
err = fmt.Errorf("incomplete metadata for %v: %w", filename, err)
|
||||
err = fmt.Errorf("incomplete metadata for %q: %w", filename, err)
|
||||
return node, arch.error(filename, err)
|
||||
}
|
||||
return node, err
|
||||
@@ -383,7 +385,7 @@ func (arch *Archiver) dirToNodeAndEntries(snPath, dir string, meta fs.File) (nod
|
||||
|
||||
names, err = meta.Readdirnames(-1)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("readdirnames %v failed: %w", dir, err)
|
||||
return nil, nil, fmt.Errorf("readdirnames %q failed: %w", dir, err)
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
@@ -547,7 +549,7 @@ func (arch *Archiver) save(ctx context.Context, snPath, target string, previous
|
||||
|
||||
debug.Log("%v hasn't changed, but contents are missing!", target)
|
||||
// There are contents missing - inform user!
|
||||
err := errors.Errorf("parts of %v not found in the repository index; storing the file again", target)
|
||||
err := errors.Errorf("parts of %q not found in the repository index; storing the file again", target)
|
||||
err = arch.error(abstarget, err)
|
||||
if err != nil {
|
||||
return futureNode{}, false, err
|
||||
@@ -670,7 +672,7 @@ func (arch *Archiver) saveTree(ctx context.Context, snPath string, atree *tree,
|
||||
var node *data.Node
|
||||
if snPath != "/" {
|
||||
if atree.FileInfoPath == "" {
|
||||
return futureNode{}, 0, errors.Errorf("FileInfoPath for %v is empty", snPath)
|
||||
return futureNode{}, 0, errors.Errorf("FileInfoPath for %q is empty", snPath)
|
||||
}
|
||||
|
||||
var err error
|
||||
@@ -780,7 +782,7 @@ func (arch *Archiver) dirPathToNode(snPath, target string) (node *data.Node, err
|
||||
return nil, err
|
||||
}
|
||||
if node.Type != data.NodeTypeDir {
|
||||
return nil, errors.Errorf("path is not a directory: %v", target)
|
||||
return nil, errors.Errorf("path is not a directory: %q", target)
|
||||
}
|
||||
return node, err
|
||||
}
|
||||
@@ -846,7 +848,7 @@ func (arch *Archiver) loadParentTree(ctx context.Context, sn *data.Snapshot) dat
|
||||
}
|
||||
|
||||
if sn.Tree == nil {
|
||||
debug.Log("snapshot %v has empty tree %v", *sn.ID())
|
||||
debug.Log("snapshot %v has empty tree", *sn.ID())
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -372,6 +372,62 @@ func BenchmarkArchiverSaveFileSmall(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkArchiverSaveFileConcurrent(b *testing.B) {
|
||||
const fileSize = 4 * 1024
|
||||
const numFiles = 64
|
||||
|
||||
d := TestDir{}
|
||||
for i := 0; i < numFiles; i++ {
|
||||
d[fmt.Sprintf("file%d", i)] = TestFile{
|
||||
Content: string(rtest.Random(23+i, fileSize)),
|
||||
}
|
||||
}
|
||||
|
||||
b.SetBytes(fileSize * numFiles)
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
b.StopTimer()
|
||||
tempdir, repo := prepareTempdirRepoSrc(b, d)
|
||||
|
||||
arch := New(repo, fs.Track{FS: fs.NewLocal()}, Options{})
|
||||
arch.Error = func(item string, err error) error {
|
||||
b.Errorf("archiver error for %v: %v", item, err)
|
||||
return err
|
||||
}
|
||||
b.StartTimer()
|
||||
|
||||
err := repo.WithBlobUploader(context.Background(), func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
|
||||
wg, ctx := errgroup.WithContext(ctx)
|
||||
arch.runWorkers(ctx, wg, uploader)
|
||||
|
||||
var futures []futureNode
|
||||
for j := 0; j < numFiles; j++ {
|
||||
filename := filepath.Join(tempdir, fmt.Sprintf("file%d", j))
|
||||
file, err := arch.FS.OpenFile(filename, fs.O_NOFOLLOW, false)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
fn := arch.fileSaver.Save(ctx, "/", filename, file, func() {}, func() {}, func(*data.Node, ItemStats) {})
|
||||
futures = append(futures, fn)
|
||||
}
|
||||
|
||||
for _, fn := range futures {
|
||||
fnr := fn.take(ctx)
|
||||
if fnr.err != nil {
|
||||
b.Fatal(fnr.err)
|
||||
}
|
||||
}
|
||||
|
||||
arch.stopWorkers()
|
||||
return wg.Wait()
|
||||
})
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkArchiverSaveFileLarge(b *testing.B) {
|
||||
const fileSize = 40*1024*1024 + 1287898
|
||||
d := TestDir{"file": TestFile{
|
||||
@@ -437,13 +493,17 @@ func (repo *blobCountingSaver) SaveBlob(ctx context.Context, t restic.BlobType,
|
||||
return id, exists, size, err
|
||||
}
|
||||
|
||||
func (repo *blobCountingSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) {
|
||||
func (repo *blobCountingSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) {
|
||||
repo.saver.SaveBlobAsync(ctx, t, buf, id, storeDuplicate, func(newID restic.ID, known bool, size int, err error) {
|
||||
repo.count(known, restic.BlobHandle{ID: newID, Type: t})
|
||||
cb(newID, known, size, err)
|
||||
})
|
||||
}
|
||||
|
||||
func (repo *blobCountingSaver) BlobBufferPool() *restic.BlobBufferPool {
|
||||
return repo.saver.BlobBufferPool()
|
||||
}
|
||||
|
||||
func appendToFile(t testing.TB, filename string, data []byte) {
|
||||
f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
@@ -2290,7 +2350,7 @@ func (f *failSaveSaver) SaveBlob(ctx context.Context, t restic.BlobType, buf []b
|
||||
return f.saver.SaveBlob(ctx, t, buf, id, storeDuplicate)
|
||||
}
|
||||
|
||||
func (f *failSaveSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) {
|
||||
func (f *failSaveSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, size int, err error)) {
|
||||
// limit concurrency to make test reliable
|
||||
f.semaphore <- struct{}{}
|
||||
|
||||
@@ -2312,6 +2372,10 @@ func (f *failSaveSaver) SaveBlobAsync(ctx context.Context, t restic.BlobType, bu
|
||||
})
|
||||
}
|
||||
|
||||
func (f *failSaveSaver) BlobBufferPool() *restic.BlobBufferPool {
|
||||
return f.saver.BlobBufferPool()
|
||||
}
|
||||
|
||||
func TestArchiverAbortEarlyOnError(t *testing.T) {
|
||||
var tests = []struct {
|
||||
src TestDir
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
package archiver
|
||||
|
||||
import "sync"
|
||||
|
||||
// buffer is a reusable buffer. After the buffer has been used, Release should
|
||||
// be called so the underlying slice is put back into the pool.
|
||||
type buffer struct {
|
||||
Data []byte
|
||||
pool *bufferPool
|
||||
}
|
||||
|
||||
// Release puts the buffer back into the pool it came from.
|
||||
func (b *buffer) Release() {
|
||||
pool := b.pool
|
||||
if pool == nil || cap(b.Data) > pool.defaultSize {
|
||||
return
|
||||
}
|
||||
|
||||
pool.pool.Put(b)
|
||||
}
|
||||
|
||||
// bufferPool implements a limited set of reusable buffers.
|
||||
type bufferPool struct {
|
||||
pool sync.Pool
|
||||
defaultSize int
|
||||
}
|
||||
|
||||
// newBufferPool initializes a new buffer pool. The pool stores at most max
|
||||
// items. New buffers are created with defaultSize. Buffers that have grown
|
||||
// larger are not put back.
|
||||
func newBufferPool(defaultSize int) *bufferPool {
|
||||
b := &bufferPool{
|
||||
defaultSize: defaultSize,
|
||||
}
|
||||
b.pool = sync.Pool{New: func() any {
|
||||
return &buffer{
|
||||
Data: make([]byte, defaultSize),
|
||||
pool: b,
|
||||
}
|
||||
}}
|
||||
return b
|
||||
}
|
||||
|
||||
// Get returns a new buffer, either from the pool or newly allocated.
|
||||
func (pool *bufferPool) Get() *buffer {
|
||||
return pool.pool.Get().(*buffer)
|
||||
}
|
||||
@@ -242,7 +242,7 @@ func (m deviceMap) IsAllowed(item string, deviceID uint64, fs fs.FS) (bool, erro
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("item %v (device ID %v) not found, deviceMap: %v", item, deviceID, m)
|
||||
return false, fmt.Errorf("item %q (device ID %v) not found, deviceMap: %v", item, deviceID, m)
|
||||
}
|
||||
|
||||
// RejectByDevice returns a RejectFunc that rejects files which are on a
|
||||
@@ -322,7 +322,7 @@ func RejectCloudFiles(warnf func(msg string, args ...any)) (RejectFunc, error) {
|
||||
return func(item string, fi *fs.ExtendedFileInfo, _ fs.FS) bool {
|
||||
recall, err := fi.RecallOnDataAccess()
|
||||
if err != nil {
|
||||
warnf("item %v: error checking online-only status: %v", item, err)
|
||||
warnf("item %q: error checking online-only status: %v", item, err)
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -18,8 +18,7 @@ const chunkReadBufSize = 512 * 1024 // matches chunker internal read buffer size
|
||||
|
||||
// fileSaver concurrently saves incoming files to the repo.
|
||||
type fileSaver struct {
|
||||
saveFilePool *bufferPool
|
||||
uploader restic.BlobSaverAsync
|
||||
uploader restic.BlobSaverAsync
|
||||
|
||||
chunkerFactory restic.ChunkerFactory
|
||||
|
||||
@@ -38,7 +37,6 @@ func newFileSaver(ctx context.Context, wg *errgroup.Group, uploader restic.BlobS
|
||||
|
||||
s := &fileSaver{
|
||||
uploader: uploader,
|
||||
saveFilePool: newBufferPool(chunkerFactory.MaxChunkSize()),
|
||||
chunkerFactory: chunkerFactory,
|
||||
ch: ch,
|
||||
|
||||
@@ -195,7 +193,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt
|
||||
panic("completed twice")
|
||||
}
|
||||
isCompleted = true
|
||||
fnr.err = fmt.Errorf("failed to save %v: %w", target, err)
|
||||
fnr.err = fmt.Errorf("failed to save %q: %w", target, err)
|
||||
fnr.node = nil
|
||||
fnr.stats = ItemStats{}
|
||||
finish(fnr)
|
||||
@@ -224,7 +222,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt
|
||||
node.Size = 0
|
||||
var idx int
|
||||
for {
|
||||
buf := s.saveFilePool.Get()
|
||||
buf := s.uploader.BlobBufferPool().Get()
|
||||
chunkData, err := chunkState.readNextChunk(f, chnker, buf.Data)
|
||||
if err == io.EOF {
|
||||
buf.Release()
|
||||
@@ -239,7 +237,8 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt
|
||||
|
||||
// put result buffer back for later reuse
|
||||
buf.Data = chunkData
|
||||
node.Size += uint64(len(chunkData))
|
||||
chunkSize := len(buf.Data)
|
||||
node.Size += uint64(chunkSize)
|
||||
|
||||
// test if the context has been cancelled, return the error
|
||||
if ctx.Err() != nil {
|
||||
@@ -256,8 +255,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt
|
||||
node.Content = append(node.Content, restic.ID{})
|
||||
lock.Unlock()
|
||||
|
||||
s.uploader.SaveBlobAsync(ctx, restic.DataBlob, chunkData, restic.ID{}, false, func(newID restic.ID, known bool, sizeInRepo int, err error) {
|
||||
defer buf.Release()
|
||||
s.uploader.SaveBlobAsync(ctx, restic.DataBlob, buf, restic.ID{}, false, func(newID restic.ID, known bool, sizeInRepo int, err error) {
|
||||
if err != nil {
|
||||
completeError(err)
|
||||
return
|
||||
@@ -266,7 +264,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt
|
||||
lock.Lock()
|
||||
if !known {
|
||||
fnr.stats.DataBlobs++
|
||||
fnr.stats.DataSize += uint64(len(chunkData))
|
||||
fnr.stats.DataSize += uint64(chunkSize)
|
||||
fnr.stats.DataSizeInRepo += uint64(sizeInRepo)
|
||||
}
|
||||
node.Content[pos] = newID
|
||||
@@ -283,7 +281,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt
|
||||
return
|
||||
}
|
||||
|
||||
s.CompleteBlob(uint64(len(chunkData)))
|
||||
s.CompleteBlob(uint64(chunkSize))
|
||||
}
|
||||
|
||||
err = f.Close()
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/fs"
|
||||
"github.com/restic/restic/internal/repository"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
"github.com/restic/restic/internal/test"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
@@ -36,7 +37,7 @@ func startFileSaver(ctx context.Context, t testing.TB, _ fs.FS) (*fileSaver, *mo
|
||||
workers := uint(runtime.NumCPU())
|
||||
chunkerFactory := repository.TestRepository(t).ChunkerFactory()
|
||||
|
||||
saver := &mockSaver{saved: make(map[string]int)}
|
||||
saver := &mockSaver{saved: make(map[string]int), buffers: restic.NewBlobBufferPool(chunkerFactory.MaxChunkSize())}
|
||||
s := newFileSaver(ctx, wg, saver, chunkerFactory, workers)
|
||||
s.NodeFromFileInfo = func(snPath, filename string, meta toNoder, ignoreXattrListError bool) (*data.Node, error) {
|
||||
return meta.ToNode(ignoreXattrListError, t.Logf)
|
||||
|
||||
@@ -175,7 +175,7 @@ func (t *tree) add(fs fs.FS, target, root string, pc []string, explicit bool) er
|
||||
}
|
||||
|
||||
if node.Path != "" {
|
||||
return errors.Errorf("path is already set for target %v", target)
|
||||
return errors.Errorf("path is already set for target %q", target)
|
||||
}
|
||||
node.Path = target
|
||||
node.Explicit = explicit
|
||||
|
||||
@@ -137,7 +137,7 @@ func (s *treeSaver) save(ctx context.Context, job *saveTreeJob) (*data.Node, Ite
|
||||
)
|
||||
|
||||
ch := make(chan struct{}, 1)
|
||||
s.uploader.SaveBlobAsync(ctx, restic.TreeBlob, buf, restic.ID{}, false, func(newID restic.ID, cbKnown bool, cbSizeInRepo int, cbErr error) {
|
||||
s.uploader.SaveBlobAsync(ctx, restic.TreeBlob, restic.NewBuffer(buf), restic.ID{}, false, func(newID restic.ID, cbKnown bool, cbSizeInRepo int, cbErr error) {
|
||||
known = cbKnown
|
||||
length = len(buf)
|
||||
sizeInRepo = cbSizeInRepo
|
||||
|
||||
@@ -15,18 +15,23 @@ import (
|
||||
)
|
||||
|
||||
type mockSaver struct {
|
||||
saved map[string]int
|
||||
mutex sync.Mutex
|
||||
saved map[string]int
|
||||
mutex sync.Mutex
|
||||
buffers *restic.BlobBufferPool
|
||||
}
|
||||
|
||||
func (m *mockSaver) SaveBlobAsync(_ context.Context, _ restic.BlobType, buf []byte, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, sizeInRepo int, err error)) {
|
||||
func (m *mockSaver) BlobBufferPool() *restic.BlobBufferPool {
|
||||
return m.buffers
|
||||
}
|
||||
|
||||
func (m *mockSaver) SaveBlobAsync(_ context.Context, _ restic.BlobType, buf *restic.BlobBuffer, id restic.ID, storeDuplicate bool, cb func(newID restic.ID, known bool, sizeInRepo int, err error)) {
|
||||
// Fake async operation
|
||||
go func() {
|
||||
m.mutex.Lock()
|
||||
m.saved[string(buf)]++
|
||||
m.saved[string(buf.Data)]++
|
||||
m.mutex.Unlock()
|
||||
|
||||
cb(restic.Hash(buf), false, len(buf), nil)
|
||||
cb(restic.Hash(buf.Data), false, len(buf.Data), nil)
|
||||
}()
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,9 @@ func ParseConfig(s string) (*Config, error) {
|
||||
// If the repository location cannot be parsed as a valid URL, it will be returned as is
|
||||
// (it's because this function is used for logging errors)
|
||||
func StripPassword(s string) string {
|
||||
if len(s) < 5 {
|
||||
return s
|
||||
}
|
||||
scheme := s[:5]
|
||||
s = prepareURL(s)
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ func drainAndClose(resp *http.Response) error {
|
||||
|
||||
// return first error
|
||||
if err != nil {
|
||||
return errors.Errorf("drain: %w", err)
|
||||
return errors.Errorf("drain: %v", err)
|
||||
}
|
||||
return cerr
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func runRESTServer(ctx context.Context, t testing.TB, dir, reqListenAddr string)
|
||||
select {
|
||||
case <-processCtx.Done():
|
||||
t.Fatal(context.Canceled)
|
||||
case <-time.NewTimer(2 * time.Second).C:
|
||||
case <-time.NewTimer(10 * time.Second).C:
|
||||
t.Fatal(context.DeadlineExceeded)
|
||||
case a, ok := <-listenAddrCh:
|
||||
if !ok {
|
||||
|
||||
@@ -17,6 +17,10 @@ type Config struct {
|
||||
Args string `option:"args" help:"specify arguments for ssh"`
|
||||
|
||||
Connections uint `option:"connections" help:"set a limit for the number of concurrent connections (default: 5)"`
|
||||
|
||||
// SSH options
|
||||
ServerAliveInterval uint `option:"server-alive-interval" help:"set the ssh ServerAliveInterval option in seconds (default: use ssh config)"`
|
||||
ServerAliveCountMax uint `option:"server-alive-count-max" help:"set the ssh ServerAliveCountMax option (default: use ssh config)"`
|
||||
}
|
||||
|
||||
// NewConfig returns a new config with default options applied.
|
||||
|
||||
@@ -257,6 +257,12 @@ func buildSSHCommand(cfg Config) (cmd string, args []string, err error) {
|
||||
if cfg.User != "" {
|
||||
args = append(args, "-l", cfg.User)
|
||||
}
|
||||
if cfg.ServerAliveInterval > 0 {
|
||||
args = append(args, "-o", fmt.Sprintf("ServerAliveInterval=%d", cfg.ServerAliveInterval))
|
||||
}
|
||||
if cfg.ServerAliveCountMax > 0 {
|
||||
args = append(args, "-o", fmt.Sprintf("ServerAliveCountMax=%d", cfg.ServerAliveCountMax))
|
||||
}
|
||||
|
||||
if cfg.Args != "" {
|
||||
a, err := backend.SplitShellStrings(cfg.Args)
|
||||
|
||||
@@ -61,6 +61,30 @@ var sshcmdTests = []struct {
|
||||
[]string{"::1%lo0", "-p", "22", "-l", "user", "-s", "sftp"},
|
||||
"",
|
||||
},
|
||||
{
|
||||
Config{User: "user", Host: "host", Path: "dir", ServerAliveInterval: 99},
|
||||
"ssh",
|
||||
[]string{"host", "-l", "user", "-o", "ServerAliveInterval=99", "-s", "sftp"},
|
||||
"",
|
||||
},
|
||||
{
|
||||
Config{User: "user", Host: "host", Path: "dir", ServerAliveCountMax: 99},
|
||||
"ssh",
|
||||
[]string{"host", "-l", "user", "-o", "ServerAliveCountMax=99", "-s", "sftp"},
|
||||
"",
|
||||
},
|
||||
{
|
||||
Config{User: "user", Host: "host", Path: "dir", ServerAliveInterval: 99, ServerAliveCountMax: 99},
|
||||
"ssh",
|
||||
[]string{"host", "-l", "user", "-o", "ServerAliveInterval=99", "-o", "ServerAliveCountMax=99", "-s", "sftp"},
|
||||
"",
|
||||
},
|
||||
{
|
||||
Config{User: "user", Host: "host", Path: "dir", ServerAliveInterval: 99, ServerAliveCountMax: 99, Args: "-i /path/to/id_rsa"},
|
||||
"ssh",
|
||||
[]string{"host", "-l", "user", "-o", "ServerAliveInterval=99", "-o", "ServerAliveCountMax=99", "-i", "/path/to/id_rsa", "-s", "sftp"},
|
||||
"",
|
||||
},
|
||||
}
|
||||
|
||||
func TestBuildSSHCommand(t *testing.T) {
|
||||
@@ -68,6 +92,9 @@ func TestBuildSSHCommand(t *testing.T) {
|
||||
t.Run("", func(t *testing.T) {
|
||||
cmd, args, err := buildSSHCommand(test.cfg)
|
||||
if test.err != "" {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error %v got nil", test.err)
|
||||
}
|
||||
if err.Error() != test.err {
|
||||
t.Fatalf("expected error %v got %v", test.err, err.Error())
|
||||
}
|
||||
|
||||
@@ -204,12 +204,18 @@ func (c *Checker) Structure(ctx context.Context, p restic.Counter, errChan chan<
|
||||
func (c *Checker) checkTree(id restic.ID, tree data.TreeNodeIterator) (errs []error) {
|
||||
debug.Log("checking tree %v", id)
|
||||
|
||||
for item := range tree {
|
||||
if item.Error != nil {
|
||||
errs = append(errs, &Error{TreeID: id, Err: errors.Errorf("failed to decode tree %v: %w", id, item.Error)})
|
||||
for item := range data.EnforceTreeOrder(tree) {
|
||||
if errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
errs = append(errs, &Error{TreeID: id, Err: item.Error})
|
||||
} else if item.Error != nil {
|
||||
errs = append(errs, &Error{TreeID: id, Err: errors.Errorf("failed to decode tree %v: %v", id, item.Error)})
|
||||
break
|
||||
}
|
||||
|
||||
node := item.Node
|
||||
if node == nil {
|
||||
continue
|
||||
}
|
||||
switch node.Type {
|
||||
case data.NodeTypeFile:
|
||||
if node.Content == nil {
|
||||
@@ -285,15 +291,18 @@ func (c *Checker) UnusedBlobs(ctx context.Context) (blobs restic.BlobHandles, er
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
err = c.repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
for blob := range c.repo.ListBlobs() {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return blobs, err
|
||||
}
|
||||
h := blob.Handle()
|
||||
if !c.blobRefs.M.Has(h) {
|
||||
debug.Log("blob %v not referenced", h)
|
||||
blobs = append(blobs, h)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return blobs, err
|
||||
return blobs, nil
|
||||
}
|
||||
|
||||
// ReadPacks wraps repository.ReadPacks:
|
||||
|
||||
@@ -631,6 +631,52 @@ func benchmarkSnapshotScaling(t *testing.B, newSnapshots int) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckerUnorderedTree(t *testing.T) {
|
||||
repo := repository.TestRepository(t)
|
||||
ctx := t.Context()
|
||||
|
||||
var rootID restic.ID
|
||||
test.OK(t, repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
|
||||
rootID = data.TestSaveUnorderedSampleTree(t, ctx, uploader)
|
||||
return nil
|
||||
}))
|
||||
|
||||
snapshot, err := data.NewSnapshot([]string{"/"}, nil, "test", time.Now())
|
||||
test.OK(t, err)
|
||||
snapshot.Tree = &rootID
|
||||
_, err = data.SaveSnapshot(ctx, repo, snapshot)
|
||||
test.OK(t, err)
|
||||
|
||||
chkr := checker.New(repo, true)
|
||||
hints, errs := chkr.LoadIndex(ctx, restic.NoopTerminalCounterFactory)
|
||||
if len(errs) > 0 {
|
||||
t.Fatalf("expected no index errors, got %v", errs)
|
||||
}
|
||||
if len(hints) > 0 {
|
||||
t.Fatalf("expected no index hints, got %v", hints)
|
||||
}
|
||||
|
||||
var unordered int
|
||||
for _, err := range checkStruct(chkr) {
|
||||
treeErr, ok := err.(*checker.TreeError)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected error %T %v", err, err)
|
||||
}
|
||||
for _, treeErr := range treeErr.Errors {
|
||||
checkErr, ok := treeErr.(*checker.Error)
|
||||
if !ok || !errors.Is(checkErr.Err, data.ErrTreeNotOrdered) {
|
||||
t.Fatalf("unexpected tree error %v", treeErr)
|
||||
}
|
||||
unordered++
|
||||
}
|
||||
}
|
||||
test.Equals(t, 2, unordered)
|
||||
|
||||
unused, err := chkr.UnusedBlobs(ctx)
|
||||
test.OK(t, err)
|
||||
test.Equals(t, 0, len(unused))
|
||||
}
|
||||
|
||||
func BenchmarkCheckerSnapshotScaling(b *testing.B) {
|
||||
counts := []int{50, 100, 200}
|
||||
for _, count := range counts {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/restic/restic/internal/errors"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
|
||||
"github.com/restic/restic/internal/debug"
|
||||
)
|
||||
@@ -134,7 +135,7 @@ func (node Node) String() string {
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s %5d %5d %6d %s %s",
|
||||
mode|node.Mode, node.UID, node.GID, node.Size, node.ModTime, node.Name)
|
||||
mode|node.Mode, node.UID, node.GID, node.Size, node.ModTime, ui.Quote(node.Name))
|
||||
}
|
||||
|
||||
// GetExtendedAttribute gets the extended attribute.
|
||||
@@ -400,7 +401,7 @@ func handleUnknownGenericAttributeFound(genericAttributeType GenericAttributeTyp
|
||||
debug.Log("Ignoring a generic attribute found in the repository: %s which may not be compatible with your OS. Compatible OS: %s", genericAttributeType, os)
|
||||
} else {
|
||||
// If genericAttributesForOS in node.go does not know about this attribute, then the repository may have been created by a newer version which has a newer GenericAttributeType.
|
||||
warn(fmt.Sprintf("Found an unrecognized generic attribute in the repository: %s. You may need to upgrade to latest version of restic.", genericAttributeType))
|
||||
warn(fmt.Sprintf("Found an unrecognized generic attribute in the repository: %s. You may need to upgrade to latest version of restic.", ui.Quote(string(genericAttributeType))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package data
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -93,3 +95,11 @@ func TestSymlinkSerializationFormat(t *testing.T) {
|
||||
test.Assert(t, n2.LinkTargetRaw == nil, "quoted link target is just a helper field and must be unset after decoding")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNodeStringQuotesName(t *testing.T) {
|
||||
ordinary := Node{Name: "file", UID: 1, GID: 2}.String()
|
||||
test.Assert(t, strings.HasSuffix(ordinary, " file"), "ordinary name was quoted: %s", ordinary)
|
||||
|
||||
quoted := Node{Name: "a\nb", UID: 1, GID: 2}.String()
|
||||
test.Assert(t, strings.HasSuffix(quoted, " "+strconv.Quote("a\nb")), "hostile name was not quoted: %s", quoted)
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/restic/restic/internal/debug"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
)
|
||||
|
||||
// Snapshot is the state of a resource at one point in time.
|
||||
@@ -119,7 +120,7 @@ func ForAllSnapshots(ctx context.Context, be restic.Lister, loader restic.Loader
|
||||
|
||||
func (sn Snapshot) String() string {
|
||||
return fmt.Sprintf("snapshot %s of %v at %s by %s@%s",
|
||||
sn.id.Str(), sn.Paths, sn.Time, sn.Username, sn.Hostname)
|
||||
sn.id.Str(), ui.QuoteSlice(sn.Paths), sn.Time, ui.Quote(sn.Username), ui.Quote(sn.Hostname))
|
||||
}
|
||||
|
||||
// ID returns the snapshot's ID.
|
||||
@@ -178,11 +179,15 @@ func (sn *Snapshot) hasTag(tag string) bool {
|
||||
return slices.Contains(sn.Tags, tag)
|
||||
}
|
||||
|
||||
// HasTags returns true if the snapshot has all the tags in l.
|
||||
// HasTags returns true if the snapshot has all the tags in l. The empty tag
|
||||
// only matches a snapshot without any tags.
|
||||
func (sn *Snapshot) HasTags(l []string) bool {
|
||||
for _, tag := range l {
|
||||
if tag == "" && len(sn.Tags) == 0 {
|
||||
return true
|
||||
if tag == "" {
|
||||
if len(sn.Tags) != 0 {
|
||||
return false
|
||||
}
|
||||
continue // Continue here to ensure that any other tag in `l` will result in no match.
|
||||
}
|
||||
if !sn.hasTag(tag) {
|
||||
return false
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/restic/restic/internal/ui"
|
||||
)
|
||||
|
||||
type SnapshotGroupByOptions struct {
|
||||
@@ -69,13 +71,13 @@ type SnapshotGroupKey struct {
|
||||
func (s *SnapshotGroupKey) String() string {
|
||||
var parts []string
|
||||
if s.Hostname != "" {
|
||||
parts = append(parts, fmt.Sprintf("host %v", s.Hostname))
|
||||
parts = append(parts, fmt.Sprintf("host %v", ui.Quote(s.Hostname)))
|
||||
}
|
||||
if len(s.Paths) != 0 {
|
||||
parts = append(parts, fmt.Sprintf("path %v", s.Paths))
|
||||
parts = append(parts, fmt.Sprintf("path %v", ui.QuoteSlice(s.Paths)))
|
||||
}
|
||||
if len(s.Tags) != 0 {
|
||||
parts = append(parts, fmt.Sprintf("tags %v", s.Tags))
|
||||
parts = append(parts, fmt.Sprintf("tags %v", ui.QuoteSlice(s.Tags)))
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package data_test
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
@@ -48,3 +49,15 @@ func TestGroupByOptions(t *testing.T) {
|
||||
test.Assert(t, err != nil, "missing error on invalid tags")
|
||||
test.Assert(t, !opts.Host && !opts.Path && !opts.Tag, "unexpected opts %s %s %s", opts.Host, opts.Path, opts.Tag)
|
||||
}
|
||||
|
||||
func TestSnapshotGroupKeyStringQuotes(t *testing.T) {
|
||||
ordinary := (&data.SnapshotGroupKey{Hostname: "host", Paths: []string{"/ok"}, Tags: []string{"tag"}}).String()
|
||||
test.Equals(t, "host host, path [/ok], tags [tag]", ordinary)
|
||||
|
||||
hostile := (&data.SnapshotGroupKey{
|
||||
Hostname: "a\nb",
|
||||
Paths: []string{"/ok", "p\nq"},
|
||||
Tags: []string{"t\tu"},
|
||||
}).String()
|
||||
test.Equals(t, "host "+strconv.Quote("a\nb")+", path [/ok "+strconv.Quote("p\nq")+"], tags ["+strconv.Quote("t\tu")+"]", hostile)
|
||||
}
|
||||
@@ -19,12 +19,29 @@ func TestNewSnapshot(t *testing.T) {
|
||||
|
||||
func TestTagList(t *testing.T) {
|
||||
paths := []string{"/home/foobar"}
|
||||
tags := []string{""}
|
||||
|
||||
sn, _ := data.NewSnapshot(paths, nil, "foo", time.Now())
|
||||
for _, test := range []struct {
|
||||
snapshotTags []string
|
||||
filterTags []string
|
||||
match bool
|
||||
}{
|
||||
{nil, []string{""}, true},
|
||||
{[]string{"foo"}, []string{""}, false},
|
||||
{nil, []string{"foo"}, false},
|
||||
{[]string{"foo"}, []string{"foo"}, true},
|
||||
// the empty tag requires an untagged snapshot, so it can never be
|
||||
// combined with another tag, no matter in which order they are given
|
||||
{nil, []string{"", "foo"}, false},
|
||||
{nil, []string{"foo", ""}, false},
|
||||
{[]string{"foo"}, []string{"", "foo"}, false},
|
||||
{[]string{"foo"}, []string{"foo", ""}, false},
|
||||
} {
|
||||
sn, err := data.NewSnapshot(paths, test.snapshotTags, "foo", time.Now())
|
||||
rtest.OK(t, err)
|
||||
|
||||
r := sn.HasTags(tags)
|
||||
rtest.Assert(t, r, "Failed to match untagged snapshot")
|
||||
rtest.Assert(t, sn.HasTags(test.filterTags) == test.match,
|
||||
"expected %v for snapshot tags %v and filter %v", test.match, test.snapshotTags, test.filterTags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadJSONUnpacked(t *testing.T) {
|
||||
@@ -49,3 +66,15 @@ func testLoadJSONUnpacked(t *testing.T, version uint) {
|
||||
rtest.Equals(t, sn.Hostname, sn2.Hostname)
|
||||
rtest.Equals(t, sn.Username, sn2.Username)
|
||||
}
|
||||
|
||||
func TestSnapshotStringQuotesFields(t *testing.T) {
|
||||
ordinary := data.Snapshot{Paths: []string{"/home"}, Username: "alice", Hostname: "box"}.String()
|
||||
rtest.Equals(t, "snapshot [nil] of [/home] at 0001-01-01 00:00:00 +0000 UTC by alice@box", ordinary)
|
||||
|
||||
hostile := data.Snapshot{
|
||||
Paths: []string{"/ok", "a\nb"},
|
||||
Username: "u\nv",
|
||||
Hostname: "host",
|
||||
}.String()
|
||||
rtest.Equals(t, `snapshot [nil] of [/ok "a\nb"] at 0001-01-01 00:00:00 +0000 UTC by "u\nv"@host`, hostile)
|
||||
}
|
||||
@@ -2,7 +2,10 @@ package data
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/restic/restic/internal/ui"
|
||||
)
|
||||
|
||||
// TagList is a list of tags.
|
||||
@@ -10,21 +13,30 @@ type TagList []string
|
||||
|
||||
// splitTagList splits a string into a list of tags. The tags in the string
|
||||
// need to be separated by commas. Whitespace is stripped around the individual
|
||||
// tags.
|
||||
func splitTagList(s string) (l TagList) {
|
||||
// tags. The empty tag only matches snapshots without any tags, so it is
|
||||
// rejected unless it is the only tag in the list.
|
||||
func splitTagList(s string) (TagList, error) {
|
||||
var l TagList
|
||||
for t := range strings.SplitSeq(s, ",") {
|
||||
l = append(l, strings.TrimSpace(t))
|
||||
}
|
||||
return l
|
||||
if len(l) > 1 && slices.Contains(l, "") {
|
||||
return nil, fmt.Errorf("invalid tag list %q, the empty tag must be the only tag in the list", s)
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func (l TagList) String() string {
|
||||
return "[" + strings.Join(l, ", ") + "]"
|
||||
return "[" + strings.Join(ui.QuoteSlice(l), ", ") + "]"
|
||||
}
|
||||
|
||||
// Set updates the TagList's value.
|
||||
func (l *TagList) Set(s string) error {
|
||||
*l = splitTagList(s)
|
||||
tags, err := splitTagList(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*l = tags
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -56,7 +68,11 @@ func (l TagLists) Flatten() (tags TagList) {
|
||||
|
||||
// Set updates the TagList's value.
|
||||
func (l *TagLists) Set(s string) error {
|
||||
*l = append(*l, splitTagList(s))
|
||||
tags, err := splitTagList(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*l = append(*l, tags)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package data
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
@@ -44,3 +45,42 @@ func TestTagLists_Flatten(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagListSet(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
value string
|
||||
want TagList
|
||||
}{
|
||||
{"", TagList{""}},
|
||||
{"foo", TagList{"foo"}},
|
||||
{"foo,bar", TagList{"foo", "bar"}},
|
||||
{" foo , bar ", TagList{"foo", "bar"}},
|
||||
} {
|
||||
var l TagList
|
||||
rtest.OK(t, l.Set(test.value))
|
||||
rtest.Equals(t, test.want, l)
|
||||
|
||||
var ls TagLists
|
||||
rtest.OK(t, ls.Set(test.value))
|
||||
rtest.Equals(t, TagLists{test.want}, ls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagListSetInvalid(t *testing.T) {
|
||||
// the empty tag only matches snapshots without any tags, so a list that
|
||||
// mixes it with another tag can never match and is rejected
|
||||
for _, value := range []string{",", ",foo", "foo,", "foo,,bar", "foo, ,bar"} {
|
||||
var l TagList
|
||||
rtest.Assert(t, l.Set(value) != nil, "missing error for tag list %q", value)
|
||||
rtest.Equals(t, TagList(nil), l)
|
||||
|
||||
var ls TagLists
|
||||
rtest.Assert(t, ls.Set(value) != nil, "missing error for tag list %q", value)
|
||||
rtest.Equals(t, TagLists(nil), ls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagListStringQuotes(t *testing.T) {
|
||||
rtest.Equals(t, "[ok, plain]", TagList{"ok", "plain"}.String())
|
||||
rtest.Equals(t, "[ok, "+strconv.Quote("a\nb")+"]", TagList{"ok", "a\nb"}.String())
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package data
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -124,6 +126,49 @@ func TestSaveNodes(t testing.TB, ctx context.Context, uploader restic.BlobSaver,
|
||||
return id
|
||||
}
|
||||
|
||||
// TestSaveUnorderedTree stores nodes in the given order, including orders that
|
||||
// TreeJSONBuilder would reject.
|
||||
//
|
||||
//nolint:revive // as this is a test helper, t should go first
|
||||
func TestSaveUnorderedTree(t testing.TB, ctx context.Context, saver restic.BlobSaver, nodes []*Node) restic.ID {
|
||||
t.Helper()
|
||||
|
||||
buf, err := json.Marshal(struct {
|
||||
Nodes []*Node `json:"nodes"`
|
||||
}{Nodes: nodes})
|
||||
rtest.OK(t, err)
|
||||
|
||||
id, _, _, err := saver.SaveBlob(ctx, restic.TreeBlob, buf, restic.ID{}, false)
|
||||
rtest.OK(t, err)
|
||||
return id
|
||||
}
|
||||
|
||||
// TestSaveUnorderedSampleTree stores a tree whose names are not strictly ordered.
|
||||
// The root is saved as file "m", directory "sub", file "a", file "z".
|
||||
// "sub" is saved as file "m", file "a". Both "a" entries are out of order.
|
||||
//
|
||||
//nolint:revive // as this is a test helper, t should go first
|
||||
func TestSaveUnorderedSampleTree(t testing.TB, ctx context.Context, saver restic.BlobSaver) restic.ID {
|
||||
t.Helper()
|
||||
file := func(name string) *Node {
|
||||
return &Node{
|
||||
Name: name,
|
||||
Type: NodeTypeFile,
|
||||
Mode: 0644,
|
||||
UID: uint32(os.Getuid()),
|
||||
GID: uint32(os.Getgid()),
|
||||
Content: restic.IDs{},
|
||||
}
|
||||
}
|
||||
childID := TestSaveUnorderedTree(t, ctx, saver, []*Node{file("m"), file("a")})
|
||||
return TestSaveUnorderedTree(t, ctx, saver, []*Node{
|
||||
file("m"),
|
||||
{Name: "sub", Type: NodeTypeDir, Mode: 0755, UID: uint32(os.Getuid()), GID: uint32(os.Getgid()), Subtree: &childID},
|
||||
file("a"),
|
||||
file("z"),
|
||||
})
|
||||
}
|
||||
|
||||
// TestCreateSnapshot creates a snapshot filled with fake data. The
|
||||
// fake data is generated deterministically from the timestamp `at`, which is
|
||||
// also used as the snapshot's timestamp. The tree's depth can be specified
|
||||
|
||||
+38
-6
@@ -68,6 +68,36 @@ func NewTreeNodeIterator(rd io.Reader) (TreeNodeIterator, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// EnforceTreeOrder wraps a TreeNodeIterator to only yield nodes in strictly
|
||||
// increasing name order. Out of order items are returned with a ErrTreeNotOrdered
|
||||
// error, which will not terminate the iterator.
|
||||
func EnforceTreeOrder(tree TreeNodeIterator) TreeNodeIterator {
|
||||
return func(yield func(NodeOrError) bool) {
|
||||
var lastName string
|
||||
for item := range tree {
|
||||
if item.Error != nil {
|
||||
if !yield(item) {
|
||||
return
|
||||
}
|
||||
// let `tree` decide whether errors stop the iterator
|
||||
continue
|
||||
}
|
||||
node := item.Node
|
||||
if node.Name <= lastName {
|
||||
err := fmt.Errorf("current node %q, last %q: %w", node.Name, lastName, ErrTreeNotOrdered)
|
||||
if !yield(NodeOrError{Node: node, Error: err}) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
lastName = node.Name
|
||||
if !yield(item) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *treeIterator) init() error {
|
||||
// A tree is expected to be encoded as a JSON object with a single key "nodes".
|
||||
// However, for future-proofness, we allow unknown keys before and after the "nodes" key.
|
||||
@@ -272,7 +302,9 @@ func (builder *TreeJSONBuilder) AddNode(node *Node) error {
|
||||
}
|
||||
builder.lastName = node.Name
|
||||
|
||||
val, err := json.Marshal(node)
|
||||
// Call MarshalJSON directly: json.Marshal would only validate and copy its
|
||||
// output, which is already compact.
|
||||
val, err := node.MarshalJSON()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -311,22 +343,22 @@ func FindTreeDirectory(ctx context.Context, repo restic.BlobLoader, id *restic.I
|
||||
subfolder = path.Join(subfolder, name)
|
||||
tree, err := LoadTree(ctx, repo, *id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("path %s: %w", subfolder, err)
|
||||
return nil, fmt.Errorf("path %q: %w", subfolder, err)
|
||||
}
|
||||
finder := NewTreeFinder(tree)
|
||||
node, err := finder.Find(name)
|
||||
finder.Close()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("path %s: %w", subfolder, err)
|
||||
return nil, fmt.Errorf("path %q: %w", subfolder, err)
|
||||
}
|
||||
if node == nil {
|
||||
if runtime.GOOS == "windows" && strings.Contains(dir, "\\") {
|
||||
return nil, fmt.Errorf("path %s: not found; subfolder syntax currently requires forward slashes; check the output of `restic ls` for valid paths", subfolder)
|
||||
return nil, fmt.Errorf("path %q: not found; subfolder syntax currently requires forward slashes; check the output of `restic ls` for valid paths", subfolder)
|
||||
}
|
||||
return nil, fmt.Errorf("path %s: not found", subfolder)
|
||||
return nil, fmt.Errorf("path %q: not found", subfolder)
|
||||
}
|
||||
if node.Type != NodeTypeDir || node.Subtree == nil {
|
||||
return nil, fmt.Errorf("path %s: not a directory", subfolder)
|
||||
return nil, fmt.Errorf("path %q: not a directory", subfolder)
|
||||
}
|
||||
id = node.Subtree
|
||||
}
|
||||
|
||||
@@ -106,6 +106,61 @@ func TestNodeComparison(t *testing.T) {
|
||||
rtest.Assert(t, !node.Equals(n2), "nodes are equal")
|
||||
}
|
||||
|
||||
func TestEnforceTreeOrder(t *testing.T) {
|
||||
nodes := func(names ...string) data.TreeNodeIterator {
|
||||
return func(yield func(data.NodeOrError) bool) {
|
||||
for _, name := range names {
|
||||
if !yield(data.NodeOrError{Node: &data.Node{Name: name}}) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
collect := func(it data.TreeNodeIterator) (names []string, errs []error) {
|
||||
t.Helper()
|
||||
for item := range it {
|
||||
if item.Error != nil {
|
||||
errs = append(errs, item.Error)
|
||||
rtest.Assert(t, item.Node != nil, "unordered item has no node: %v", item.Error)
|
||||
continue
|
||||
}
|
||||
names = append(names, item.Node.Name)
|
||||
}
|
||||
return names, errs
|
||||
}
|
||||
|
||||
names, errs := collect(data.EnforceTreeOrder(nodes("a", "m", "z")))
|
||||
rtest.Equals(t, []string{"a", "m", "z"}, names)
|
||||
rtest.Assert(t, len(errs) == 0, "unexpected errors: %v", errs)
|
||||
|
||||
names, errs = collect(data.EnforceTreeOrder(nodes("m", "a", "z", "m")))
|
||||
rtest.Equals(t, []string{"m", "z"}, names)
|
||||
rtest.Equals(t, 2, len(errs))
|
||||
rtest.Assert(t, errors.Is(errs[0], data.ErrTreeNotOrdered), "wrong error %v", errs[0])
|
||||
rtest.Assert(t, errors.Is(errs[1], data.ErrTreeNotOrdered), "wrong error %v", errs[1])
|
||||
|
||||
var got []string
|
||||
var decode error
|
||||
for item := range data.EnforceTreeOrder(slices.Values([]data.NodeOrError{
|
||||
{Node: &data.Node{Name: "b"}},
|
||||
{Node: &data.Node{Name: "a"}},
|
||||
{Error: errors.New("decode")},
|
||||
{Node: &data.Node{Name: "z"}},
|
||||
})) {
|
||||
if item.Error != nil && !errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
decode = item.Error
|
||||
// continue here to ensure that "z" is yieled even after an error
|
||||
continue
|
||||
}
|
||||
if item.Error != nil {
|
||||
continue
|
||||
}
|
||||
got = append(got, item.Node.Name)
|
||||
}
|
||||
rtest.Equals(t, []string{"b", "z"}, got)
|
||||
rtest.Assert(t, decode != nil && decode.Error() == "decode", "missing decode error, got %v", decode)
|
||||
}
|
||||
|
||||
func TestEmptyLoadTree(t *testing.T) {
|
||||
repo := repository.TestRepository(t)
|
||||
|
||||
@@ -190,7 +245,7 @@ func BenchmarkBuildTree(b *testing.B) {
|
||||
nodes := make([]data.Node, size)
|
||||
for i := range nodes {
|
||||
// Archiver.SaveTree inputs in sorted order, so do that here too.
|
||||
nodes[i].Name = strconv.Itoa(i)
|
||||
nodes[i].Name = fmt.Sprintf("%03d", i)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
@@ -416,8 +471,8 @@ func TestFindTreeDirectory(t *testing.T) {
|
||||
{"", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil},
|
||||
{"/", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil},
|
||||
{".", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil},
|
||||
{"..", restic.ID{}, errors.New("path ..: not found")},
|
||||
{"file-1", restic.ID{}, errors.New("path file-1: not a directory")},
|
||||
{"..", restic.ID{}, errors.New(`path "..": not found`)},
|
||||
{"file-1", restic.ID{}, errors.New(`path "file-1": not a directory`)},
|
||||
{"dir-7", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil},
|
||||
{"/dir-7", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil},
|
||||
{"dir-7/", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil},
|
||||
@@ -436,6 +491,10 @@ func TestFindTreeDirectory(t *testing.T) {
|
||||
|
||||
_, err := data.FindTreeDirectory(context.TODO(), repo, nil, "")
|
||||
rtest.Assert(t, err != nil, "missing error on null tree id")
|
||||
|
||||
_, err = data.FindTreeDirectory(context.TODO(), repo, sn.Tree, "a\nb")
|
||||
rtest.Assert(t, err != nil && strings.Contains(err.Error(), strconv.Quote("a\nb")),
|
||||
"hostile path was not quoted: %v", err)
|
||||
}
|
||||
|
||||
func TestFindTreeDirectoryWindowsBackslashHint(t *testing.T) {
|
||||
@@ -449,7 +508,7 @@ func TestFindTreeDirectoryWindowsBackslashHint(t *testing.T) {
|
||||
rtest.Assert(t, strings.Contains(err.Error(), "forward slashes"),
|
||||
"expected backslash hint on Windows, got %v", err)
|
||||
} else {
|
||||
rtest.Assert(t, err.Error() == `path missing\path: not found`,
|
||||
rtest.Assert(t, err.Error() == `path "missing\\path": not found`,
|
||||
"unexpected err: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/restic/restic/internal/errors"
|
||||
)
|
||||
@@ -67,6 +69,7 @@ func redactHeader(header http.Header) map[string][]string {
|
||||
"Authorization",
|
||||
"X-Auth-Token", // Swift headers
|
||||
"X-Auth-Key",
|
||||
"X-Amz-Security-Token", // Short-lived S3 tokens
|
||||
} {
|
||||
origHeader, hasHeader := header[hdr]
|
||||
if hasHeader {
|
||||
@@ -81,11 +84,48 @@ func restoreHeader(header http.Header, origHeaders map[string][]string) {
|
||||
maps.Copy(header, origHeaders)
|
||||
}
|
||||
|
||||
func secretQueryParam(key string) bool {
|
||||
switch strings.ToLower(key) {
|
||||
// "sig" contains the Azure SAS signature
|
||||
// "x-amz-signature" and "x-amz-security-token" could show up for
|
||||
// presigned s3 URLs although those aren't used at the moment
|
||||
case "sig", "x-amz-signature", "x-amz-security-token":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// redactRequestURL replaces secret query values. It assumes a well-formed query
|
||||
// string and as such does not preserve ordering and encoding.
|
||||
func redactRequestURL(u *url.URL) *url.URL {
|
||||
values := u.Query()
|
||||
changed := false
|
||||
for key, vals := range values {
|
||||
if !secretQueryParam(key) {
|
||||
continue
|
||||
}
|
||||
for i := range vals {
|
||||
vals[i] = "redacted"
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return u
|
||||
}
|
||||
clone := *u
|
||||
clone.RawQuery = values.Encode()
|
||||
return &clone
|
||||
}
|
||||
|
||||
func (tr loggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {
|
||||
// save original auth and redact it
|
||||
origHeaders := redactHeader(req.Header)
|
||||
origURL := req.URL
|
||||
req.URL = redactRequestURL(req.URL)
|
||||
|
||||
trace, err := httputil.DumpRequestOut(req, false)
|
||||
req.URL = origURL
|
||||
if err != nil {
|
||||
Log("DumpRequestOut() error: %v\n", err)
|
||||
} else {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package debug
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/test"
|
||||
@@ -12,12 +16,14 @@ func TestRedactHeader(t *testing.T) {
|
||||
"Authorization",
|
||||
"X-Auth-Token",
|
||||
"X-Auth-Key",
|
||||
"X-Amz-Security-Token",
|
||||
}
|
||||
|
||||
header := make(http.Header)
|
||||
header["Authorization"] = []string{"123"}
|
||||
header["X-Auth-Token"] = []string{"1234"}
|
||||
header["X-Auth-Key"] = []string{"12345"}
|
||||
header["X-Amz-Security-Token"] = []string{"session"}
|
||||
header["Host"] = []string{"my.host"}
|
||||
|
||||
origHeaders := redactHeader(header)
|
||||
@@ -31,6 +37,7 @@ func TestRedactHeader(t *testing.T) {
|
||||
test.Equals(t, "123", header["Authorization"][0])
|
||||
test.Equals(t, "1234", header["X-Auth-Token"][0])
|
||||
test.Equals(t, "12345", header["X-Auth-Key"][0])
|
||||
test.Equals(t, "session", header["X-Amz-Security-Token"][0])
|
||||
test.Equals(t, "my.host", header["Host"][0])
|
||||
|
||||
delete(header, "X-Auth-Key")
|
||||
@@ -42,3 +49,63 @@ func TestRedactHeader(t *testing.T) {
|
||||
_, hasHeader = header["X-Auth-Key"]
|
||||
test.Assert(t, !hasHeader, "Unexpected header: %v", header["X-Auth-Key"])
|
||||
}
|
||||
|
||||
func TestLoggingRoundTripperRedactsSecrets(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
oldLogger, oldEnabled := opts.logger, opts.isEnabled
|
||||
opts.logger = log.New(&buf, "", 0)
|
||||
opts.isEnabled = true
|
||||
t.Cleanup(func() {
|
||||
opts.logger = oldLogger
|
||||
opts.isEnabled = oldEnabled
|
||||
})
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "https://account.blob.core.windows.net/container?comp=list&sig=sas-secret&X-Amz-Signature=aws-secret&X-Amz-Security-Token=query-token", nil)
|
||||
test.OK(t, err)
|
||||
req.Header.Set("Authorization", "basic-secret")
|
||||
req.Header.Set("X-Amz-Security-Token", "header-token")
|
||||
|
||||
var sent *http.Request
|
||||
tr := loggingRoundTripper{RoundTripper: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
sent = r.Clone(r.Context())
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: http.Header{"X-Amz-Security-Token": []string{"response-token"}},
|
||||
Body: io.NopCloser(strings.NewReader("")),
|
||||
Request: r,
|
||||
}, nil
|
||||
})}
|
||||
|
||||
res, err := tr.RoundTrip(req)
|
||||
test.OK(t, err)
|
||||
defer func() {
|
||||
test.OK(t, res.Body.Close())
|
||||
}()
|
||||
test.Equals(t, "response-token", res.Header.Get("X-Amz-Security-Token"))
|
||||
test.Equals(t, "basic-secret", sent.Header.Get("Authorization"))
|
||||
test.Equals(t, "header-token", sent.Header.Get("X-Amz-Security-Token"))
|
||||
test.Equals(t, "sas-secret", sent.URL.Query().Get("sig"))
|
||||
test.Equals(t, "aws-secret", sent.URL.Query().Get("X-Amz-Signature"))
|
||||
test.Equals(t, "query-token", sent.URL.Query().Get("X-Amz-Security-Token"))
|
||||
test.Equals(t, "list", sent.URL.Query().Get("comp"))
|
||||
|
||||
logText := buf.String()
|
||||
for _, secret := range []string{"sas-secret", "aws-secret", "query-token", "header-token", "basic-secret", "response-token"} {
|
||||
test.Assert(t, !strings.Contains(logText, secret), "secret %q leaked into debug log: %s", secret, logText)
|
||||
}
|
||||
test.Assert(t, strings.Contains(logText, "sig=redacted"), "missing redacted sas: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "X-Amz-Signature=redacted"), "missing redacted signature: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "X-Amz-Security-Token=redacted"), "missing redacted query token: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "comp=list"), "ordinary query parameter was dropped: %s", logText)
|
||||
test.Assert(t, strings.Contains(logText, "X-Amz-Security-Token: **redacted**"), "missing redacted header: %s", logText)
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return f(r)
|
||||
}
|
||||
+38
-28
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/restic/restic/internal/bloblru"
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/errors"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
"github.com/restic/restic/internal/walker"
|
||||
"golang.org/x/sync/errgroup"
|
||||
@@ -19,6 +20,8 @@ type Dumper struct {
|
||||
format string
|
||||
repo restic.Loader
|
||||
w io.Writer
|
||||
// Error reports a node that is skipped due to an error. Currently only used to report out-of-order directory entries.
|
||||
Error func(nodePath string, err error)
|
||||
}
|
||||
|
||||
func New(format string, repo restic.Loader, w io.Writer) *Dumper {
|
||||
@@ -27,6 +30,7 @@ func New(format string, repo restic.Loader, w io.Writer) *Dumper {
|
||||
format: format,
|
||||
repo: repo,
|
||||
w: w,
|
||||
Error: func(string, error) {},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +40,7 @@ func (d *Dumper) DumpTree(ctx context.Context, tree data.TreeNodeIterator, rootP
|
||||
// ch is buffered to deal with variable download/write speeds.
|
||||
ch := make(chan *data.Node, 10)
|
||||
wg.Go(func() error {
|
||||
return sendTrees(ctx, d.repo, tree, rootPath, ch)
|
||||
return d.sendTrees(ctx, tree, rootPath, ch)
|
||||
})
|
||||
|
||||
wg.Go(func() error {
|
||||
@@ -52,23 +56,27 @@ func (d *Dumper) DumpTree(ctx context.Context, tree data.TreeNodeIterator, rootP
|
||||
return wg.Wait()
|
||||
}
|
||||
|
||||
func sendTrees(ctx context.Context, repo restic.BlobLoader, nodes data.TreeNodeIterator, rootPath string, ch chan *data.Node) error {
|
||||
func (d *Dumper) sendTrees(ctx context.Context, nodes data.TreeNodeIterator, rootPath string, ch chan *data.Node) error {
|
||||
defer close(ch)
|
||||
|
||||
for item := range nodes {
|
||||
for item := range data.EnforceTreeOrder(nodes) {
|
||||
if item.Error != nil {
|
||||
if errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
d.Error(path.Join(rootPath, item.Node.Name), item.Error)
|
||||
continue
|
||||
}
|
||||
return item.Error
|
||||
}
|
||||
node := item.Node
|
||||
node.Path = path.Join(rootPath, node.Name)
|
||||
if err := sendNodes(ctx, repo, node, ch); err != nil {
|
||||
if err := d.sendNodes(ctx, node, ch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendNodes(ctx context.Context, repo restic.BlobLoader, root *data.Node, ch chan *data.Node) error {
|
||||
func (d *Dumper) sendNodes(ctx context.Context, root *data.Node, ch chan *data.Node) error {
|
||||
select {
|
||||
case ch <- root:
|
||||
case <-ctx.Done():
|
||||
@@ -80,30 +88,32 @@ func sendNodes(ctx context.Context, repo restic.BlobLoader, root *data.Node, ch
|
||||
return nil
|
||||
}
|
||||
|
||||
err := walker.Walk(ctx, repo, *root.Subtree, walker.WalkVisitor{ProcessNode: func(_ restic.ID, nodepath string, node *data.Node, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if node == nil {
|
||||
return walker.Walk(ctx, d.repo, *root.Subtree, walker.WalkVisitor{
|
||||
EnforceTreeOrder: true,
|
||||
ProcessNode: func(_ restic.ID, nodePath string, node *data.Node, err error) error {
|
||||
if errors.Is(err, data.ErrTreeNotOrdered) {
|
||||
d.Error(path.Join(root.Path, nodePath), err)
|
||||
// Skip only this entry. ErrSkipNode would drop the rest of a non-directory.
|
||||
return nil
|
||||
} else if err != nil {
|
||||
return err
|
||||
} else if node == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
node.Path = path.Join(root.Path, nodePath)
|
||||
if node.Type != data.NodeTypeFile && node.Type != data.NodeTypeDir && node.Type != data.NodeTypeSymlink {
|
||||
return nil
|
||||
}
|
||||
|
||||
select {
|
||||
case ch <- node:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
node.Path = path.Join(root.Path, nodepath)
|
||||
|
||||
if node.Type != data.NodeTypeFile && node.Type != data.NodeTypeDir && node.Type != data.NodeTypeSymlink {
|
||||
return nil
|
||||
}
|
||||
|
||||
select {
|
||||
case ch <- node:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
return nil
|
||||
}})
|
||||
|
||||
return err
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// WriteNode writes a file node's contents directly to d's Writer,
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package dump
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/archiver"
|
||||
"github.com/restic/restic/internal/backend"
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/errors"
|
||||
"github.com/restic/restic/internal/fs"
|
||||
"github.com/restic/restic/internal/repository"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
@@ -113,3 +117,51 @@ func WriteTest(t *testing.T, format string, cd CheckDump) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDumpSkipsUnorderedNodes(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
repo := repository.TestRepository(t)
|
||||
|
||||
var rootID restic.ID
|
||||
rtest.OK(t, repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
|
||||
file := func(name string) *data.Node {
|
||||
return &data.Node{Name: name, Type: data.NodeTypeFile, Content: restic.IDs{}}
|
||||
}
|
||||
// "z" stays in order after the skipped file "a".
|
||||
childID := data.TestSaveUnorderedTree(t, ctx, uploader, []*data.Node{file("m"), file("a"), file("z")})
|
||||
skippedID := data.TestSaveUnorderedTree(t, ctx, uploader, []*data.Node{file("kept")})
|
||||
rootID = data.TestSaveUnorderedTree(t, ctx, uploader, []*data.Node{
|
||||
file("m"),
|
||||
{Name: "b", Type: data.NodeTypeDir, Subtree: &skippedID},
|
||||
{Name: "sub", Type: data.NodeTypeDir, Subtree: &childID},
|
||||
file("a"),
|
||||
file("z"),
|
||||
})
|
||||
return nil
|
||||
}))
|
||||
|
||||
tree, err := data.LoadTree(ctx, repo, rootID)
|
||||
rtest.OK(t, err)
|
||||
|
||||
var reported []string
|
||||
dst := &bytes.Buffer{}
|
||||
d := New("tar", repo, dst)
|
||||
d.Error = func(nodePath string, err error) {
|
||||
rtest.Assert(t, errors.Is(err, data.ErrTreeNotOrdered), "unexpected error %v", err)
|
||||
reported = append(reported, nodePath)
|
||||
}
|
||||
rtest.OK(t, d.DumpTree(ctx, tree, "/"))
|
||||
rtest.Equals(t, []string{"/b", "/sub/a", "/a"}, reported)
|
||||
|
||||
var names []string
|
||||
tr := tar.NewReader(dst)
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
rtest.OK(t, err)
|
||||
names = append(names, hdr.Name)
|
||||
}
|
||||
rtest.Equals(t, []string{"m", "sub/", "sub/m", "sub/z", "z"}, names)
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func checkTar(t *testing.T, testDir string, srcTar *bytes.Buffer) error {
|
||||
return err
|
||||
}
|
||||
if target != hdr.Linkname {
|
||||
return fmt.Errorf("symlink target does not match, got %s want %s", target, hdr.Linkname)
|
||||
return fmt.Errorf("symlink target does not match, got %q want %q", target, hdr.Linkname)
|
||||
}
|
||||
default:
|
||||
if match.Size() != hdr.Size {
|
||||
|
||||
@@ -98,7 +98,7 @@ func checkZip(t *testing.T, testDir string, srcZip *bytes.Buffer) error {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if target != string(linkName) {
|
||||
return fmt.Errorf("symlink target does not match, got %s want %s", string(linkName), target)
|
||||
return fmt.Errorf("symlink target does not match, got %q want %q", string(linkName), target)
|
||||
}
|
||||
default:
|
||||
if f.Method != zip.Deflate {
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ func Readdirnames(filesystem FS, dir string, flags int) ([]string, error) {
|
||||
entries, err := f.Readdirnames(-1)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, fmt.Errorf("readdirnames %v failed: %w", dir, err)
|
||||
return nil, fmt.Errorf("readdirnames %q failed: %w", dir, err)
|
||||
}
|
||||
|
||||
err = f.Close()
|
||||
|
||||
@@ -74,7 +74,7 @@ func parseMountPoints(list string, msgError ErrorHandler) (volumes map[string]st
|
||||
}
|
||||
for s := range strings.SplitSeq(list, ";") {
|
||||
if v, err := getVolumeNameForVolumeMountPoint(s); err != nil {
|
||||
msgError(s, errors.Errorf("failed to parse vss.exclude-volumes [%s]: %s", s, err))
|
||||
msgError(s, errors.Errorf("failed to parse vss.exclude-volumes %q: %s", s, err))
|
||||
} else {
|
||||
if volumes == nil {
|
||||
volumes = make(map[string]struct{})
|
||||
@@ -137,7 +137,7 @@ func (fs *LocalVss) isMountPointIncluded(mountPoint string) bool {
|
||||
|
||||
volume, err := getVolumeNameForVolumeMountPoint(mountPoint)
|
||||
if err != nil {
|
||||
fs.msgError(mountPoint, errors.Errorf("failed to get volume from mount point [%s]: %s", mountPoint, err))
|
||||
fs.msgError(mountPoint, errors.Errorf("failed to get volume from mount point %q: %s", mountPoint, err))
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ func (fs *LocalVss) snapshotPath(path string) string {
|
||||
}
|
||||
|
||||
if snapshot, err := newVssSnapshot(fs.provider, vssVolume, fs.timeout, includeVolume, fs.msgError); err != nil {
|
||||
fs.msgError(vssVolume, errors.Errorf("failed to create snapshot for [%s]: %s",
|
||||
fs.msgError(vssVolume, errors.Errorf("failed to create snapshot for %q: %s",
|
||||
vssVolume, err))
|
||||
fs.failedSnapshots[volumeNameLower] = struct{}{}
|
||||
} else {
|
||||
|
||||
@@ -24,14 +24,7 @@ func matchStrings(ptrs []string, strs []string) bool {
|
||||
}
|
||||
|
||||
for i, p := range ptrs {
|
||||
if p == "" {
|
||||
return false
|
||||
}
|
||||
matched, err := regexp.MatchString(p, strs[i])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if !matched {
|
||||
if p == "" || !strings.HasPrefix(strs[i], p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -180,12 +173,12 @@ func TestParseMountPoints(t *testing.T) {
|
||||
{``, true},
|
||||
},
|
||||
[]string{
|
||||
`failed to parse vss\.exclude-volumes \[z:\\nonexistent\]:.*`,
|
||||
`failed to parse vss\.exclude-volumes \[c:\\windows\\\]:.*`,
|
||||
`failed to parse vss\.exclude-volumes \[\\\\\?\\Volume\{39b9cac2-bcdb-4d51-97c8-0d0677d607fb\}\\\]:.*`,
|
||||
`failed to get volume from mount point \[c:\\windows\\\]:.*`,
|
||||
`failed to get volume from mount point \[\\\\\?\\Volume\{39b9cac2-bcdb-4d51-97c8-0d0677d607fb\}\\\]:.*`,
|
||||
`failed to get volume from mount point \[\]:.*`,
|
||||
`failed to parse vss.exclude-volumes "z:\\nonexistent":`,
|
||||
`failed to parse vss.exclude-volumes "c:\\windows\\":`,
|
||||
`failed to parse vss.exclude-volumes "\\\\?\\Volume{39b9cac2-bcdb-4d51-97c8-0d0677d607fb}\\":`,
|
||||
`failed to get volume from mount point "c:\\windows\\":`,
|
||||
`failed to get volume from mount point "\\\\?\\Volume{39b9cac2-bcdb-4d51-97c8-0d0677d607fb}\\":`,
|
||||
`failed to get volume from mount point "":`,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -219,7 +219,7 @@ func TestNodeRestoreAt(t *testing.T) {
|
||||
}
|
||||
rtest.OK(t, NodeCreateAt(&test, nodePath))
|
||||
// Restore metadata, restoring all xattrs
|
||||
rtest.OK(t, NodeRestoreMetadata(&test, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) },
|
||||
rtest.OK(t, NodeRestoreMetadata(&test, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", nodePath, msg)) },
|
||||
func(_ string) bool { return true }, ownershipByName))
|
||||
|
||||
fs := NewLocal()
|
||||
@@ -296,7 +296,7 @@ func TestNodeRestoreMetadataError(t *testing.T) {
|
||||
nodePath := filepath.Join(tempdir, node.Name)
|
||||
|
||||
// This will fail because the target file does not exist
|
||||
err := NodeRestoreMetadata(node, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) },
|
||||
err := NodeRestoreMetadata(node, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", nodePath, msg)) },
|
||||
func(_ string) bool { return true }, false)
|
||||
rtest.Assert(t, errors.Is(err, os.ErrNotExist), "failed for an unexpected reason")
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
)
|
||||
|
||||
func lchown(name string, node *data.Node, lookupByName bool, warn func(msg string)) error {
|
||||
@@ -19,14 +20,14 @@ func lchown(name string, node *data.Node, lookupByName bool, warn func(msg strin
|
||||
if id, ok := lookupUid(node.User); ok {
|
||||
uid = id
|
||||
} else if warn != nil {
|
||||
warn(fmt.Sprintf("cannot resolve user %q for %v, using uid %d", node.User, name, uid))
|
||||
warn(fmt.Sprintf("cannot resolve user %q for %s, using uid %d", node.User, ui.Quote(name), uid))
|
||||
}
|
||||
}
|
||||
if node.Group != "" {
|
||||
if id, ok := lookupGid(node.Group); ok {
|
||||
gid = id
|
||||
} else if warn != nil {
|
||||
warn(fmt.Sprintf("cannot resolve group %q for %v, using gid %d", node.Group, name, gid))
|
||||
warn(fmt.Sprintf("cannot resolve group %q for %s, using gid %d", node.Group, ui.Quote(name), gid))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-17
@@ -115,7 +115,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, _ bool, _ func(for
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return errors.Errorf("get EA failed while opening file handle for path %v, with: %v", path, err)
|
||||
return errors.Errorf("get EA failed while opening file handle for path %q, with: %v", path, err)
|
||||
}
|
||||
defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call
|
||||
//Get the windows Extended Attributes using the file handle
|
||||
@@ -123,7 +123,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, _ bool, _ func(for
|
||||
extAtts, err = fgetEA(fileHandle)
|
||||
debug.Log("fillExtendedAttributes(%v) %v", path, extAtts)
|
||||
if err != nil {
|
||||
return errors.Errorf("get EA failed for path %v, with: %v", path, err)
|
||||
return errors.Errorf("get EA failed for path %q, with: %v", path, err)
|
||||
}
|
||||
if len(extAtts) == 0 {
|
||||
return nil
|
||||
@@ -157,7 +157,7 @@ func restoreExtendedAttributes(nodeType data.NodeType, path string, eas []extend
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return errors.Errorf("set EA failed while opening file handle for path %v, with: %v", path, err)
|
||||
return errors.Errorf("set EA failed while opening file handle for path %q, with: %v", path, err)
|
||||
}
|
||||
defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call
|
||||
|
||||
@@ -182,7 +182,7 @@ func restoreExtendedAttributes(nodeType data.NodeType, path string, eas []extend
|
||||
}
|
||||
|
||||
if err = fsetEA(fileHandle, eas); err != nil {
|
||||
return errors.Errorf("set EA failed for path %v, with: %v", path, err)
|
||||
return errors.Errorf("set EA failed for path %q, with: %v", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -195,21 +195,21 @@ func nodeRestoreGenericAttributes(node *data.Node, path string, warn func(msg st
|
||||
var errs []error
|
||||
windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error parsing generic attribute for: %s : %v", path, err)
|
||||
return fmt.Errorf("error parsing generic attribute for: %q : %v", path, err)
|
||||
}
|
||||
if windowsAttributes.CreationTime != nil {
|
||||
if err := restoreCreationTime(path, windowsAttributes.CreationTime); err != nil {
|
||||
errs = append(errs, fmt.Errorf("error restoring creation time for: %s : %v", path, err))
|
||||
errs = append(errs, fmt.Errorf("error restoring creation time for: %q : %v", path, err))
|
||||
}
|
||||
}
|
||||
if windowsAttributes.FileAttributes != nil {
|
||||
if err := restoreFileAttributes(path, windowsAttributes.FileAttributes); err != nil {
|
||||
errs = append(errs, fmt.Errorf("error restoring file attributes for: %s : %v", path, err))
|
||||
errs = append(errs, fmt.Errorf("error restoring file attributes for: %q : %v", path, err))
|
||||
}
|
||||
}
|
||||
if windowsAttributes.SecurityDescriptor != nil {
|
||||
if err := setSecurityDescriptor(path, windowsAttributes.SecurityDescriptor); err != nil {
|
||||
errs = append(errs, fmt.Errorf("error restoring security descriptor for: %s : %v", path, err))
|
||||
errs = append(errs, fmt.Errorf("error restoring security descriptor for: %q : %v", path, err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,24 +272,24 @@ func fixEncryptionAttribute(path string, attrs *uint32, pathPointer *uint16) (er
|
||||
// The readonly and system flags will be set again at the end of this func if they are needed.
|
||||
err = ResetPermissions(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err)
|
||||
return fmt.Errorf("failed to encrypt file: failed to reset permissions: %q : %v", path, err)
|
||||
}
|
||||
err = clearSystem(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encrypt file: failed to clear system flag: %s : %v", path, err)
|
||||
return fmt.Errorf("failed to encrypt file: failed to clear system flag: %q : %v", path, err)
|
||||
}
|
||||
err = encryptFile(pathPointer)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed retry to encrypt file: %s : %v", path, err)
|
||||
return fmt.Errorf("failed retry to encrypt file: %q : %v", path, err)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("failed to encrypt file: %s : %v", path, err)
|
||||
return fmt.Errorf("failed to encrypt file: %q : %v", path, err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
existingAttrs, err := windows.GetFileAttributes(pathPointer)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get file attributes for existing file: %s : %v", path, err)
|
||||
return fmt.Errorf("failed to get file attributes for existing file: %q : %v", path, err)
|
||||
}
|
||||
if existingAttrs&windows.FILE_ATTRIBUTE_ENCRYPTED != 0 {
|
||||
// File should not be encrypted, but it's already encrypted. Decrypt it.
|
||||
@@ -300,18 +300,18 @@ func fixEncryptionAttribute(path string, attrs *uint32, pathPointer *uint16) (er
|
||||
// The readonly and system flags will be set again after this func if they are needed.
|
||||
err = ResetPermissions(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err)
|
||||
return fmt.Errorf("failed to encrypt file: failed to reset permissions: %q : %v", path, err)
|
||||
}
|
||||
err = clearSystem(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decrypt file: failed to clear system flag: %s : %v", path, err)
|
||||
return fmt.Errorf("failed to decrypt file: failed to clear system flag: %q : %v", path, err)
|
||||
}
|
||||
err = decryptFile(pathPointer)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed retry to decrypt file: %s : %v", path, err)
|
||||
return fmt.Errorf("failed retry to decrypt file: %q : %v", path, err)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("failed to decrypt file: %s : %v", path, err)
|
||||
return fmt.Errorf("failed to decrypt file: %q : %v", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,10 +33,10 @@ func TestRestoreSecurityDescriptors(t *testing.T) {
|
||||
func testRestoreSecurityDescriptor(t *testing.T, sd string, tempDir string, fileType data.NodeType, fileName string) {
|
||||
// Decode the encoded string SD to get the security descriptor input in bytes.
|
||||
sdInputBytes, err := base64.StdEncoding.DecodeString(sd)
|
||||
test.OK(t, errors.Wrapf(err, "Error decoding SD for: %s", fileName))
|
||||
test.OK(t, errors.Wrapf(err, "Error decoding SD for: %q", fileName))
|
||||
// Wrap the security descriptor bytes in windows attributes and convert to generic attributes.
|
||||
genericAttributes, err := data.WindowsAttrsToGenericAttributes(data.WindowsAttributes{CreationTime: nil, FileAttributes: nil, SecurityDescriptor: &sdInputBytes})
|
||||
test.OK(t, errors.Wrapf(err, "Error constructing windows attributes for: %s", fileName))
|
||||
test.OK(t, errors.Wrapf(err, "Error constructing windows attributes for: %q", fileName))
|
||||
// Construct a Node with the generic attributes.
|
||||
expectedNode := getNode(fileName, fileType, genericAttributes)
|
||||
|
||||
@@ -47,7 +47,7 @@ func testRestoreSecurityDescriptor(t *testing.T, sd string, tempDir string, file
|
||||
|
||||
// Get the security descriptor for the test path after the restore.
|
||||
sdBytesFromRestoredPath, err := getSecurityDescriptor(testPath)
|
||||
test.OK(t, errors.Wrapf(err, "Error while getting the security descriptor for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error while getting the security descriptor for: %q", testPath))
|
||||
|
||||
// Compare the input SD and the SD got from the restored file.
|
||||
compareSecurityDescriptors(t, testPath, sdInputBytes, *sdBytesFromRestoredPath)
|
||||
@@ -239,7 +239,7 @@ func getNode(name string, fileType data.NodeType, genericAttributes map[data.Gen
|
||||
|
||||
func getWindowsAttr(t *testing.T, testPath string, node *data.Node) data.WindowsAttributes {
|
||||
windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes)
|
||||
test.OK(t, errors.Wrapf(err, "Error getting windows attr from generic attr: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting windows attr from generic attr: %q", testPath))
|
||||
test.Assert(t, len(unknownAttribs) == 0, "Unknown attribs found: %s for: %s", unknownAttribs, testPath)
|
||||
return windowsAttributes
|
||||
}
|
||||
@@ -248,7 +248,7 @@ func TestRestoreCreationTime(t *testing.T) {
|
||||
t.Parallel()
|
||||
path := t.TempDir()
|
||||
fi, err := os.Lstat(path)
|
||||
test.OK(t, errors.Wrapf(err, "Could not Lstat for path: %s", path))
|
||||
test.OK(t, errors.Wrapf(err, "Could not Lstat for path: %q", path))
|
||||
attr := fi.Sys().(*syscall.Win32FileAttributeData)
|
||||
creationTimeAttribute := attr.CreationTime
|
||||
//Using the temp dir creation time as the test creation time for the test file and folder
|
||||
@@ -367,17 +367,17 @@ func runGenericAttributesTestForNodes(t *testing.T, expectedNodes []data.Node, t
|
||||
func restoreAndGetNode(t *testing.T, tempDir string, testNode *data.Node, warningExpected bool) (string, *data.Node) {
|
||||
testPath := filepath.Join(tempDir, "001", testNode.Name)
|
||||
err := os.MkdirAll(filepath.Dir(testPath), testNode.Mode)
|
||||
test.OK(t, errors.Wrapf(err, "Failed to create parent directories for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Failed to create parent directories for: %q", testPath))
|
||||
|
||||
if testNode.Type == data.NodeTypeFile {
|
||||
|
||||
testFile, err := os.Create(testPath)
|
||||
test.OK(t, errors.Wrapf(err, "Failed to create test file: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Failed to create test file: %q", testPath))
|
||||
testFile.Close()
|
||||
} else if testNode.Type == data.NodeTypeDir {
|
||||
|
||||
err := os.Mkdir(testPath, testNode.Mode)
|
||||
test.OK(t, errors.Wrapf(err, "Failed to create test directory: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Failed to create test directory: %q", testPath))
|
||||
}
|
||||
|
||||
err = NodeRestoreMetadata(testNode, testPath, func(msg string) {
|
||||
@@ -385,16 +385,16 @@ func restoreAndGetNode(t *testing.T, tempDir string, testNode *data.Node, warnin
|
||||
test.Assert(t, warningExpected, "Warning triggered as expected: %s", msg)
|
||||
} else {
|
||||
// If warning is not expected, this code should not get triggered.
|
||||
test.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", testPath, msg))
|
||||
test.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", testPath, msg))
|
||||
}
|
||||
}, func(_ string) bool { return true }, false)
|
||||
test.OK(t, errors.Wrapf(err, "Failed to restore metadata for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Failed to restore metadata for: %q", testPath))
|
||||
|
||||
fs := NewLocal()
|
||||
meta, err := fs.OpenFile(testPath, O_NOFOLLOW, true)
|
||||
test.OK(t, err)
|
||||
nodeFromFileInfo, err := meta.ToNode(false, t.Logf)
|
||||
test.OK(t, errors.Wrapf(err, "Could not get NodeFromFileInfo for path: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Could not get NodeFromFileInfo for path: %q", testPath))
|
||||
test.OK(t, meta.Close())
|
||||
|
||||
return testPath, nodeFromFileInfo
|
||||
@@ -474,14 +474,14 @@ func TestRestoreExtendedAttributes(t *testing.T) {
|
||||
if node.Type == data.NodeTypeFile || node.Type == data.NodeTypeDir {
|
||||
handle, err = windows.CreateFile(utf16Path, windows.FILE_READ_EA, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
|
||||
}
|
||||
test.OK(t, errors.Wrapf(err, "Error opening file/directory for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error opening file/directory for: %q", testPath))
|
||||
defer func() {
|
||||
err := windows.Close(handle)
|
||||
test.OK(t, errors.Wrapf(err, "Error closing file for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error closing file for: %q", testPath))
|
||||
}()
|
||||
|
||||
extAttr, err := fgetEA(handle)
|
||||
test.OK(t, errors.Wrapf(err, "Error getting extended attributes for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting extended attributes for: %q", testPath))
|
||||
test.Equals(t, len(node.ExtendedAttributes), len(extAttr))
|
||||
|
||||
for _, expectedExtAttr := range node.ExtendedAttributes {
|
||||
|
||||
@@ -109,7 +109,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, ignoreListError bo
|
||||
for _, attr := range xattrs {
|
||||
attrVal, err := getxattr(path, attr)
|
||||
if err != nil {
|
||||
warnf("can not obtain extended attribute %v for %v: %v\n", attr, path, err)
|
||||
warnf("can not obtain extended attribute %q for %q: %v\n", attr, path, err)
|
||||
continue
|
||||
}
|
||||
attr := data.ExtendedAttribute{
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestBackupPrivilegeBypassACL(t *testing.T) {
|
||||
|
||||
// Read-only Open/OpenFile should automatically use FILE_FLAG_BACKUP_SEMANTICS since Go v1.20.
|
||||
testfile, err := os.Open(testPath)
|
||||
test.OK(t, errors.Wrapf(err, "failed to open file for reading: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "failed to open file for reading: %q", testPath))
|
||||
test.OK(t, testfile.Close())
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestRestorePrivilegeBypassACL(t *testing.T) {
|
||||
|
||||
// Writable OpenFile needs explicit FILE_FLAG_BACKUP_SEMANTICS.
|
||||
testfile, err := os.OpenFile(testPath, os.O_WRONLY|windows.O_FILE_FLAG_BACKUP_SEMANTICS, 0)
|
||||
test.OK(t, errors.Wrapf(err, "failed to open file for writing: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "failed to open file for writing: %q", testPath))
|
||||
test.OK(t, testfile.Close())
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func testGetRestrictedFilePath(t *testing.T) string {
|
||||
testPath := filepath.Join(tempDir, "testfile.txt")
|
||||
|
||||
testfile, err := os.Create(testPath)
|
||||
test.OK(t, errors.Wrapf(err, "failed to create temporary file: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "failed to create temporary file: %q", testPath))
|
||||
test.OK(t, testfile.Close())
|
||||
|
||||
// Set restricted permissions.
|
||||
@@ -53,7 +53,7 @@ func testGetRestrictedFilePath(t *testing.T) string {
|
||||
dacl, _, err := sd.DACL()
|
||||
test.OK(t, errors.Wrap(err, "failed to extract SD DACL"))
|
||||
err = windows.SetNamedSecurityInfo(testPath, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil)
|
||||
test.OK(t, errors.Wrapf(err, "failed to set SD: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "failed to set SD: %q", testPath))
|
||||
|
||||
return testPath
|
||||
}
|
||||
@@ -45,14 +45,14 @@ func TestSetGetFolderSecurityDescriptors(t *testing.T) {
|
||||
func testSecurityDescriptors(t *testing.T, testSDs []string, testPath string) {
|
||||
for _, testSD := range testSDs {
|
||||
sdInputBytes, err := base64.StdEncoding.DecodeString(testSD)
|
||||
test.OK(t, errors.Wrapf(err, "Error decoding SD: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error decoding SD: %q", testPath))
|
||||
|
||||
err = setSecurityDescriptor(testPath, &sdInputBytes)
|
||||
test.OK(t, errors.Wrapf(err, "Error setting file security descriptor for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error setting file security descriptor for: %q", testPath))
|
||||
|
||||
var sdOutputBytes *[]byte
|
||||
sdOutputBytes, err = getSecurityDescriptor(testPath)
|
||||
test.OK(t, errors.Wrapf(err, "Error getting file security descriptor for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting file security descriptor for: %q", testPath))
|
||||
|
||||
compareSecurityDescriptors(t, testPath, sdInputBytes, *sdOutputBytes)
|
||||
}
|
||||
|
||||
@@ -42,13 +42,13 @@ func isAdmin() (isAdmin bool, err error) {
|
||||
// compareSecurityDescriptors runs tests for comparing 2 security descriptors in []byte format.
|
||||
func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdOutputBytes []byte) {
|
||||
sdInput, err := securityDescriptorBytesToStruct(sdInputBytes)
|
||||
test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %q", testPath))
|
||||
|
||||
sdOutput, err := securityDescriptorBytesToStruct(sdOutputBytes)
|
||||
test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %q", testPath))
|
||||
|
||||
isAdmin, err := isAdmin()
|
||||
test.OK(t, errors.Wrapf(err, "Error checking if user is admin: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error checking if user is admin: %q", testPath))
|
||||
|
||||
var ownerExpected *windows.SID
|
||||
var defaultedOwnerExpected bool
|
||||
@@ -61,28 +61,28 @@ func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdO
|
||||
|
||||
// The Dacl is set correctly whether or not application is running as admin.
|
||||
daclExpected, defaultedDaclExpected, err = sdInput.DACL()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input dacl for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input dacl for: %q", testPath))
|
||||
|
||||
if isAdmin {
|
||||
// If application is running as admin, all sd values including owner, group, dacl, sacl are set correctly during restore.
|
||||
// Hence we will use the input values for comparison with the output values.
|
||||
ownerExpected, defaultedOwnerExpected, err = sdInput.Owner()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input owner for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input owner for: %q", testPath))
|
||||
groupExpected, defaultedGroupExpected, err = sdInput.Group()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input group for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input group for: %q", testPath))
|
||||
saclExpected, defaultedSaclExpected, err = sdInput.SACL()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input sacl for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting input sacl for: %q", testPath))
|
||||
} else {
|
||||
// If application is not running as admin, owner and group are set as current user's SID/GID during restore and sacl is empty.
|
||||
// Get the current user
|
||||
user, err := user.Current()
|
||||
test.OK(t, errors.Wrapf(err, "Could not get current user for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Could not get current user for: %q", testPath))
|
||||
// Get current user's SID
|
||||
currentUserSID, err := windows.StringToSid(user.Uid)
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath))
|
||||
// Get current user's Group SID
|
||||
currentGroupSID, err := windows.StringToSid(user.Gid)
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath))
|
||||
|
||||
// Set owner and group as current user's SID and GID during restore.
|
||||
ownerExpected = currentUserSID
|
||||
@@ -97,28 +97,28 @@ func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdO
|
||||
// Now do all the comparisons
|
||||
// Get owner SID from output file
|
||||
ownerOut, defaultedOwnerOut, err := sdOutput.Owner()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output owner for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output owner for: %q", testPath))
|
||||
// Compare owner SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs.
|
||||
test.Assert(t, ownerExpected.Equals(ownerOut), "Owner from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, ownerExpected.String(), ownerOut.String())
|
||||
test.Equals(t, defaultedOwnerExpected, defaultedOwnerOut, "Defaulted for owner from SDs read from test path don't match: %s", testPath)
|
||||
|
||||
// Get group SID from output file
|
||||
groupOut, defaultedGroupOut, err := sdOutput.Group()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath))
|
||||
// Compare group SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs.
|
||||
test.Assert(t, groupExpected.Equals(groupOut), "Group from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, groupExpected.String(), groupOut.String())
|
||||
test.Equals(t, defaultedGroupExpected, defaultedGroupOut, "Defaulted for group from SDs read from test path don't match: %s", testPath)
|
||||
|
||||
// Get dacl from output file
|
||||
daclOut, defaultedDaclOut, err := sdOutput.DACL()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output dacl for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output dacl for: %q", testPath))
|
||||
// Compare dacls
|
||||
test.Equals(t, daclExpected, daclOut, "DACL from SDs read from test path don't match: %s", testPath)
|
||||
test.Equals(t, defaultedDaclExpected, defaultedDaclOut, "Defaulted for DACL from SDs read from test path don't match: %s", testPath)
|
||||
|
||||
// Get sacl from output file
|
||||
saclOut, defaultedSaclOut, err := sdOutput.SACL()
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output sacl for: %s", testPath))
|
||||
test.OK(t, errors.Wrapf(err, "Error getting output sacl for: %q", testPath))
|
||||
// Compare sacls
|
||||
test.Equals(t, saclExpected, saclOut, "DACL from SDs read from test path don't match: %s", testPath)
|
||||
test.Equals(t, defaultedSaclExpected, defaultedSaclOut, "Defaulted for SACL from SDs read from test path don't match: %s", testPath)
|
||||
|
||||
@@ -44,7 +44,7 @@ func extendedStat(fi os.FileInfo) *ExtendedFileInfo {
|
||||
func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) {
|
||||
extAttribute, ok := fi.sys.(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return false, fmt.Errorf("could not determine file attributes: %s", fi.Name)
|
||||
return false, fmt.Errorf("could not determine file attributes: %q", fi.Name)
|
||||
}
|
||||
const mask uint32 = unix.SF_DATALESS // 0x40000000
|
||||
if extAttribute.Flags&mask == mask {
|
||||
|
||||
@@ -86,6 +86,6 @@ func TestRecallOnDataAccessMockError(t *testing.T) {
|
||||
|
||||
recall, err := efi.RecallOnDataAccess()
|
||||
rtest.Assert(t, err != nil, "err should be set", err)
|
||||
rtest.Assert(t, err.Error() == "could not determine file attributes: test-file-name", "err message not correct", err)
|
||||
rtest.Assert(t, err.Error() == `could not determine file attributes: "test-file-name"`, "err message not correct", err)
|
||||
rtest.Assert(t, recall == false, "RecallOnDataAccess should be false")
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func extendedStat(fi os.FileInfo) *ExtendedFileInfo {
|
||||
func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) {
|
||||
attrs, ok := fi.sys.(*syscall.Win32FileAttributeData)
|
||||
if !ok {
|
||||
return false, fmt.Errorf("could not determine file attributes: %s", fi.Name)
|
||||
return false, fmt.Errorf("could not determine file attributes: %q", fi.Name)
|
||||
}
|
||||
|
||||
if attrs.FileAttributes&windows.FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS > 0 {
|
||||
|
||||
@@ -969,7 +969,7 @@ func newVssSnapshot(provider string,
|
||||
} else if !isSupported {
|
||||
iVssBackupComponents.Release()
|
||||
return vssSnapshot{}, newVssTextError(fmt.Sprintf("Snapshots are not supported for volume "+
|
||||
"%s", volume))
|
||||
"%q", volume))
|
||||
}
|
||||
|
||||
const retryStartSnapshotSetSleep = 5 * time.Second
|
||||
@@ -1005,7 +1005,7 @@ func newVssSnapshot(provider string,
|
||||
iVssBackupComponents.Release()
|
||||
|
||||
return vssSnapshot{}, newVssTextError(fmt.Sprintf(
|
||||
"failed to enumerate mount points for volume %s: %s", volume, err))
|
||||
"failed to enumerate mount points for volume %q: %s", volume, err))
|
||||
}
|
||||
|
||||
for _, mp := range mountPoints {
|
||||
@@ -1072,7 +1072,7 @@ func newVssSnapshot(provider string,
|
||||
&info.snapshotProperties)
|
||||
if err != nil {
|
||||
msgError(mountPoint, errors.Errorf(
|
||||
"VSS error: GetSnapshotProperties() for mount point %s returned error: ",
|
||||
"VSS error: GetSnapshotProperties() for mount point %q returned error: %v",
|
||||
mountPoint, err))
|
||||
info.isSnapshotted = false
|
||||
} else {
|
||||
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user