mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Merge pull request #868 from seaweedfs/fix/verify-bindings-stat
fix: verify chunk bindings without reading their bodies
This commit is contained in:
commit
fd86f2301f
13 files changed
+757
-13
No files matched your search
@@ -37,7 +37,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.StringVar(&snapshot, "snapshot", "", "unsupported: every snapshot HEAD names is always checked")
|
||||
fs.BoolVar(&allSnapshots, "all-snapshots", false, "unsupported: every snapshot HEAD names is always checked")
|
||||
fs.StringVar(&depth, "depth", "bindings", "meta or bindings: every named object exists; data: and every chunk's bytes hash to its name")
|
||||
fs.StringVar(&depth, "depth", "bindings", "meta or bindings: named filer entries, sizes and needle HEAD; data: and every chunk's bytes hash to its name")
|
||||
fs.BoolVar(&orphans, "orphans", false, "also report the volume's own names no reachable root names (report only)")
|
||||
fs.IntVar(&concurrency, "concurrency", 1, "unsupported: chunks are read one at a time")
|
||||
fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "unsupported: chunk reads are not paced")
|
||||
|
||||
@@ -43,7 +43,7 @@ func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, string) {
|
||||
oldResolve := resolveVolumeID
|
||||
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return id, nil }
|
||||
t.Cleanup(func() { resolveVolumeID = oldResolve })
|
||||
vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}.Encode()
|
||||
vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4096}, Format: layout.VolumeFormat}.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -264,6 +264,16 @@ type fakeBlobs struct {
|
||||
|
||||
func newFakeBlobs() *fakeBlobs { return &fakeBlobs{data: map[string][]byte{}} }
|
||||
|
||||
func (b *fakeBlobs) HeadBlob(_ context.Context, fid string) (uint64, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
d, ok := b.data[fid]
|
||||
if !ok {
|
||||
return 0, ErrBlobNotFound
|
||||
}
|
||||
return uint64(len(d)), nil
|
||||
}
|
||||
|
||||
func (b *fakeBlobs) Put(_ context.Context, d []byte) (string, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
|
||||
@@ -40,6 +40,9 @@ type VerifyOptions struct {
|
||||
Depth string // DepthNames (default) or DepthFull
|
||||
Orphans bool // also report unreachable own names (needs List)
|
||||
List List
|
||||
// Stat checks a chunk's presence and size without reading its body.
|
||||
// In-memory callers may omit it and supply those bytes through Fetch.
|
||||
Stat func(ctx context.Context, p string, expectedSize uint64) (found bool, err error)
|
||||
}
|
||||
|
||||
// Finding is one problem found at Path (relative to <base>).
|
||||
@@ -66,7 +69,9 @@ type verifier struct {
|
||||
res VerifyResult
|
||||
ownPool map[string]bool // reachable own names, by path relative to the volume
|
||||
ownMeta map[string]bool
|
||||
owners map[string]ownerID // VOLUME id per chunk owner, read once
|
||||
owners map[string]ownerID // VOLUME id per chunk owner, read once
|
||||
checked map[verifyChunkKey]bool // exact immutable chunk identities across all roots
|
||||
geometry map[string]Geometry
|
||||
ownID VolumeID
|
||||
}
|
||||
|
||||
@@ -75,6 +80,12 @@ type ownerID struct {
|
||||
ok bool
|
||||
}
|
||||
|
||||
type verifyChunkKey struct {
|
||||
owner VolumeID
|
||||
index uint64
|
||||
hash Hash
|
||||
}
|
||||
|
||||
// Verify checks the canonical store directory vol under base; callers resolve
|
||||
// logical names through the master before choosing VolumeDir(name, id).
|
||||
func Verify(ctx context.Context, base, vol string, fetch Fetch, opts VerifyOptions) (VerifyResult, error) {
|
||||
@@ -93,7 +104,7 @@ func Verify(ctx context.Context, base, vol string, fetch Fetch, opts VerifyOptio
|
||||
if opts.Orphans && opts.List == nil {
|
||||
return VerifyResult{}, errors.New("layout: verify orphans needs a list")
|
||||
}
|
||||
v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}}
|
||||
v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}, checked: map[verifyChunkKey]bool{}, geometry: map[string]Geometry{}}
|
||||
v.res.Complete = true
|
||||
head, ok, err := v.head(ctx, vol)
|
||||
if err != nil {
|
||||
@@ -196,6 +207,7 @@ func (v *verifier) volumeID(ctx context.Context, vol string, report bool) (Volum
|
||||
v.incomplete("VOLUME identity mismatch")
|
||||
return VolumeID{}, false, nil
|
||||
}
|
||||
v.geometry[vol] = rec.Geometry
|
||||
return rec.ID, true, nil
|
||||
}
|
||||
|
||||
@@ -321,6 +333,11 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo
|
||||
v.find(FindIdentity, p, fmt.Sprintf("names owner %s id %s; its VOLUME has %s", ref.Owner, ref.OwnerID, map[bool]string{true: o.id.String(), false: "none"}[o.ok]))
|
||||
continue
|
||||
}
|
||||
key := verifyChunkKey{owner: ref.OwnerID, index: ref.Chunk.Index, hash: ref.Chunk.Hash}
|
||||
if v.checked[key] {
|
||||
continue
|
||||
}
|
||||
v.checked[key] = true
|
||||
if v.opts.Depth == DepthFull {
|
||||
if _, err := r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash); err != nil {
|
||||
if err := v.classify(p, err); err != nil {
|
||||
@@ -329,8 +346,27 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo
|
||||
}
|
||||
continue
|
||||
}
|
||||
_, ok, err := v.fetch(ctx, path.Join(v.base, p))
|
||||
var expectedSize uint64
|
||||
if v.opts.Stat != nil {
|
||||
g := v.geometry[dir]
|
||||
if ref.Chunk.Index > (g.SizeBytes-1)/g.ChunkBytes {
|
||||
v.find(FindCorrupt, p, "chunk index is outside its owner's VOLUME geometry")
|
||||
continue
|
||||
}
|
||||
expectedSize = min(g.ChunkBytes, g.SizeBytes-ref.Chunk.Index*g.ChunkBytes)
|
||||
}
|
||||
var ok bool
|
||||
var err error
|
||||
if v.opts.Stat != nil {
|
||||
ok, err = v.opts.Stat(ctx, path.Join(v.base, p), expectedSize)
|
||||
} else {
|
||||
_, ok, err = v.fetch(ctx, path.Join(v.base, p))
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrCorrupt) {
|
||||
v.find(FindCorrupt, p, err.Error())
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("layout: read %s: %w", p, err)
|
||||
}
|
||||
if !ok {
|
||||
|
||||
@@ -89,6 +89,9 @@ func TestVolumeWriterRepositorySites(t *testing.T) {
|
||||
// One exclusive create plus one read-only collision classification;
|
||||
// TestDirectoryCollisionIsOnlyAnExclusiveCreateRefusal pins the latter.
|
||||
"core/frontend/chunkstore/layout_create.go CreateVolumeRecord VolumeName": 2,
|
||||
// Read-only cache discriminator; the distinct-object verifier control
|
||||
// proves VOLUME is observed once while HEAD is confirmed separately.
|
||||
"core/frontend/chunkstore/layout_verify.go VerifyLayout VolumeName": 1,
|
||||
}
|
||||
got := map[string]int{}
|
||||
root := filepath.Clean("../../../..")
|
||||
|
||||
@@ -51,13 +51,30 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve
|
||||
}
|
||||
s := &LayoutStore{f: f, b: b, root: path.Join(base, vol)}
|
||||
opts.List = s.List
|
||||
opts.Stat = s.verifyStat
|
||||
// Keep the generation from the same lookup as the HEAD bytes walked by
|
||||
// Verify. A later lookup must confirm every observed HEAD, including live
|
||||
// dependent targets, before publishing absence/reachability findings.
|
||||
heads := map[string]layout.Head{}
|
||||
// Immutable metadata may be shared by several roots. Keep it for this
|
||||
// pass, but never retain chunk bodies or cache mutable HEAD observations.
|
||||
type metadataObject struct {
|
||||
data []byte
|
||||
found bool
|
||||
}
|
||||
metadata := map[string]metadataObject{}
|
||||
fetch := func(ctx context.Context, p string) ([]byte, bool, error) {
|
||||
if path.Base(p) != layout.HeadName {
|
||||
return s.Fetch(ctx, p)
|
||||
parts := strings.Split(strings.TrimPrefix(p, base+"/"), "/")
|
||||
cacheable := len(parts) == 2 && parts[1] == layout.VolumeName || len(parts) == 3 && (parts[1] == layout.RootDir || parts[1] == layout.SegDir)
|
||||
if cached, ok := metadata[p]; ok && cacheable {
|
||||
return cached.data, cached.found, nil
|
||||
}
|
||||
data, found, err := s.Fetch(ctx, p)
|
||||
if cacheable && err == nil {
|
||||
metadata[p] = metadataObject{data, found}
|
||||
}
|
||||
return data, found, err
|
||||
}
|
||||
b, head, found, err := s.verifyHead(ctx, p)
|
||||
heads[p] = head
|
||||
@@ -103,6 +120,51 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// verifyStat checks the filer binding and the needle's existence and size by
|
||||
// HEAD. Reading and hashing the response body belongs to data depth.
|
||||
func (s *LayoutStore) verifyStat(ctx context.Context, p string, expectedSize uint64) (bool, error) {
|
||||
if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") {
|
||||
return false, errors.New("chunkstore: object path outside the store base")
|
||||
}
|
||||
e, err := s.f.LookupEntry(ctx, path.Dir(p), path.Base(p))
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if e == nil || e.IsDirectory {
|
||||
return false, fmt.Errorf("%w: %s is not a file", layout.ErrCorrupt, p)
|
||||
}
|
||||
if len(e.Chunks) == 0 {
|
||||
if uint64(len(e.Content)) != expectedSize {
|
||||
return false, fmt.Errorf("%w: inline size differs from VOLUME geometry for %s", layout.ErrCorrupt, p)
|
||||
}
|
||||
if e.Attributes != nil && e.Attributes.FileSize != uint64(len(e.Content)) {
|
||||
return false, fmt.Errorf("%w: inline size mismatch for %s", layout.ErrCorrupt, p)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0] == nil || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" || e.Attributes == nil || e.Attributes.FileSize != e.Chunks[0].Size || e.Attributes.FileSize != expectedSize {
|
||||
return false, fmt.Errorf("%w: invalid file binding or size for %s", layout.ErrCorrupt, p)
|
||||
}
|
||||
head, ok := s.b.(BlobHeaders)
|
||||
if !ok {
|
||||
return false, errors.New("chunkstore: verify needs needle HEAD support")
|
||||
}
|
||||
size, err := head.HeadBlob(ctx, e.Chunks[0].FileId)
|
||||
if errors.Is(err, ErrBlobNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if size != expectedSize {
|
||||
return false, fmt.Errorf("%w: needle size differs from VOLUME geometry for %s", layout.ErrCorrupt, p)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// verifyHead preserves inline bytes for the kernel's malformed/identity
|
||||
// diagnostics; an invalid envelope has no usable generation for confirmation.
|
||||
func (s *LayoutStore) verifyHead(ctx context.Context, p string) ([]byte, layout.Head, bool, error) {
|
||||
|
||||
@@ -48,7 +48,7 @@ func verifyFixtureVolume(t *testing.T) (filerBlobs, layout.VolumeID) {
|
||||
manifest := map[uint64]layout.Ref{}
|
||||
putDir(t, f, path.Join("/blocks", layout.VolumeDir("v", id), "pool/0"))
|
||||
for _, i := range []uint64{0, 5} {
|
||||
d := []byte(strings.Repeat(string(rune('a'+i)), 64))
|
||||
d := []byte(strings.Repeat(string(rune('a'+i)), 4*4096))
|
||||
c := layout.NameChunk(i, d)
|
||||
putFile(t, f, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), c.Path()), d)
|
||||
manifest[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: c}
|
||||
@@ -87,7 +87,7 @@ func TestVerifyLayoutThroughTheAdapter(t *testing.T) {
|
||||
}
|
||||
extra := layout.NameChunk(9, []byte("zz"))
|
||||
putFile(t, fb.fakeFiler, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), extra.Path()), []byte("zz"))
|
||||
c0 := layout.NameChunk(0, []byte(strings.Repeat("a", 64)))
|
||||
c0 := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))
|
||||
delete(fb.fakeFiler.entries, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), c0.Path()))
|
||||
before = snapshotStore(fb)
|
||||
r, err = VerifyLayout(ctx, fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Orphans: true})
|
||||
@@ -190,7 +190,7 @@ func TestVerifyLayoutRequiresStableHeadForMissingAndOrphans(t *testing.T) {
|
||||
fb, id := verifyFixtureVolume(t)
|
||||
hp := path.Join("/blocks", layout.VolumeDir("v", id), layout.HeadName)
|
||||
fb.fakeFiler.entries[hp].Extended = map[string][]byte{layoutKind: []byte("head"), layoutVolume: []byte(id.String()), layoutGen: []byte("1")}
|
||||
c := layout.NameChunk(0, []byte(strings.Repeat("a", 64)))
|
||||
c := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))
|
||||
delete(fb.fakeFiler.entries, path.Join("/blocks", layout.VolumeDir("v", id), c.Path()))
|
||||
extra := layout.NameChunk(9, []byte("orphan"))
|
||||
putFile(t, fb.fakeFiler, path.Join("/blocks", layout.VolumeDir("v", id), extra.Path()), []byte("orphan"))
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BlobHeaders checks needle existence and logical size without transferring its
|
||||
// body to the client. The volume server may read small needles internally.
|
||||
type BlobHeaders interface {
|
||||
HeadBlob(context.Context, string) (uint64, error)
|
||||
}
|
||||
|
||||
// HeadBlob resolves every replica with the same fresh-location absence rule as
|
||||
// Get. A reachable copy is sufficient; only all fresh 404s prove absence.
|
||||
func (c *SWFS) HeadBlob(ctx context.Context, fid string) (uint64, error) {
|
||||
vid, needle, ok := strings.Cut(fid, ",")
|
||||
if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") {
|
||||
return 0, fmt.Errorf("chunkstore: bad fid %q", fid)
|
||||
}
|
||||
urls, cached, err := c.lookupVolume(ctx, vid)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for attempt := 0; ; attempt++ {
|
||||
size, absent, readErr := c.headFromAll(ctx, urls, fid)
|
||||
if readErr == nil {
|
||||
return size, nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.vidCache, vid)
|
||||
c.mu.Unlock()
|
||||
if absent && cached && attempt == 0 {
|
||||
urls, _, err = c.lookupVolume(ctx, vid)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if absent {
|
||||
readErr = &blobNotFoundError{readErr}
|
||||
}
|
||||
return 0, fmt.Errorf("chunkstore: HEAD %s: %w", fid, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SWFS) headFromAll(ctx context.Context, urls []string, fid string) (uint64, bool, error) {
|
||||
absent := true
|
||||
var last error
|
||||
for _, host := range urls {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodHead, "http://"+host+"/"+fid, nil)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err == nil {
|
||||
closeErr := resp.Body.Close()
|
||||
switch {
|
||||
case closeErr != nil:
|
||||
err = closeErr
|
||||
case resp.StatusCode != http.StatusOK:
|
||||
err = &blobStatusError{code: resp.StatusCode, host: host}
|
||||
case resp.ContentLength < 0:
|
||||
err = errors.New("chunkstore: needle HEAD has no size")
|
||||
default:
|
||||
return uint64(resp.ContentLength), false, nil
|
||||
}
|
||||
}
|
||||
last = err
|
||||
var se *blobStatusError
|
||||
if !errors.As(err, &se) || se.code != http.StatusNotFound {
|
||||
absent = false
|
||||
}
|
||||
}
|
||||
if last == nil {
|
||||
last = errors.New("chunkstore: needle HEAD has no locations")
|
||||
absent = false
|
||||
}
|
||||
return 0, absent, last
|
||||
}
|
||||
|
||||
var _ BlobHeaders = (*SWFS)(nil)
|
||||
@@ -0,0 +1,80 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
func TestSWFSHeadBlobUsesOnlyHEADAndClassifiesAbsence(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, length string
|
||||
status int
|
||||
missing bool
|
||||
wantError bool
|
||||
}{
|
||||
{"exists", "4194304", 200, false, false},
|
||||
{"missing", "0", 404, true, true},
|
||||
{"unavailable", "0", 503, false, true},
|
||||
{"size-unavailable", "", 200, false, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
methods := make(chan string, 4)
|
||||
vol := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
methods <- r.Method
|
||||
if tc.length != "" {
|
||||
w.Header().Set("Content-Length", tc.length)
|
||||
}
|
||||
w.WriteHeader(tc.status)
|
||||
}))
|
||||
defer vol.Close()
|
||||
host := strings.TrimPrefix(vol.URL, "http://")
|
||||
f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: host}}}}}}
|
||||
c := startFakeFiler(t, f)
|
||||
size, err := c.HeadBlob(context.Background(), "7,01abcdef")
|
||||
if (err != nil) != tc.wantError || errors.Is(err, ErrBlobNotFound) != tc.missing || !tc.wantError && size != 4194304 {
|
||||
t.Fatalf("size=%d err=%v", size, err)
|
||||
}
|
||||
if method := <-methods; method != http.MethodHead {
|
||||
t.Fatalf("body request %s", method)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSWFSHeadBlobRefreshesCachedMissingLocation(t *testing.T) {
|
||||
stale := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }))
|
||||
defer stale.Close()
|
||||
live := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodHead {
|
||||
t.Errorf("body request %s", r.Method)
|
||||
}
|
||||
w.Header().Set("Content-Length", "4096")
|
||||
}))
|
||||
defer live.Close()
|
||||
f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: strings.TrimPrefix(live.URL, "http://")}}}}}}
|
||||
c := startFakeFiler(t, f)
|
||||
c.vidCache["7"] = []string{strings.TrimPrefix(stale.URL, "http://")}
|
||||
size, err := c.HeadBlob(context.Background(), "7,01abcdef")
|
||||
if err != nil || size != 4096 || f.volLookups != 1 {
|
||||
t.Fatalf("size=%d err=%v fresh lookups=%d", size, err, f.volLookups)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSWFSHeadBlobMixedReplicaFailureDoesNotProveAbsence(t *testing.T) {
|
||||
missing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }))
|
||||
defer missing.Close()
|
||||
failed := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503) }))
|
||||
defer failed.Close()
|
||||
f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: strings.TrimPrefix(failed.URL, "http://")}, {Url: strings.TrimPrefix(missing.URL, "http://")}}}}}}
|
||||
c := startFakeFiler(t, f)
|
||||
_, err := c.HeadBlob(context.Background(), "7,01abcdef")
|
||||
if err == nil || errors.Is(err, ErrBlobNotFound) {
|
||||
t.Fatalf("mixed operational/404 answer: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
func verifyBlobFixture(t *testing.T) (filerBlobs, layout.VolumeID) {
|
||||
t.Helper()
|
||||
fb, id := verifyFixtureVolume(t)
|
||||
for p, e := range fb.fakeFiler.entries {
|
||||
if !strings.Contains(p, "/pool/") || e.IsDirectory {
|
||||
continue
|
||||
}
|
||||
fid, err := fb.fakeBlobs.Put(context.Background(), e.Content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.Attributes = &filerpb.FuseAttributes{FileSize: uint64(len(e.Content))}
|
||||
e.Chunks = []*filerpb.FileChunk{{FileId: fid, Size: uint64(len(e.Content))}}
|
||||
e.Content = nil
|
||||
}
|
||||
return fb, id
|
||||
}
|
||||
|
||||
func TestVerifyBindingsNeverReadsChunkBodies(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
_, before, _ := fb.fakeBlobs.counts()
|
||||
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 0 || res.Chunks != 2 {
|
||||
t.Fatalf("bindings: %+v, %v", res, err)
|
||||
}
|
||||
_, after, _ := fb.fakeBlobs.counts()
|
||||
if after != before {
|
||||
t.Fatalf("bindings read %d chunk bodies; want zero", after-before)
|
||||
}
|
||||
// Data depth must continue to fetch the two bodies and verify their hashes.
|
||||
res, err = VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthFull})
|
||||
_, full, _ := fb.fakeBlobs.counts()
|
||||
if err != nil || !res.Complete || len(res.Findings) != 0 || full-after != 2 {
|
||||
t.Fatalf("data: %+v, %v, body reads=%d", res, err, full-after)
|
||||
}
|
||||
// Same-size damage is invisible to bindings, but must be caught by data depth.
|
||||
e := fb.fakeFiler.entries[path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path())]
|
||||
fb.fakeBlobs.data[e.Chunks[0].FileId] = []byte(strings.Repeat("z", 4*4096))
|
||||
res, err = VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthFull})
|
||||
if err != nil || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt {
|
||||
t.Fatalf("damaged data: %+v, %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyBindingsReportsMissingNeedleBehindPresentEntry(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
dir := layout.VolumeDir("v", id)
|
||||
n := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))
|
||||
e := fb.fakeFiler.entries[path.Join("/blocks", dir, n.Path())]
|
||||
delete(fb.fakeBlobs.data, e.Chunks[0].FileId)
|
||||
_, before, _ := fb.fakeBlobs.counts()
|
||||
res, err := VerifyLayout(context.Background(), fb, "/blocks", dir, layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
_, after, _ := fb.fakeBlobs.counts()
|
||||
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindMissing || after != before {
|
||||
t.Fatalf("missing needle without body reads: %+v, %v, gets=%d", res, err, after-before)
|
||||
}
|
||||
}
|
||||
|
||||
type verifyNeedleFailure struct {
|
||||
filerBlobs
|
||||
err error
|
||||
size uint64
|
||||
}
|
||||
|
||||
func (f verifyNeedleFailure) HeadBlob(context.Context, string) (uint64, error) {
|
||||
return f.size, f.err
|
||||
}
|
||||
|
||||
func TestVerifyBindingsNeedleFailureAndSize(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
injected := errors.New("needle service unavailable")
|
||||
res, err := VerifyLayout(context.Background(), verifyNeedleFailure{filerBlobs: fb, err: injected}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if !errors.Is(err, injected) || res.Complete || len(res.Findings) != 0 {
|
||||
t.Fatalf("unavailable needle: %+v, %v", res, err)
|
||||
}
|
||||
res, err = VerifyLayout(context.Background(), verifyNeedleFailure{filerBlobs: fb, size: 32}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 2 {
|
||||
t.Fatalf("wrong needle sizes: %+v, %v", res, err)
|
||||
}
|
||||
for _, f := range res.Findings {
|
||||
if f.Class != layout.FindCorrupt {
|
||||
t.Fatalf("wrong-size class: %+v", f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDistinctChunksRetainHashAcrossSnapshots(t *testing.T) {
|
||||
for _, depth := range []string{layout.DepthNames, layout.DepthFull} {
|
||||
t.Run(depth, func(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
dir := path.Join("/blocks", layout.VolumeDir("v", id))
|
||||
missing := layout.NameChunk(0, []byte(strings.Repeat("z", 4*4096)))
|
||||
root, segs, err := layout.Build(map[uint64]layout.Ref{0: {Owner: "v", OwnerID: id, Chunk: missing}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for n, b := range segs {
|
||||
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b)
|
||||
}
|
||||
rn, raw, err := layout.NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw)
|
||||
e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)]
|
||||
h, err := layout.DecodeHead(e.Content, 0, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Snapshots = map[string]layout.Snapshot{"older": {Root: rn}}
|
||||
e.Content, err = h.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: depth})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindMissing || res.Findings[0].Path != path.Join(layout.VolumeDir("v", id), missing.Path()) {
|
||||
t.Fatalf("different content at the same owner/index: %+v, %v", res, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type verifyLookupCounter struct {
|
||||
filerBlobs
|
||||
reads map[string]int
|
||||
}
|
||||
|
||||
func (f *verifyLookupCounter) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
f.reads[path.Join(dir, name)]++
|
||||
return f.filerBlobs.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
func TestVerifyBindingsChecksEachDistinctObjectOnce(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
dir := path.Join("/blocks", layout.VolumeDir("v", id))
|
||||
refs := map[uint64]layout.Ref{}
|
||||
for _, i := range []uint64{0, 5} {
|
||||
refs[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: layout.NameChunk(i, []byte(strings.Repeat(string(rune('a'+i)), 4*4096)))}
|
||||
}
|
||||
// This snapshot deliberately reaches the next shard; its volume covers it.
|
||||
vp := path.Join(dir, layout.VolumeName)
|
||||
volume, err := layout.DecodeVolume(fb.fakeFiler.entries[vp].Content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
volume.SizeBytes = uint64(layout.ShardSize+2) * volume.ChunkBytes
|
||||
fb.fakeFiler.entries[vp].Content, err = volume.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
index := uint64(layout.ShardSize + 1)
|
||||
n := layout.NameChunk(index, []byte(strings.Repeat("s", 4*4096)))
|
||||
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), []byte(strings.Repeat("s", 4*4096)))
|
||||
refs[index] = layout.Ref{Owner: "v", OwnerID: id, Chunk: n}
|
||||
root, segs, err := layout.Build(refs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for n, b := range segs {
|
||||
if fb.fakeFiler.entries[path.Join(dir, n.Path())] == nil {
|
||||
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b)
|
||||
}
|
||||
}
|
||||
rn, raw, err := layout.NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw)
|
||||
e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)]
|
||||
h, err := layout.DecodeHead(e.Content, 0, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Snapshots = map[string]layout.Snapshot{"s": {Root: rn}}
|
||||
e.Content, err = h.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &verifyLookupCounter{filerBlobs: fb, reads: map[string]int{}}
|
||||
res, err := VerifyLayout(context.Background(), f, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 0 || res.Roots != 2 {
|
||||
t.Fatalf("shared snapshot objects: %+v, %v", res, err)
|
||||
}
|
||||
for p, count := range f.reads {
|
||||
want := 1
|
||||
if path.Base(p) == layout.HeadName {
|
||||
want = 2
|
||||
}
|
||||
if count != want {
|
||||
t.Errorf("%s: %d lookups; want %d", p, count, want)
|
||||
}
|
||||
}
|
||||
for _, ref := range refs {
|
||||
p := path.Join(dir, ref.Chunk.Path())
|
||||
if f.reads[p] != 1 {
|
||||
t.Errorf("reachable chunk %s: %d lookups", p, f.reads[p])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyBindingsChecksDeclaredSizesAndRefusals(t *testing.T) {
|
||||
for _, mode := range []string{"size", "no-attributes", "offset", "empty-fid", "nil-chunk", "multiple-chunks", "directory", "mixed-content", "inline-size", "missing"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path())
|
||||
e := fb.fakeFiler.entries[p]
|
||||
switch mode {
|
||||
case "size":
|
||||
e.Attributes.FileSize++
|
||||
case "no-attributes":
|
||||
e.Attributes = nil
|
||||
case "offset":
|
||||
e.Chunks[0].Offset = 1
|
||||
case "empty-fid":
|
||||
e.Chunks[0].FileId = ""
|
||||
case "nil-chunk":
|
||||
e.Chunks[0] = nil
|
||||
case "multiple-chunks":
|
||||
e.Chunks = append(e.Chunks, e.Chunks[0])
|
||||
case "directory":
|
||||
e.IsDirectory = true
|
||||
case "mixed-content":
|
||||
e.Content = []byte("mixed")
|
||||
case "inline-size":
|
||||
e.Chunks = nil
|
||||
e.Content = []byte("short")
|
||||
case "missing":
|
||||
delete(fb.fakeFiler.entries, p)
|
||||
}
|
||||
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
want := layout.FindCorrupt
|
||||
if mode == "missing" {
|
||||
want = layout.FindMissing
|
||||
}
|
||||
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != want || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") {
|
||||
t.Fatalf("%s: %+v, %v; want %s at %s", mode, res, err, want, p)
|
||||
}
|
||||
_, gets, _ := fb.fakeBlobs.counts()
|
||||
if gets != 0 {
|
||||
t.Fatalf("bindings read %d bodies", gets)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type verifyLookupFailure struct {
|
||||
filerBlobs
|
||||
err error
|
||||
}
|
||||
|
||||
func (f verifyLookupFailure) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if strings.Contains(dir, "/pool/") {
|
||||
return nil, f.err
|
||||
}
|
||||
return f.filerBlobs.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
func TestVerifyBindingsLookupFailureIsNotAMissingObject(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
injected := errors.New("injected filer unavailable")
|
||||
res, err := VerifyLayout(context.Background(), verifyLookupFailure{fb, injected}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if !errors.Is(err, injected) || res.Complete || len(res.Findings) != 0 {
|
||||
t.Fatalf("lookup failure: %+v, %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
type verifyPayloadCounter struct {
|
||||
Filer
|
||||
Blobs
|
||||
payloads map[string]bool
|
||||
payloadReads, metadataReads int
|
||||
}
|
||||
|
||||
func (f *verifyPayloadCounter) HeadBlob(ctx context.Context, fid string) (uint64, error) {
|
||||
return f.Blobs.(BlobHeaders).HeadBlob(ctx, fid)
|
||||
}
|
||||
|
||||
func (f *verifyPayloadCounter) Get(ctx context.Context, fid string) ([]byte, error) {
|
||||
if f.payloads[fid] {
|
||||
f.payloadReads++
|
||||
} else {
|
||||
f.metadataReads++
|
||||
}
|
||||
return f.Blobs.Get(ctx, fid)
|
||||
}
|
||||
func TestVerifyBindingsProductionMetadataStillDecodes(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, source := verifyProductionFixture(t)
|
||||
target := newRef(t, "restored")
|
||||
if _, err := c.Restore(ctx, source, "s", target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := c.f.ListEntries(ctx, path.Join(c.base, source.Dir(), layout.PoolDir, "0"), "", "", 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &verifyPayloadCounter{Filer: c.f, Blobs: c.b, payloads: map[string]bool{}}
|
||||
for _, e := range entries {
|
||||
for _, chunk := range e.Chunks {
|
||||
f.payloads[chunk.FileId] = true
|
||||
}
|
||||
}
|
||||
if len(f.payloads) == 0 {
|
||||
t.Fatal("production fixture has no blob-backed chunks")
|
||||
}
|
||||
for _, v := range []VolumeRef{source, target} {
|
||||
res, err := VerifyLayout(ctx, f, c.base, v.Dir(), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 0 || res.Chunks != 1 {
|
||||
t.Fatalf("%s bindings: %+v, %v", v.Name, res, err)
|
||||
}
|
||||
}
|
||||
if f.payloadReads != 0 || f.metadataReads == 0 {
|
||||
t.Fatalf("body reads: payload=%d metadata=%d; only manifests need body decoding", f.payloadReads, f.metadataReads)
|
||||
}
|
||||
res, err := VerifyLayout(ctx, f, c.base, target.Dir(), layout.VerifyOptions{Depth: layout.DepthFull})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 0 || f.payloadReads != 1 {
|
||||
t.Fatalf("restore data: %+v, %v, payload reads=%d", res, err, f.payloadReads)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path())
|
||||
e := fb.fakeFiler.entries[p]
|
||||
e.Attributes.FileSize = 32
|
||||
e.Chunks[0].Size = 32
|
||||
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") {
|
||||
t.Fatalf("self-consistent truncation: %+v, %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume(t *testing.T) {
|
||||
for _, mode := range []string{"tail", "short-tail", "outside"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
dir := path.Join("/blocks", layout.VolumeDir("v", id))
|
||||
vp := path.Join(dir, layout.VolumeName)
|
||||
volume, err := layout.DecodeVolume(fb.fakeFiler.entries[vp].Content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
volume.SizeBytes = 5*volume.ChunkBytes + 4096
|
||||
if mode == "outside" {
|
||||
volume.SizeBytes = 5 * volume.ChunkBytes
|
||||
}
|
||||
fb.fakeFiler.entries[vp].Content, err = volume.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := path.Join(dir, layout.NameChunk(5, []byte(strings.Repeat("f", 4*4096))).Path())
|
||||
// A valid tail has both a shortened needle and matching metadata.
|
||||
e := fb.fakeFiler.entries[p]
|
||||
fb.fakeBlobs.data[e.Chunks[0].FileId] = fb.fakeBlobs.data[e.Chunks[0].FileId][:4096]
|
||||
e.Attributes.FileSize, e.Chunks[0].Size = 4096, 4096
|
||||
if mode == "short-tail" {
|
||||
e.Attributes.FileSize, e.Chunks[0].Size = 2048, 2048
|
||||
}
|
||||
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
|
||||
if err != nil || !res.Complete {
|
||||
t.Fatalf("%s: %+v, %v", mode, res, err)
|
||||
}
|
||||
if mode == "tail" {
|
||||
if len(res.Findings) != 0 {
|
||||
t.Fatalf("valid tail: %+v", res.Findings)
|
||||
}
|
||||
} else if len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") {
|
||||
t.Fatalf("%s: %+v", mode, res.Findings)
|
||||
}
|
||||
_, gets, _ := fb.fakeBlobs.counts()
|
||||
if gets != 0 {
|
||||
t.Fatalf("bindings read %d bodies", gets)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyDeduplicationNeverSkipsFullOwnerIdentity(t *testing.T) {
|
||||
for _, depth := range []string{layout.DepthNames, layout.DepthFull} {
|
||||
t.Run(depth, func(t *testing.T) {
|
||||
fb, id := verifyBlobFixture(t)
|
||||
wrong := id
|
||||
wrong[15] ^= 1
|
||||
if layout.VolumeDir("v", wrong) != layout.VolumeDir("v", id) {
|
||||
t.Fatal("fixture needs an id8 collision")
|
||||
}
|
||||
ref := layout.Ref{Owner: "v", OwnerID: wrong, Chunk: layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))}
|
||||
root, segs, err := layout.Build(map[uint64]layout.Ref{0: ref})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := path.Join("/blocks", layout.VolumeDir("v", id))
|
||||
for n, b := range segs {
|
||||
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b)
|
||||
}
|
||||
rn, raw, err := layout.NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw)
|
||||
e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)]
|
||||
h, err := layout.DecodeHead(e.Content, 0, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Snapshots = map[string]layout.Snapshot{"different-owner": {Root: rn}}
|
||||
e.Content, err = h.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: depth})
|
||||
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindIdentity {
|
||||
t.Fatalf("id8 collision after a valid reference: %+v, %v", res, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -15,11 +16,15 @@ type verifyProductionStore struct {
|
||||
Blobs
|
||||
}
|
||||
|
||||
func (f verifyProductionStore) HeadBlob(ctx context.Context, fid string) (uint64, error) {
|
||||
return f.Blobs.(BlobHeaders).HeadBlob(ctx, fid)
|
||||
}
|
||||
|
||||
// Use the production creators, not a hand-written name-only directory: a
|
||||
// restored image borrows the source's chunks while owning copied metadata.
|
||||
func TestVerifyProductionLayoutCurrentAndRestored(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, source, _, _ := cleanFixture(t)
|
||||
c, source := verifyProductionFixture(t)
|
||||
target := newRef(t, "restored")
|
||||
if _, err := c.Restore(ctx, source, "s", target); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -58,7 +63,7 @@ func (f *verifyMovingDependent) LookupEntry(ctx context.Context, dir, name strin
|
||||
}
|
||||
func TestVerifyConfirmsDependentHeadBeforeReportingOrphans(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, source, _, _ := cleanFixture(t)
|
||||
c, source := verifyProductionFixture(t)
|
||||
target := newRef(t, "restored")
|
||||
if _, err := c.Restore(ctx, source, "s", target); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -80,3 +85,21 @@ func TestVerifyConfirmsDependentHeadBeforeReportingOrphans(t *testing.T) {
|
||||
t.Fatalf("moving dependent: %+v %v reads=%d", r, err, f.reads)
|
||||
}
|
||||
}
|
||||
|
||||
// Unlike catalog-only fixtures, a verifier fixture stores full geometry-sized chunks.
|
||||
func verifyProductionFixture(t *testing.T) (*BCatalog, VolumeRef) {
|
||||
t.Helper()
|
||||
c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := newRef(t, "source")
|
||||
if _, err := c.CreateVolume(context.Background(), source, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commitSnapshot(t, c, source, bytes.Repeat([]byte{7}, 4*4096), "s")
|
||||
if err := c.f.CreateEntry(context.Background(), path.Join(c.base, source.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c, source
|
||||
}
|
||||
@@ -1063,13 +1063,16 @@ Notes:
|
||||
| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after the commit naming it is confirmed (every object its root reaches written by the session first); an unknown outcome reports failure, settled by reading HEAD. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead`; `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `TestLayoutRemote_CutCommitsThroughTheKernel` (`core/frontend/chunkstore/layout_remote_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE |
|
||||
| `INV-SNAP-SCHEDULE-RESTART-001` | A new snapshot worker seeds its last success from HEAD's newest scheduled creation time (future clamped to now), then the next stable per-volume grid slot; absent history is due now. Restarts preserve overdue age; manual snapshots do not seed it. | M8 scheduled worker Armed → Due | `core/frontend/durable/chunk_snapshot_schedule.go` `snapshotScheduleFromHead`; `provider_chunk.go` `newChunkLayer` | `TestScheduledSnapshotRestartsStillTakeTheDueSnapshot`, `TestScheduledSnapshotRestartPreservesOverdueFromHEAD`, `TestScheduledSnapshotWithoutHistoryIsImmediatelyDue`, `TestScheduledSnapshotProvidersSpreadAfterImmediateFirstAttempt`, `TestSnapshotScheduleHeadSeedKeepsPerVolumeGrid`, `TestSnapshotScheduleHeadSeedClampsFutureCreationTime` | — (read-only timer initialization from existing HEAD metadata) | ACTIVE |
|
||||
| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retain/retain.go` `Plan`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retain/retain_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch, Stat and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-BINDINGS-001` | Bindings checks each chunk's filer binding, declared size and needle HEAD size against its owner's VOLUME geometry (tail excepted), without transferring the blob body. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `verifyStat`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsNeverReadsChunkBodies`, `TestVerifyBindingsChecksDeclaredSizesAndRefusals`, `TestVerifyBindingsLookupFailureIsNotAMissingObject`, `TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry`, `TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume` | — (read-only inspection) | ACTIVE |
|
||||
| `INV-VERIFY-NEEDLE-001` | Bindings reports a missing needle only after every freshly resolved location answers 404; operational failures remain incomplete. A needle HEAD never falls back to a client GET. | M6 reader (no transition) | `core/frontend/chunkstore/swfs_head.go` `HeadBlob`; `core/frontend/chunkstore/layout_verify.go` `verifyStat` | `TestVerifyBindingsReportsMissingNeedleBehindPresentEntry`, `TestSWFSHeadBlobUsesOnlyHEADAndClassifiesAbsence`, `TestSWFSHeadBlobRefreshesCachedMissingLocation` | — (read-only inspection) | ACTIVE |
|
||||
| `INV-VERIFY-DISTINCT-001` | A verify pass looks up each immutable metadata object and chunk binding once across roots; HEAD remains independently confirmed, and chunk bodies are never retained in the metadata cache. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsChecksEachDistinctObjectOnce` | — (pass-local reuse) | ACTIVE |
|
||||
| `INV-VERIFY-STABLE-HEAD-001` | Filer verify publishes MISSING or ORPHAN only after two HEAD observations agree on a nonzero generation and volume identity. An unavailable or changed own/dependent HEAD makes the pass incomplete and suppresses those findings. Unsupported verify options refuse before dialing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `cmd/sw-block/chunk_verify.go` `chunkVerify` | `TestVerifyLayoutRequiresStableHeadForMissingAndOrphans`; `TestVerifyConfirmsDependentHeadBeforeReportingOrphans`; `TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial` | — | ACTIVE |
|
||||
| `INV-VERIFY-NOTFOUND-001` | Verify reports `MISSING` only when the store answers that the object does not exist; any other read failure ends the pass as incomplete with that error, and is never a finding. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyReadErrorIsReturned`, `TestVerifyFindsMissingAndCorrupt` (`core/frontend/chunkstore/layout/verify_test.go`); `TestOpsChunk_VerifyReadErrorIsIncomplete` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-REACH-001` | A complete pass checks every object the current root and every snapshot root name (roots, segments, chunks): an absent one is `MISSING`; one whose bytes do not hash to its name, at depth full, is `CORRUPT`. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyCleanVolume`, `TestVerifyFindsMissingAndCorrupt`, `TestVerifyWalksSnapshotRoots` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-INCOMPLETE-001` | A volume whose VOLUME or HEAD is absent or does not decode is never reported clean: the pass is incomplete and says which object. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyHeadMissingOrMalformedIsIncomplete` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-ORPHAN-001` | With orphans on, only this volume's own full-id names that no root or live restore target names are ORPHAN. Owner/target paths use VolumeDir(name,id); an unreadable live target suppresses orphan findings. Verify deletes nothing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyOrphans`, `TestVerifyDependentReachIsNotOrphanAndUnreadableDependentSuppresses` (`core/frontend/chunkstore/layout/verify_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-IDENTITY-001` | Verify reads canonical VolumeDir(name,id) directories. VOLUME must match its directory, HEAD must match VOLUME, and a master-resolved id must match in full. A mismatched chunk-owner VOLUME is IDENTITY, never clean. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyVolumeRecordAndHeadID`, `TestVerifyChunkOwnerIdentity` (`core/frontend/chunkstore/layout/verify_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`); `TestOpsChunk_VerifyProductionLayoutNameAndDirectory`, `TestOpsChunk_VerifyBindsMasterFullIDDespiteDirectoryPrefixCollision` (`cmd/sw-block/chunk_verify_production_test.go`) | — | ACTIVE |
|
||||
| `INV-VERIFY-IDENTITY-001` | Verify reads canonical VolumeDir(name,id) directories. VOLUME must match its directory, HEAD must match VOLUME, and a master-resolved id must match in full. A mismatched chunk-owner VOLUME is IDENTITY, never clean. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyVolumeRecordAndHeadID`, `TestVerifyChunkOwnerIdentity` (`core/frontend/chunkstore/layout/verify_test.go`), `TestVerifyDeduplicationNeverSkipsFullOwnerIdentity` (`core/frontend/chunkstore/verify_bindings_stat_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`); `TestOpsChunk_VerifyProductionLayoutNameAndDirectory`, `TestOpsChunk_VerifyBindsMasterFullIDDespiteDirectoryPrefixCollision` (`cmd/sw-block/chunk_verify_production_test.go`) | — | ACTIVE |
|
||||
| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fetches a chunk only through that chunk's shared fill flight: at most one fetch per chunk absence, and a fetched block is never installed over a block written locally. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `nextHydrateTarget`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked`; `core/storage/chunk_layer.go` `fillOnce` | `TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage`, `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | DORMANT |
|
||||
| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | DORMANT |
|
||||
| `INV-RESTORE-READ-REF-001` | A restore target reads each chunk its HEAD names from the pool of the reference's owner, by the reference alone (no other copy, no name-built path); a chunk missing there is an error on a fresh host, never zeros. | M6 restore target read (no transition) | `core/frontend/chunkstore/layout/read.go` `Reader.ReadRef`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Get` | `TestLayoutRemote_RestoreTargetReadsItsSource` (`core/frontend/chunkstore/layout_restore_read_test.go`) | — | ACTIVE |
|
||||
|
||||
@@ -869,6 +869,19 @@ must also match VOLUME; the eight-character directory suffix is not an identity
|
||||
check. Source and restore-target chunks are checked in their owners' canonical
|
||||
directories using each reference's full owner id.
|
||||
|
||||
The default `--depth bindings` (also named `meta`) checks each distinct chunk's
|
||||
filer entry and its declared size against its owner's VOLUME geometry (including
|
||||
the final partial chunk), then checks the backing needle's existence and size
|
||||
using HTTP HEAD without downloading its body. A missing needle behind a present
|
||||
entry is MISSING. A successful replica is sufficient; when none succeeds,
|
||||
an operational failure makes the pass incomplete rather than proving absence. This does
|
||||
not detect same-size content damage; use `--depth data` for the hash check.
|
||||
SeaweedFS 4.53 reads only metadata for ordinary uncompressed 4 MiB needles on
|
||||
HEAD, but may read small needles internally. Roots and segments are still
|
||||
read and decoded, and shared immutable objects are checked once per pass.
|
||||
Inline filer entries are checked directly from the content returned by the
|
||||
lookup; they have no backing needle and require no needle HEAD.
|
||||
|
||||
Verify is read-only: exit 0 means complete with no findings, 3 means complete
|
||||
with findings, 1 means incomplete, and 2 means invalid arguments. `--depth data`
|
||||
checks chunk hashes and requires an explicit timeout. `--orphans` only reports;
|
||||
|
||||
Reference in new issue
Block a user