Files
seaweedfs/weed/shell/command_fs_verify_restore_test.go
T
Chris LuandClaude Opus 5.5 4cc4180aa6 shell: fs.verify keeps an entry the restore source may still hold
With -restoreFrom and -pruneEntries, a missing needle the source could
not be read for (an unreadable .idx or a .dat read error), or held
intact but skipped (a cipher-key chunk, a volume-level manifest), let
the entry be pruned, deleting the file whose bytes were on hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 00:55:28 -08:00

413 lines
17 KiB
Go

package shell
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
)
// restoreTestFiler replaces entries under the IF_ENTRY_EQUAL precondition the
// way the filer does. changeBeforeUpdate makes a client write the entry
// between the restore's lookup and its update.
type restoreTestFiler struct {
stubFilerServer
updates []*filer_pb.CreateEntryRequest
changeBeforeUpdate bool
}
func (s *restoreTestFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
path := string(util.NewFullPath(req.Directory, req.Entry.Name))
current := s.entries[path]
if s.changeBeforeUpdate {
current.Attributes.Mtime++
}
for _, clause := range req.GetCondition().GetClauses() {
if clause.Kind == filer_pb.WriteCondition_IF_ENTRY_EQUAL && !proto.Equal(clause.ExpectedEntry, current) {
return &filer_pb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil
}
}
s.updates = append(s.updates, req)
s.entries[path] = req.Entry
return &filer_pb.CreateEntryResponse{}, nil
}
type restoreTestUpload struct {
collection string
ttlSec int32
data []byte
gzipped bool
}
func etagOf(data []byte) string {
return base64.StdEncoding.EncodeToString(util.Md5For(util.DigestMd5, data))
}
func testChunk(vid uint32, key uint64, cookie uint32, offset int64, size int, etag string) *filer_pb.FileChunk {
return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: vid, FileKey: key, Cookie: cookie}, Offset: offset, Size: uint64(size), ETag: etag}
}
func newRestoreTestCommand(t *testing.T, filer *restoreTestFiler, restoreDir string) (*commandFsVerify, *bytes.Buffer, *[]restoreTestUpload) {
t.Helper()
commandEnv, _, cleanup := newFsVerifyTestCommandEnv(t, filer, &fsVerifyTestVolumeServer{})
t.Cleanup(cleanup)
commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{})
output := &bytes.Buffer{}
c := newFsVerifyTestCommand(t, commandEnv, output)
source, err := openRestoreSource(restoreDir)
if err != nil {
t.Fatal(err)
}
t.Cleanup(source.Close)
c.restore = source
uploads := &[]restoreTestUpload{}
c.uploadRestored = func(target restoreTarget, data []byte, gzipped bool, _ string) (string, error) {
*uploads = append(*uploads, restoreTestUpload{collection: target.collection, ttlSec: target.ttlSec, data: append([]byte(nil), data...), gzipped: gzipped})
return needle.NewFileId(9, uint64(100+len(*uploads)), 0xabcd).String(), nil
}
return c, output, uploads
}
func TestFsVerifyRestoreEntry(t *testing.T) {
plain := []byte("hello restored world")
text := bytes.Repeat([]byte("compressible "), 100)
gzipped, err := util.GzipData(text)
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "pics_7"))
v.write(1, 0x11, plain, false)
v.write(2, 0x22, gzipped, true)
v.write(6, 0x66, []byte("other bytes"), false)
v.close()
mtime := time.Now().Add(-time.Hour).Unix()
attr := &filer_pb.FuseAttributes{Mtime: mtime, Md5: []byte("md5"), TtlSec: 86400}
restorable := testChunk(7, 1, 0x11, 0, len(plain), etagOf(plain))
healthy := testChunk(7, 3, 0x33, int64(len(plain)), 10, "")
compressed := testChunk(7, 2, 0x22, int64(len(plain))+10, len(text), etagOf(text))
compressed.IsCompressed = true
lost := testChunk(7, 5, 0x55, int64(len(plain)+10+len(text)), 10, "")
wrongContent := testChunk(7, 6, 0x66, int64(len(plain)+20+len(text)), 11, etagOf([]byte("expected bytes")))
chunks := []*filer_pb.FileChunk{restorable, healthy, compressed, lost, wrongContent}
missing := []*filer_pb.FileChunk{restorable, compressed, lost, wrongContent}
newEntry := func() *filer_pb.Entry {
return &filer_pb.Entry{Name: "file", Attributes: proto.Clone(attr).(*filer_pb.FuseAttributes), Chunks: chunks}
}
path := util.NewFullPath("/buckets/b", "file")
t.Run("restores what it can in one update", func(t *testing.T) {
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
if !restored || !isRestorable {
t.Fatalf("restored=%v restorable=%v, want both\n%s", restored, isRestorable, output)
}
if len(filer.updates) != 1 {
t.Fatalf("%d updates, want 1", len(filer.updates))
}
if len(*uploads) != 2 {
t.Fatalf("%d uploads, want 2", len(*uploads))
}
// the new needle is assigned with the entry's lifetime
if u := (*uploads)[0]; !bytes.Equal(u.data, plain) || u.gzipped || u.collection != "pics" || u.ttlSec != 86400 {
t.Errorf("plain upload = %+v", u)
}
// the stored gzip bytes go up as they are, marked gzipped
if u := (*uploads)[1]; !bytes.Equal(u.data, gzipped) || !u.gzipped {
t.Errorf("compressed upload gzipped=%v, same bytes=%v", u.gzipped, bytes.Equal(u.data, gzipped))
}
got := filer.updates[0].Entry.Chunks
for i, want := range []*filer_pb.FileChunk{
withFileId(restorable, needle.NewFileId(9, 101, 0xabcd).String()),
healthy,
withFileId(compressed, needle.NewFileId(9, 102, 0xabcd).String()),
lost,
wrongContent,
} {
want.FileId, got[i].FileId = "", ""
if !proto.Equal(got[i], want) {
t.Errorf("chunk %d = %v, want %v", i, got[i], want)
}
}
for _, line := range []string{
"restored /buckets/b/file chunk " + restorable.GetFileIdString() + " -> " + needle.NewFileId(9, 101, 0xabcd).String(),
"restored /buckets/b/file chunk " + compressed.GetFileIdString() + " -> " + needle.NewFileId(9, 102, 0xabcd).String(),
"not restorable /buckets/b/file chunk " + lost.GetFileIdString() + ": not in restore source",
"not restorable /buckets/b/file chunk " + wrongContent.GetFileIdString() + ": content does not match chunk etag",
} {
if !strings.Contains(output.String(), line) {
t.Errorf("output lacks %q:\n%s", line, output)
}
}
})
t.Run("entry changed since verification", func(t *testing.T) {
changed := newEntry()
changed.Attributes.Mtime++
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): changed}}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
if restored || !isRestorable || len(*uploads) != 0 || len(filer.updates) != 0 {
t.Fatalf("restored=%v restorable=%v uploads=%d updates=%d, want only restorable", restored, isRestorable, len(*uploads), len(filer.updates))
}
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: entry changed since verification") {
t.Errorf("output:\n%s", output)
}
})
t.Run("entry changes before the update", func(t *testing.T) {
filer := &restoreTestFiler{
stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}},
changeBeforeUpdate: true,
}
c, output, _ := newRestoreTestCommand(t, filer, dir)
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
if restored || !isRestorable || len(filer.updates) != 0 {
t.Fatalf("restored=%v restorable=%v updates=%d, want only restorable", restored, isRestorable, len(filer.updates))
}
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: entry changed since verification") {
t.Errorf("output:\n%s", output)
}
})
t.Run("restorable entry is never pruned", func(t *testing.T) {
changed := newEntry()
changed.Attributes.Mtime++
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): changed}}}
c, _, _ := newRestoreTestCommand(t, filer, dir)
prune := true
c.pruneEntries = &prune
var counts fsVerifyCounts
c.repairEntry(path, attr, chunks, missing, &counts)
if counts != (fsVerifyCounts{}) || len(filer.deleted) != 0 {
t.Fatalf("counts=%+v deleted=%v, want the entry kept", counts, filer.deleted)
}
// nothing restorable: pruned as before
changed.Attributes.Mtime--
c.repairEntry(path, attr, chunks, []*filer_pb.FileChunk{lost}, &counts)
if counts.pruned != 1 || len(filer.deleted) != 1 {
t.Fatalf("counts=%+v deleted=%v, want the entry pruned", counts, filer.deleted)
}
})
}
func TestFsVerifyRestoreKeepsEntryTheSourceMayHold(t *testing.T) {
data := []byte("encrypted bytes")
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, data, false)
v.write(2, 0x22, data, false)
v.close()
newTestRestoreVolume(t, filepath.Join(dir, "8")).close()
if err := os.Truncate(filepath.Join(dir, "7.dat"), 8+int64(needle.GetActualSize(types.Size(len(data)), needle.GetCurrentVersion()))+10); err != nil {
t.Fatal(err)
}
if err := os.Remove(filepath.Join(dir, "8.idx")); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, "8.idx"), 0755); err != nil {
t.Fatal(err)
}
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
encrypted := testChunk(7, 1, 0x11, 0, len(data), "")
encrypted.CipherKey = []byte("key")
truncated := testChunk(7, 2, 0x22, 0, len(data), "")
unreadable := testChunk(8, 3, 0x33, 0, 10, "")
path := util.NewFullPath("/buckets/b", "file")
for _, c := range []struct {
name string
chunk *filer_pb.FileChunk
kept bool
}{
{"encrypted chunk held by the source", encrypted, true},
{"unreadable index", unreadable, true},
{"needle cut off the .dat", truncated, false},
} {
t.Run(c.name, func(t *testing.T) {
chunks := []*filer_pb.FileChunk{c.chunk}
entry := &filer_pb.Entry{Name: "file", Attributes: proto.Clone(attr).(*filer_pb.FuseAttributes), Chunks: chunks}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): entry}}}
cmd, output, uploads := newRestoreTestCommand(t, filer, dir)
prune := true
cmd.pruneEntries = &prune
var counts fsVerifyCounts
cmd.repairEntry(path, attr, chunks, chunks, &counts)
if len(*uploads) != 0 || len(filer.updates) != 0 {
t.Fatalf("uploads=%d updates=%d, want none\n%s", len(*uploads), len(filer.updates), output)
}
if kept := len(filer.deleted) == 0; kept != c.kept {
t.Fatalf("kept=%v, want %v\n%s", kept, c.kept, output)
}
})
}
}
// A missing chunk held in a manifest is restored by uploading a rewritten
// manifest that points at the new needle and keeps every other chunk.
func TestFsVerifyRestoreChunkInsideManifest(t *testing.T) {
data := []byte("chunk held by a manifest")
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, data, false)
v.close()
held := []*filer_pb.FileChunk{
testChunk(7, 1, 0x11, 0, len(data), etagOf(data)),
testChunk(7, 2, 0x22, int64(len(data)), 100, ""),
}
manifest := testChunk(8, 1, 0x88, 0, len(data)+100, "manifest-etag")
manifest.IsChunkManifest = true
path := util.NewFullPath("/dir", "file")
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix(), TtlSec: 3600}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{manifest}}},
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{manifest: held})},
}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{manifest}, held[:1])
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
}
if (*uploads)[1].ttlSec != 3600 {
t.Errorf("manifest assigned with ttl %d, want the entry's 3600", (*uploads)[1].ttlSec)
}
m := &filer_pb.FileChunkManifest{}
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
t.Fatal(err)
}
if len(m.Chunks) != 2 || m.Chunks[0].Fid.VolumeId != 9 || m.Chunks[0].Fid.FileKey != 101 || !proto.Equal(m.Chunks[1], held[1]) {
t.Fatalf("rewritten manifest holds %v", m.Chunks)
}
if m.Chunks[0].Offset != 0 || m.Chunks[0].Size != uint64(len(data)) || m.Chunks[0].ETag != held[0].ETag {
t.Errorf("restored chunk lost its fields: %v", m.Chunks[0])
}
got := filer.updates[0].Entry.Chunks[0]
if !got.IsChunkManifest || got.Fid.FileKey != 102 || got.Size != manifest.Size || got.ETag != manifest.ETag {
t.Errorf("entry manifest chunk = %v", got)
}
if !strings.Contains(output.String(), "restored /dir/file chunk "+held[0].GetFileIdString()+" -> "+needle.NewFileId(9, 101, 0xabcd).String()) {
t.Errorf("output:\n%s", output)
}
}
func TestCheckRestoredContent(t *testing.T) {
data := []byte("0123456789")
n := &needle.Needle{Data: data}
for _, c := range []struct {
name string
chunk *filer_pb.FileChunk
ok bool
}{
{"exact", testChunk(7, 1, 1, 0, 10, etagOf(data)), true},
{"truncated chunk", testChunk(7, 1, 1, 0, 4, etagOf(data)), true},
{"needle too short", testChunk(7, 1, 1, 0, 11, etagOf(data)), false},
{"md5 mismatch", testChunk(7, 1, 1, 0, 10, etagOf([]byte("other"))), false},
{"hex md5", testChunk(7, 1, 1, 0, 10, hex.EncodeToString(util.Md5For(util.DigestMd5, data))), true},
{"hex md5 mismatch", testChunk(7, 1, 1, 0, 10, hex.EncodeToString(util.Md5For(util.DigestMd5, []byte("x")))), false},
{"truncated sha256", testChunk(7, 1, 1, 0, 10, base64.StdEncoding.EncodeToString(util.Md5For(util.DigestSha256, data))), true},
{"crc etag", testChunk(7, 1, 1, 0, 10, "1a2b3c4d"), true},
{"no etag", testChunk(7, 1, 1, 0, 10, ""), true},
{"sse chunk keeps ciphertext", &filer_pb.FileChunk{Size: 10, ETag: etagOf([]byte("plain")), SseType: filer_pb.SSEType_SSE_S3}, true},
} {
if err := checkRestoredContent(c.chunk, n); (err == nil) != c.ok {
t.Errorf("%s: err=%v, want ok=%v", c.name, err, c.ok)
}
}
// a length-delimited field longer than the blob
if err := checkRestoredContent(&filer_pb.FileChunk{IsChunkManifest: true}, &needle.Needle{Data: []byte{0x0a, 0xff}}); err == nil {
t.Error("a manifest that does not parse must fail")
}
m, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: []*filer_pb.FileChunk{testChunk(7, 2, 2, 0, 1<<20, "")}})
if err != nil {
t.Fatal(err)
}
if err := checkRestoredContent(&filer_pb.FileChunk{Size: 1 << 20, IsChunkManifest: true}, &needle.Needle{Data: m}); err != nil {
t.Errorf("manifest: %v", err)
}
gzipped, err := util.GzipData(bytes.Repeat(data, 10))
if err != nil {
t.Fatal(err)
}
compressed := &needle.Needle{Data: gzipped}
compressed.SetIsCompressed()
if err := checkRestoredContent(testChunk(7, 1, 1, 0, 100, etagOf(bytes.Repeat(data, 10))), compressed); err != nil {
t.Errorf("compressed needle: %v", err)
}
}
// A lost manifest held by a readable one is restored, and the parent is
// rewritten to point at it.
func TestFsVerifyRestoreNestedManifest(t *testing.T) {
inner := []*filer_pb.FileChunk{testChunk(7, 5, 0x55, 100, 100, "")}
blob, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: inner})
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(2, 0x22, blob, false)
v.close()
nested := testChunk(7, 2, 0x22, 100, 100, "")
nested.IsChunkManifest = true
held := []*filer_pb.FileChunk{testChunk(7, 1, 0x11, 0, 100, ""), nested}
parent := testChunk(8, 1, 0x88, 0, 200, "")
parent.IsChunkManifest = true
path := util.NewFullPath("/dir", "file")
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{parent}}},
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{parent: held})},
}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{parent}, []*filer_pb.FileChunk{nested})
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
}
if !bytes.Equal((*uploads)[0].data, blob) {
t.Error("the nested manifest was not uploaded as stored")
}
m := &filer_pb.FileChunkManifest{}
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
t.Fatal(err)
}
if len(m.Chunks) != 2 || !proto.Equal(m.Chunks[0], held[0]) || m.Chunks[1].Fid.FileKey != 101 || !m.Chunks[1].IsChunkManifest {
t.Fatalf("rewritten parent holds %v", m.Chunks)
}
if got := filer.updates[0].Entry.Chunks[0]; got.Fid.FileKey != 102 || !got.IsChunkManifest {
t.Errorf("entry chunk = %v", got)
}
if !strings.Contains(output.String(), "restored /dir/file manifest "+nested.GetFileIdString()) {
t.Errorf("output:\n%s", output)
}
}