mirror of
https://github.com/restic/restic.git
synced 2026-12-04 15:44:46 +00:00
Merge pull request #22209 from MichaelEischer/enforce-ordering
Also enforce node ordering for check, dump and mount
This commit is contained in:
20 files changed
+635
-169
No files matched your search
@@ -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
|
||||
+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", 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)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
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: %w", id, item.Error)})
|
||||
break
|
||||
}
|
||||
|
||||
node := item.Node
|
||||
if node == nil {
|
||||
continue
|
||||
}
|
||||
switch node.Type {
|
||||
case data.NodeTypeFile:
|
||||
if node.Content == nil {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
+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)
|
||||
}
|
||||
+18
-6
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
@@ -33,6 +34,7 @@ type dir struct {
|
||||
inode uint64
|
||||
parentInode uint64
|
||||
node *data.Node
|
||||
location string
|
||||
m sync.Mutex
|
||||
cache treeCache
|
||||
}
|
||||
@@ -41,13 +43,14 @@ func cleanupNodeName(name string) string {
|
||||
return filepath.Base(name)
|
||||
}
|
||||
|
||||
func newDir(root *Root, forget forgetFn, inode, parentInode uint64, node *data.Node) (*dir, error) {
|
||||
func newDir(root *Root, forget forgetFn, inode, parentInode uint64, node *data.Node, location string) (*dir, error) {
|
||||
debug.Log("new dir for %v (%v)", node.Name, node.Subtree)
|
||||
|
||||
return &dir{
|
||||
root: root,
|
||||
forget: forget,
|
||||
node: node,
|
||||
location: location,
|
||||
inode: inode,
|
||||
parentInode: parentInode,
|
||||
cache: *newTreeCache(),
|
||||
@@ -95,8 +98,9 @@ func newDirFromSnapshot(root *Root, forget forgetFn, inode uint64, snapshot *dat
|
||||
Mode: os.ModeDir | 0555,
|
||||
Subtree: snapshot.Tree,
|
||||
},
|
||||
inode: inode,
|
||||
cache: *newTreeCache(),
|
||||
inode: inode,
|
||||
location: "/",
|
||||
cache: *newTreeCache(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -116,8 +120,12 @@ func (d *dir) open(ctx context.Context) error {
|
||||
return unwrapCtxCanceled(err)
|
||||
}
|
||||
items := make(map[string]*data.Node)
|
||||
for item := range tree {
|
||||
for item := range data.EnforceTreeOrder(tree) {
|
||||
if item.Error != nil {
|
||||
if errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
debug.Log("skipping unordered node in %s: %v", d.location, item.Error)
|
||||
continue
|
||||
}
|
||||
return unwrapCtxCanceled(item.Error)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
@@ -130,8 +138,12 @@ func (d *dir) open(ctx context.Context) error {
|
||||
debug.Log(" replaceSpecialNodes(%v) failed: %v", n, err)
|
||||
return err
|
||||
}
|
||||
for item := range nodes {
|
||||
for item := range data.EnforceTreeOrder(nodes) {
|
||||
if item.Error != nil {
|
||||
if errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
debug.Log("skipping unordered node in %s: %v", d.location, item.Error)
|
||||
continue
|
||||
}
|
||||
return unwrapCtxCanceled(item.Error)
|
||||
}
|
||||
items[cleanupNodeName(item.Node.Name)] = item.Node
|
||||
@@ -234,7 +246,7 @@ func (d *dir) Lookup(ctx context.Context, name string) (fs.Node, error) {
|
||||
inode := inodeFromNode(d.inode, node)
|
||||
switch node.Type {
|
||||
case data.NodeTypeDir:
|
||||
return newDir(d.root, forget, inode, d.inode, node)
|
||||
return newDir(d.root, forget, inode, d.inode, node, path.Join(d.location, name))
|
||||
case data.NodeTypeFile:
|
||||
return newFile(d.root, forget, inode, node)
|
||||
case data.NodeTypeSymlink:
|
||||
|
||||
@@ -5,10 +5,13 @@ package fuse
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -163,7 +166,7 @@ func TestFuseDir(t *testing.T) {
|
||||
}
|
||||
parentInode := inodeFromName(0, "parent")
|
||||
inode := inodeFromName(1, "foo")
|
||||
d, err := newDir(root, func() {}, inode, parentInode, node)
|
||||
d, err := newDir(root, func() {}, inode, parentInode, node, "")
|
||||
rtest.OK(t, err)
|
||||
|
||||
// don't open the directory as that would require setting up a proper tree blob
|
||||
@@ -380,6 +383,54 @@ func TestLink(t *testing.T) {
|
||||
rtest.Assert(t, err != nil, "missing error on reading invalid xattr")
|
||||
}
|
||||
|
||||
func TestFuseDirSkipsUnorderedNodes(t *testing.T) {
|
||||
repo := repository.TestRepository(t)
|
||||
ctx := t.Context()
|
||||
|
||||
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
|
||||
}))
|
||||
|
||||
root := &Root{repo: repo, blobCache: bloblru.New(blobCacheSize)}
|
||||
|
||||
d, err := newDir(root, func() {}, 1, 1, &data.Node{
|
||||
Name: "snap",
|
||||
Type: data.NodeTypeDir,
|
||||
Subtree: &rootID,
|
||||
}, "/")
|
||||
rtest.OK(t, err)
|
||||
|
||||
entries, err := d.ReadDirAll(ctx)
|
||||
rtest.OK(t, err)
|
||||
var names []string
|
||||
for _, entry := range entries {
|
||||
if entry.Name == "." || entry.Name == ".." {
|
||||
continue
|
||||
}
|
||||
names = append(names, entry.Name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
rtest.Equals(t, []string{"m", "sub", "z"}, names)
|
||||
|
||||
_, err = d.Lookup(ctx, "a")
|
||||
rtest.Assert(t, errors.Is(err, syscall.ENOENT), "unordered file was exposed: %v", err)
|
||||
|
||||
sub, err := d.Lookup(ctx, "sub")
|
||||
rtest.OK(t, err)
|
||||
subEntries, err := sub.(fs.HandleReadDirAller).ReadDirAll(ctx)
|
||||
rtest.OK(t, err)
|
||||
var subNames []string
|
||||
for _, entry := range subEntries {
|
||||
if entry.Name == "." || entry.Name == ".." {
|
||||
continue
|
||||
}
|
||||
subNames = append(subNames, entry.Name)
|
||||
}
|
||||
rtest.Equals(t, []string{"m"}, subNames)
|
||||
}
|
||||
|
||||
var sink uint64
|
||||
|
||||
func BenchmarkInode(b *testing.B) {
|
||||
|
||||
@@ -169,31 +169,23 @@ func (res *Restorer) traverseTreeInner(ctx context.Context, target, location str
|
||||
filenames = make([]string, 0)
|
||||
}
|
||||
|
||||
// Track the previous node name to enforce the ordering invariant that
|
||||
// tree writers guarantee: names must be strictly increasing. Trees
|
||||
// with duplicate or out-of-order names must be rejected, otherwise a
|
||||
// symlink and a directory sharing a name could make restore write
|
||||
// through the symlink to files outside the restore target.
|
||||
lastName := ""
|
||||
for item := range tree {
|
||||
if item.Error != nil {
|
||||
// Skip out-of-order names to prevent symlink attacks based on duplicate names.
|
||||
for item := range data.EnforceTreeOrder(tree) {
|
||||
if errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
debug.Log("unordered node in tree %v: %v", treeID, item.Error)
|
||||
if err := res.sanitizeError(location, item.Error); err != nil {
|
||||
return nil, hasRestored, err
|
||||
}
|
||||
continue
|
||||
} else if item.Error != nil {
|
||||
debug.Log("error iterating tree %v: %v", treeID, item.Error)
|
||||
// the expected directory content is incomplete, force disable deletion
|
||||
// to avoid removing existing files
|
||||
res.opts.Delete = false
|
||||
return nil, hasRestored, res.sanitizeError(location, item.Error)
|
||||
}
|
||||
node := item.Node
|
||||
|
||||
if node.Name <= lastName {
|
||||
err := fmt.Errorf("node %q, last %q in tree %v: %w", node.Name, lastName, treeID, data.ErrTreeNotOrdered)
|
||||
err = res.sanitizeError(location, err)
|
||||
if err != nil {
|
||||
return nil, hasRestored, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
lastName = node.Name
|
||||
node := item.Node
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return nil, hasRestored, ctx.Err()
|
||||
|
||||
@@ -1572,125 +1572,39 @@ func TestRestorerLongPath(t *testing.T) {
|
||||
rtest.OK(t, err)
|
||||
}
|
||||
|
||||
// saveUnorderedTree saves nodes in the given order without enforcing the
|
||||
// name ordering that TreeJSONBuilder requires. This simulates trees written
|
||||
// by clients that bypass restic's ordering checks.
|
||||
func saveUnorderedTree(t testing.TB, saver restic.BlobSaver, nodes []*data.Node) restic.ID {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
buf, err := json.Marshal(struct {
|
||||
Nodes []*data.Node `json:"nodes"`
|
||||
}{Nodes: nodes})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id, _, _, err := saver.SaveBlob(ctx, restic.TreeBlob, buf, restic.ID{}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func saveSnapshotWithTree(t testing.TB, repo restic.Repository, treeID restic.ID) *data.Snapshot {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
sn, err := data.NewSnapshot([]string{"test"}, nil, "", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sn.Tree = &treeID
|
||||
_, err = data.SaveSnapshot(ctx, repo, sn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sn
|
||||
}
|
||||
|
||||
// TestRestoreDuplicateNodeNames covers https://github.com/restic/restic/issues/22180:
|
||||
// a tree containing a symlink `a` followed by a directory `a` must not let
|
||||
// restore write through the symlink to files outside the target.
|
||||
func TestRestoreDuplicateNodeNames(t *testing.T) {
|
||||
func TestRestoreSkipsUnorderedNodes(t *testing.T) {
|
||||
repo := repository.TestRepository(t)
|
||||
ctx := t.Context()
|
||||
|
||||
uid, gid := uint32(os.Getuid()), uint32(os.Getgid())
|
||||
var treeID restic.ID
|
||||
var rootID restic.ID
|
||||
rtest.OK(t, repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
|
||||
contentID := saveFile(t, uploader, "file")
|
||||
treeID = saveUnorderedTree(t, uploader, []*data.Node{
|
||||
{
|
||||
Type: data.NodeTypeFile, Name: "a", Mode: 0644,
|
||||
UID: uid, GID: gid, Links: 1,
|
||||
Size: 4, Content: restic.IDs{contentID},
|
||||
},
|
||||
{
|
||||
Type: data.NodeTypeSymlink, Name: "a", Mode: os.ModeSymlink | 0777,
|
||||
UID: uid, GID: gid, Links: 1, LinkTarget: "some-symlink-target",
|
||||
},
|
||||
})
|
||||
rootID = data.TestSaveUnorderedSampleTree(t, ctx, uploader)
|
||||
return nil
|
||||
}))
|
||||
|
||||
sn := saveSnapshotWithTree(t, repo, treeID)
|
||||
target := filepath.Join(rtest.TempDir(t), "target")
|
||||
sn, err := data.NewSnapshot([]string{"test"}, nil, "", time.Now())
|
||||
rtest.OK(t, err)
|
||||
sn.Tree = &rootID
|
||||
|
||||
res := NewRestorer(repo, sn, Options{})
|
||||
_, err := res.RestoreTo(ctx, target)
|
||||
if !errors.Is(err, data.ErrTreeNotOrdered) {
|
||||
t.Fatalf("RestoreTo returned error %v, want an error wrapping ErrTreeNotOrdered", err)
|
||||
reported := map[string]struct{}{}
|
||||
res.Error = func(location string, err error) error {
|
||||
rtest.Assert(t, errors.Is(err, data.ErrTreeNotOrdered), "unexpected error %v", err)
|
||||
reported[filepath.ToSlash(location)] = struct{}{}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ensure that restore filtering does not cause file overwrites
|
||||
target = filepath.Join(rtest.TempDir(t), "target")
|
||||
res = NewRestorer(repo, sn, Options{})
|
||||
res.Error = func(location string, err error) error { return nil }
|
||||
target := filepath.Join(rtest.TempDir(t), "target")
|
||||
_, err = res.RestoreTo(ctx, target)
|
||||
rtest.OK(t, err)
|
||||
|
||||
// Ensure file was not replaced by a symlink
|
||||
path := filepath.Join(target, "a")
|
||||
fi, err := os.Lstat(path)
|
||||
rtest.OK(t, err)
|
||||
rtest.Assert(t, fi.Mode()&os.ModeSymlink == 0, "file was replaced by a symlink")
|
||||
content, err := os.ReadFile(path)
|
||||
rtest.OK(t, err)
|
||||
rtest.Assert(t, string(content) == "file", "file contains %q, want %q", content, "file")
|
||||
}
|
||||
|
||||
// TestRestoreUnorderedNodeNames checks that trees whose names are not in
|
||||
// strictly increasing order are rejected even without duplicate names.
|
||||
func TestRestoreUnorderedNodeNames(t *testing.T) {
|
||||
repo := repository.TestRepository(t)
|
||||
ctx := t.Context()
|
||||
|
||||
uid, gid := uint32(os.Getuid()), uint32(os.Getgid())
|
||||
var treeID restic.ID
|
||||
rtest.OK(t, repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
|
||||
contentID := saveFile(t, uploader, "data")
|
||||
treeID = saveUnorderedTree(t, uploader, []*data.Node{
|
||||
{
|
||||
Type: data.NodeTypeFile, Name: "b", Mode: 0644,
|
||||
UID: uid, GID: gid, Inode: 100, Links: 1,
|
||||
Size: 4, Content: restic.IDs{contentID},
|
||||
},
|
||||
{
|
||||
Type: data.NodeTypeFile, Name: "a", Mode: 0644,
|
||||
UID: uid, GID: gid, Inode: 101, Links: 1,
|
||||
Size: 4, Content: restic.IDs{contentID},
|
||||
},
|
||||
})
|
||||
return nil
|
||||
}))
|
||||
|
||||
sn := saveSnapshotWithTree(t, repo, treeID)
|
||||
target := filepath.Join(rtest.TempDir(t), "target")
|
||||
|
||||
res := NewRestorer(repo, sn, Options{})
|
||||
_, err := res.RestoreTo(ctx, target)
|
||||
if !errors.Is(err, data.ErrTreeNotOrdered) {
|
||||
t.Fatalf("RestoreTo returned error %v, want an error wrapping ErrTreeNotOrdered", err)
|
||||
for _, name := range []string{"m", "z", filepath.Join("sub", "m")} {
|
||||
_, err := os.Stat(filepath.Join(target, name))
|
||||
rtest.OK(t, err)
|
||||
}
|
||||
for _, name := range []string{"a", filepath.Join("sub", "a")} {
|
||||
_, err := os.Stat(filepath.Join(target, name))
|
||||
rtest.Assert(t, os.IsNotExist(err), "restored unordered file %s", name)
|
||||
}
|
||||
rtest.Equals(t, map[string]struct{}{"/": {}, "/sub": {}}, reported)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package walker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
|
||||
@@ -14,6 +15,7 @@ type NodeRewriteFunc func(node *data.Node, path string) *data.Node
|
||||
type FailedTreeRewriteFunc func(nodeID restic.ID, path string, err error) (data.TreeNodeIterator, error)
|
||||
type QueryRewrittenSizeFunc func() SnapshotSize
|
||||
type NodeKeepEmptyDirectoryFunc func(path string) bool
|
||||
type DroppedNodeFunc func(parent string, node *data.Node, err error)
|
||||
|
||||
type SnapshotSize struct {
|
||||
FileCount uint
|
||||
@@ -26,6 +28,9 @@ type RewriteOpts struct {
|
||||
KeepEmptyDirectory NodeKeepEmptyDirectoryFunc
|
||||
// decide what to do with a tree that could not be loaded. Return nil to remove the node. By default the load error is returned which causes the operation to fail.
|
||||
RewriteFailedTree FailedTreeRewriteFunc
|
||||
// DroppedNodeFunc is called when a directory entry is not stored due to an error.
|
||||
// Intentional removals are not reported. Currently only used to report out-of-order nodes.
|
||||
ReportDroppedNode DroppedNodeFunc
|
||||
|
||||
AllowUnstableSerialization bool
|
||||
DisableNodeCache bool
|
||||
@@ -66,7 +71,7 @@ func NewTreeRewriter(opts RewriteOpts) *TreeRewriter {
|
||||
return rw
|
||||
}
|
||||
|
||||
func NewSnapshotSizeRewriter(rewriteNode NodeRewriteFunc, keepEmptyDirectoryFilter NodeKeepEmptyDirectoryFunc) (*TreeRewriter, QueryRewrittenSizeFunc) {
|
||||
func NewSnapshotSizeRewriter(rewriteNode NodeRewriteFunc, keepEmptyDirectoryFilter NodeKeepEmptyDirectoryFunc, reportDropped DroppedNodeFunc) (*TreeRewriter, QueryRewrittenSizeFunc) {
|
||||
var count uint
|
||||
var size uint64
|
||||
|
||||
@@ -81,6 +86,7 @@ func NewSnapshotSizeRewriter(rewriteNode NodeRewriteFunc, keepEmptyDirectoryFilt
|
||||
},
|
||||
DisableNodeCache: true,
|
||||
KeepEmptyDirectory: keepEmptyDirectoryFilter,
|
||||
ReportDroppedNode: reportDropped,
|
||||
})
|
||||
|
||||
ss := func() SnapshotSize {
|
||||
@@ -137,10 +143,15 @@ func (t *TreeRewriter) RewriteTree(ctx context.Context, loader restic.BlobLoader
|
||||
debug.Log("filterTree: %s, nodeId: %s\n", nodepath, nodeID.Str())
|
||||
|
||||
tb := data.NewTreeWriter(saver)
|
||||
for item := range curTree {
|
||||
// drop out-of-order nodes to restore the node ordering expect in other parts of restic.
|
||||
for item := range data.EnforceTreeOrder(curTree) {
|
||||
if ctx.Err() != nil {
|
||||
return restic.ID{}, ctx.Err()
|
||||
}
|
||||
if errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
t.reportDropped(nodepath, item.Node, item.Error)
|
||||
continue
|
||||
}
|
||||
if item.Error != nil {
|
||||
return restic.ID{}, item.Error
|
||||
}
|
||||
@@ -193,3 +204,10 @@ func (t *TreeRewriter) RewriteTree(ctx context.Context, loader restic.BlobLoader
|
||||
}
|
||||
return newTreeID, err
|
||||
}
|
||||
|
||||
func (t *TreeRewriter) reportDropped(parent string, node *data.Node, err error) {
|
||||
debug.Log("skipping out-of-order node %q in %s: %v\n", node.Name, parent, err)
|
||||
if t.opts.ReportDroppedNode != nil {
|
||||
t.opts.ReportDroppedNode(parent, node, err)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package walker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
@@ -303,7 +304,7 @@ func TestSnapshotSizeQuery(t *testing.T) {
|
||||
}
|
||||
return node
|
||||
}
|
||||
rewriter, querySize := NewSnapshotSizeRewriter(rewriteNode, nil)
|
||||
rewriter, querySize := NewSnapshotSizeRewriter(rewriteNode, nil, nil)
|
||||
newRoot, err := rewriter.RewriteTree(ctx, modrepo, modrepo, "/", root)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
@@ -426,6 +427,109 @@ func TestRewriterFailOnUnknownFields(t *testing.T) {
|
||||
test.Assert(t, root == expRoot, "mismatched trees")
|
||||
}
|
||||
|
||||
type reportedDrop struct {
|
||||
parent string
|
||||
name string
|
||||
err error
|
||||
typ data.NodeType
|
||||
}
|
||||
|
||||
func collectDrops(dst *[]reportedDrop) DroppedNodeFunc {
|
||||
return func(parent string, node *data.Node, err error) {
|
||||
*dst = append(*dst, reportedDrop{
|
||||
parent: parent,
|
||||
name: node.Name,
|
||||
err: err,
|
||||
typ: node.Type,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertReportedDrops(t *testing.T, exp, got []reportedDrop) {
|
||||
t.Helper()
|
||||
test.Equals(t, len(exp), len(got), "dropped entry count")
|
||||
for i := range exp {
|
||||
test.Equals(t, exp[i].parent, got[i].parent, "parent of dropped entry %q", exp[i].name)
|
||||
test.Equals(t, exp[i].name, got[i].name, "name of dropped entry")
|
||||
test.Equals(t, exp[i].typ, got[i].typ, "type of dropped entry %q", exp[i].name)
|
||||
test.Assert(t, errors.Is(got[i].err, exp[i].err), "dropped entry %q: got error %v", exp[i].name, got[i].err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriterSkipsOutOfOrderNodes(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
t.Run("unsorted and duplicate", func(t *testing.T) {
|
||||
childMap, childID := BuildTreeMap(TestTree{
|
||||
"child": TestFile{},
|
||||
})
|
||||
tm := data.TestWritableTreeMap{TestTreeMap: childMap}
|
||||
|
||||
// "a" sorts before "m", the second "m" is a duplicate, "z" is still in order.
|
||||
root := data.TestSaveUnorderedTree(t, ctx, tm, []*data.Node{
|
||||
{Name: "m", Type: data.NodeTypeFile},
|
||||
{Name: "a", Type: data.NodeTypeDir, Subtree: &childID},
|
||||
{Name: "z", Type: data.NodeTypeFile},
|
||||
{Name: "m", Type: data.NodeTypeFile, Size: 5},
|
||||
})
|
||||
|
||||
var seen []string
|
||||
var dropped []reportedDrop
|
||||
rewriter := NewTreeRewriter(RewriteOpts{
|
||||
RewriteNode: func(node *data.Node, path string) *data.Node {
|
||||
seen = append(seen, path)
|
||||
return node
|
||||
},
|
||||
AllowUnstableSerialization: true,
|
||||
ReportDroppedNode: collectDrops(&dropped),
|
||||
})
|
||||
newRoot, err := rewriter.RewriteTree(ctx, tm, tm, "/", root)
|
||||
test.OK(t, err)
|
||||
|
||||
_, expRoot := BuildTreeMap(TestTree{
|
||||
"m": TestFile{},
|
||||
"z": TestFile{},
|
||||
})
|
||||
test.Equals(t, expRoot, newRoot, "out-of-order nodes should be dropped")
|
||||
test.Equals(t, []string{"/m", "/z"}, seen, "skipped nodes and their children must not be visited")
|
||||
assertReportedDrops(t, []reportedDrop{
|
||||
{parent: "/", name: "a", err: data.ErrTreeNotOrdered, typ: data.NodeTypeDir},
|
||||
{parent: "/", name: "m", err: data.ErrTreeNotOrdered, typ: data.NodeTypeFile},
|
||||
}, dropped)
|
||||
})
|
||||
|
||||
t.Run("nested", func(t *testing.T) {
|
||||
tm := data.TestWritableTreeMap{TestTreeMap: data.TestTreeMap{}}
|
||||
childID := data.TestSaveUnorderedTree(t, ctx, tm, []*data.Node{
|
||||
{Name: "b", Type: data.NodeTypeFile, Size: 2},
|
||||
{Name: "a", Type: data.NodeTypeFile, Size: 9},
|
||||
{Name: "c", Type: data.NodeTypeFile, Size: 3},
|
||||
})
|
||||
root := data.TestSaveUnorderedTree(t, ctx, tm, []*data.Node{
|
||||
{Name: "sub", Type: data.NodeTypeDir, Subtree: &childID},
|
||||
})
|
||||
|
||||
var dropped []reportedDrop
|
||||
rewriter := NewTreeRewriter(RewriteOpts{
|
||||
AllowUnstableSerialization: true,
|
||||
ReportDroppedNode: collectDrops(&dropped),
|
||||
})
|
||||
newRoot, err := rewriter.RewriteTree(ctx, tm, tm, "/", root)
|
||||
test.OK(t, err)
|
||||
|
||||
_, expRoot := BuildTreeMap(TestTree{
|
||||
"sub": TestTree{
|
||||
"b": TestFile{Size: 2},
|
||||
"c": TestFile{Size: 3},
|
||||
},
|
||||
})
|
||||
test.Equals(t, expRoot, newRoot, "nested out-of-order nodes should be dropped")
|
||||
assertReportedDrops(t, []reportedDrop{
|
||||
{parent: "/sub", name: "a", err: data.ErrTreeNotOrdered, typ: data.NodeTypeFile},
|
||||
}, dropped)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRewriterTreeLoadError(t *testing.T) {
|
||||
tm := data.TestWritableTreeMap{TestTreeMap: data.TestTreeMap{}}
|
||||
id := restic.NewRandomID()
|
||||
|
||||
@@ -29,6 +29,8 @@ type WalkVisitor struct {
|
||||
ProcessNode WalkFunc
|
||||
// Optional callback
|
||||
LeaveDir func(path string) error
|
||||
// If true, out-of-order nodes are reported with ErrTreeNotOrdered.
|
||||
EnforceTreeOrder bool
|
||||
}
|
||||
|
||||
// Walk calls walkFn recursively for each node in root. If walkFn returns an
|
||||
@@ -52,13 +54,29 @@ func Walk(ctx context.Context, repo restic.BlobLoader, root restic.ID, visitor W
|
||||
// subtree is in ignoreTrees. If err is nil and ignore is true, the subtree ID
|
||||
// will be added to ignoreTrees by walk.
|
||||
func walk(ctx context.Context, repo restic.BlobLoader, prefix string, parentTreeID restic.ID, tree data.TreeNodeIterator, visitor WalkVisitor) (err error) {
|
||||
if visitor.EnforceTreeOrder {
|
||||
tree = data.EnforceTreeOrder(tree)
|
||||
}
|
||||
for item := range tree {
|
||||
if item.Error != nil {
|
||||
return item.Error
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if errors.Is(item.Error, data.ErrTreeNotOrdered) {
|
||||
p := path.Join(prefix, item.Node.Name)
|
||||
err = visitor.ProcessNode(parentTreeID, p, item.Node, item.Error)
|
||||
if err == ErrSkipNode {
|
||||
if item.Node.Type == data.NodeTypeDir {
|
||||
continue
|
||||
}
|
||||
// skip the remaining entries in this tree
|
||||
break
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
} else if item.Error != nil {
|
||||
return item.Error
|
||||
}
|
||||
node := item.Node
|
||||
|
||||
p := path.Join(prefix, node.Name)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package walker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"testing"
|
||||
@@ -473,3 +474,35 @@ func TestWalker(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkEnforceTreeOrder(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
tm := data.TestWritableTreeMap{TestTreeMap: data.TestTreeMap{}}
|
||||
childID := data.TestSaveUnorderedTree(t, ctx, tm, []*data.Node{
|
||||
{Name: "child", Type: data.NodeTypeFile},
|
||||
})
|
||||
root := data.TestSaveUnorderedTree(t, ctx, tm, []*data.Node{
|
||||
{Name: "m", Type: data.NodeTypeFile},
|
||||
{Name: "a", Type: data.NodeTypeDir, Subtree: &childID},
|
||||
{Name: "z", Type: data.NodeTypeFile},
|
||||
{Name: "m", Type: data.NodeTypeFile},
|
||||
})
|
||||
|
||||
var got []string
|
||||
err := Walk(ctx, tm, root, WalkVisitor{
|
||||
EnforceTreeOrder: true,
|
||||
ProcessNode: func(_ restic.ID, path string, node *data.Node, err error) error {
|
||||
if errors.Is(err, data.ErrTreeNotOrdered) {
|
||||
got = append(got, "skip:"+path)
|
||||
return ErrSkipNode
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
got = append(got, path)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
rtest.Equals(t, []string{"/", "/m", "skip:/a", "/z", "skip:/m"}, got)
|
||||
}
|
||||
Reference in new issue
Block a user