diff --git a/other/java/client/src/main/java/seaweedfs/client/FileChunkManifest.java b/other/java/client/src/main/java/seaweedfs/client/FileChunkManifest.java index dd4d407b07..58e91286a0 100644 --- a/other/java/client/src/main/java/seaweedfs/client/FileChunkManifest.java +++ b/other/java/client/src/main/java/seaweedfs/client/FileChunkManifest.java @@ -42,12 +42,26 @@ public class FileChunkManifest { // avoid deprecated chunk.getFileId() resolvedChunks.add(t.toBuilder().setFileId(FilerClient.toFileId(t.getFid())).build()); } - dataChunks.addAll(resolveChunkManifest(filerClient, resolvedChunks)); + dataChunks.addAll(resolveChunkManifest(filerClient, cutToManifestSpan(chunk, resolvedChunks))); } return dataChunks; } + // A truncate may have shortened a manifest and left the chunks it holds whole. + static List cutToManifestSpan(FilerProto.FileChunk manifest, List held) { + long end = manifest.getOffset() + manifest.getSize(); + List cut = new ArrayList<>(held.size()); + for (FilerProto.FileChunk chunk : held) { + if (chunk.getOffset() + chunk.getSize() <= end) { + cut.add(chunk); + } else if (chunk.getOffset() < end) { + cut.add(chunk.toBuilder().setSize(end - chunk.getOffset()).build()); + } + } + return cut; + } + private static byte[] fetchChunk(final FilerClient filerClient, FilerProto.FileChunk chunk) throws IOException { String vid = "" + chunk.getFid().getVolumeId(); diff --git a/other/java/client/src/test/java/seaweedfs/client/FileChunkManifestTest.java b/other/java/client/src/test/java/seaweedfs/client/FileChunkManifestTest.java new file mode 100644 index 0000000000..d7d5965427 --- /dev/null +++ b/other/java/client/src/test/java/seaweedfs/client/FileChunkManifestTest.java @@ -0,0 +1,43 @@ +package seaweedfs.client; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +public class FileChunkManifestTest { + + private static FilerProto.FileChunk chunk(int volumeId, long key, long offset, long size) { + return FilerProto.FileChunk.newBuilder() + .setFid(FilerProto.FileId.newBuilder().setVolumeId(volumeId).setFileKey(key).setCookie(1)) + .setOffset(offset) + .setSize(size) + .setModifiedTsNs(1) + .build(); + } + + @Test + public void testCutToManifestSpanCutsAShortenedManifest() throws IOException { + List held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100), chunk(9, 3, 200, 100)); + FilerProto.FileChunk manifest = chunk(9, 4, 0, 150).toBuilder().setIsChunkManifest(true).build(); + + List cut = FileChunkManifest.cutToManifestSpan(manifest, held); + Assert.assertEquals(2, cut.size()); + Assert.assertEquals(held.get(0), cut.get(0)); + Assert.assertEquals(100, cut.get(1).getOffset()); + Assert.assertEquals(50, cut.get(1).getSize()); + Assert.assertEquals(100, held.get(1).getSize()); + + List visibles = ReadChunks.readResolvedChunks(cut); + Assert.assertEquals(150, visibles.get(visibles.size() - 1).stop); + } + + @Test + public void testCutToManifestSpanLeavesAWholeManifestAlone() { + List held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100)); + FilerProto.FileChunk manifest = chunk(9, 4, 0, 200).toBuilder().setIsChunkManifest(true).build(); + Assert.assertEquals(held, FileChunkManifest.cutToManifestSpan(manifest, held)); + } +} diff --git a/seaweed-worker/crates/sw-client/src/read.rs b/seaweed-worker/crates/sw-client/src/read.rs index 94b15c1af6..d5fe72dde0 100644 --- a/seaweed-worker/crates/sw-client/src/read.rs +++ b/seaweed-worker/crates/sw-client/src/read.rs @@ -486,12 +486,31 @@ async fn expand_chunks( }; let manifest = FileChunkManifest::decode(raw.as_slice()) .with_context(|| format!("decode manifest {fid}"))?; - let sub = Box::pin(expand_chunks(client, volumes, &manifest.chunks, decoder)).await?; + let held = cut_to_manifest_span(chunk, manifest.chunks); + let sub = Box::pin(expand_chunks(client, volumes, &held, decoder)).await?; data.extend(sub); } Ok(data) } +/// The chunks a manifest holds, cut to the manifest's span: a truncate may +/// have shortened the manifest and left its chunks whole. +fn cut_to_manifest_span(manifest: &FileChunk, held: Vec) -> Vec { + let end = manifest.offset + manifest.size as i64; + held.into_iter() + .filter_map(|mut c| { + if c.offset + c.size as i64 <= end { + return Some(c); + } + if c.offset >= end { + return None; + } + c.size = (end - c.offset) as u64; + Some(c) + }) + .collect() +} + /// Resolve data chunks into non-overlapping visible intervals (latest write wins). fn resolve_visibles(chunks: &[FileChunk]) -> Vec { if let Some(visibles) = resolve_visibles_ordered_non_overlapping(chunks) { @@ -1454,6 +1473,42 @@ mod tests { assert_eq!(tail, &plain[19..], "a size past u64::MAX reads to EOF"); } + #[tokio::test] + async fn a_shortened_manifest_reads_only_its_span() { + let plain: Vec = (0..16u8).map(|i| i + 1).collect(); + let inner = FileChunkManifest { + chunks: vec![chunk("1,aa", 0, 8, 1), chunk("1,bb", 8, 8, 1)], + }; + let needles = HashMap::from([ + ("1,mm".to_string(), inner.encode_to_vec()), + ("1,aa".to_string(), plain[..8].to_vec()), + ("1,bb".to_string(), plain[8..].to_vec()), + ]); + let volumes = VolumeReader::with_transport(Arc::new(BytesTransport { + needles, + reads: AtomicUsize::new(0), + whole_reads: AtomicUsize::new(0), + })); + volumes.location_cache.learn(1, vec!["h:1".into()]); + let mut manifest = chunk("1,mm", 0, 12, 1); + manifest.is_chunk_manifest = true; + let entry = Entry { + attributes: Some(crate::filer_pb::FuseAttributes { + file_size: 20, + ..Default::default() + }), + chunks: vec![manifest], + ..Default::default() + }; + let mut client = FilerClient::connect_lazy("127.0.0.1:1").unwrap(); + let got = read_file(&mut client, &volumes, &entry, 0, 20) + .await + .unwrap(); + let mut want = plain[..12].to_vec(); + want.resize(20, 0); + assert_eq!(got, want); + } + #[tokio::test] async fn encrypted_chunks_need_a_decoder() { let (entry, plain, _, volumes) = encrypted_file(); diff --git a/weed/filer/filechunk_group.go b/weed/filer/filechunk_group.go index 0c6f943742..dac6e1eed3 100644 --- a/weed/filer/filechunk_group.go +++ b/weed/filer/filechunk_group.go @@ -246,7 +246,7 @@ func (group *ChunkGroup) SetChunks(chunks []*filer_pb.FileChunk) error { return err } - dataChunks = append(dataChunks, resolvedChunks...) + dataChunks = append(dataChunks, cutToManifestSpan(chunk, resolvedChunks)...) } sections := make(map[SectionIndex]*FileChunkSection) diff --git a/weed/filer/filechunk_manifest.go b/weed/filer/filechunk_manifest.go index 0b37f8583d..a395c023c3 100644 --- a/weed/filer/filechunk_manifest.go +++ b/weed/filer/filechunk_manifest.go @@ -56,12 +56,49 @@ func SeparateManifestChunks(chunks []*filer_pb.FileChunk) (manifestChunks, nonMa return } -func ResolveChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, startOffset, stopOffset int64, invalidator CacheInvalidator) (dataChunks, manifestChunks []*filer_pb.FileChunk, manifestResolveErr error) { +// ResolveChunkManifest expands manifests into the data chunks they hold. With +// cutToSpan, for reading a file's bytes, each manifest's chunks are cut to the +// manifest's span, since an older truncate could shorten a manifest and leave +// its chunks whole. Deletions and chunk-list comparisons need every referenced +// chunk, so they pass false. +func ResolveChunkManifest(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, startOffset, stopOffset int64, invalidator CacheInvalidator, cutToSpan bool) (dataChunks, manifestChunks []*filer_pb.FileChunk, manifestResolveErr error) { resolver := newChunkManifestResolver(ctx, lookupFileIdFn, invalidator, nil) + resolver.cutToSpan = cutToSpan defer resolver.close() return resolver.resolve(chunks, startOffset, stopOffset) } +// cutToManifestSpan returns the chunks a manifest holds, cut to the manifest's +// span: chunks that start at or past its end are dropped, and one that crosses +// it is shortened, in a copy. A manifest made by MaybeManifestize spans its +// chunks exactly, so this only changes one a truncate shortened. +func cutToManifestSpan(manifest *filer_pb.FileChunk, held []*filer_pb.FileChunk) []*filer_pb.FileChunk { + end := manifest.Offset + int64(manifest.Size) + var cut []*filer_pb.FileChunk + for i, chunk := range held { + chunkEnd := chunk.Offset + int64(chunk.Size) + if chunkEnd <= end { + if cut != nil { + cut = append(cut, chunk) + } + continue + } + if cut == nil { + cut = append(make([]*filer_pb.FileChunk, 0, len(held)), held[:i]...) + } + if chunk.Offset >= end { + continue + } + shortened := proto.Clone(chunk).(*filer_pb.FileChunk) + shortened.Size = uint64(end - chunk.Offset) + cut = append(cut, shortened) + } + if cut == nil { + return held + } + return cut +} + // ResolveChunkManifestWithFilerJwt is ResolveChunkManifest that signs proxied // manifest downloads with filerJwtFn instead of the process-wide filer read // key, for readers carrying per-source credentials. @@ -98,6 +135,16 @@ type chunkManifestResolver struct { workers sync.WaitGroup startOnce sync.Once started bool + // cutToSpan cuts each manifest's chunks to its span (cutToManifestSpan). + cutToSpan bool +} + +// held returns a resolved manifest's chunks, cut to its span for reads. +func (r *chunkManifestResolver) held(manifest *filer_pb.FileChunk, chunks []*filer_pb.FileChunk) []*filer_pb.FileChunk { + if r.cutToSpan { + return cutToManifestSpan(manifest, chunks) + } + return chunks } func newChunkManifestResolver(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator CacheInvalidator, filerJwtFn security.FilerJwtProvider) *chunkManifestResolver { @@ -264,7 +311,7 @@ func (r *chunkManifestResolver) resolve(chunks []*filer_pb.FileChunk, startOffse dataChunks = append(dataChunks, slots[j].chunk) continue } - for _, c := range slots[j].result.chunks { + for _, c := range r.held(slots[j].chunk, slots[j].result.chunks) { if !c.IsChunkManifest && max(c.Offset, startOffset) < min(c.Offset+int64(c.Size), stopOffset) { dataChunks = append(dataChunks, c) } @@ -290,7 +337,7 @@ func (r *chunkManifestResolver) resolve(chunks []*filer_pb.FileChunk, startOffse } manifestChunks = append(manifestChunks, slot.chunk) - subDataChunks, subManifestChunks, subErr := r.resolve(slot.result.chunks, startOffset, stopOffset) + subDataChunks, subManifestChunks, subErr := r.resolve(r.held(slot.chunk, slot.result.chunks), startOffset, stopOffset) if subErr != nil { return dataChunks, nil, subErr } diff --git a/weed/filer/filechunk_manifest_read_test.go b/weed/filer/filechunk_manifest_read_test.go new file mode 100644 index 0000000000..8c7796bb2d --- /dev/null +++ b/weed/filer/filechunk_manifest_read_test.go @@ -0,0 +1,89 @@ +package filer + +import ( + "context" + "math" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +// shortenedManifestFixture serves a manifest of three 100-byte chunks whose +// chunk in the entry an older truncate shortened to 150 bytes. +func shortenedManifestFixture(t *testing.T) (*manifestReadFixture, *filer_pb.FileChunk) { + fixture := newManifestReadFixture(t, map[string][]*filer_pb.FileChunk{ + "short": { + {FileId: "1,01", Offset: 0, Size: 100, ModifiedTsNs: 1}, + {FileId: "1,02", Offset: 100, Size: 100, ModifiedTsNs: 2}, + {FileId: "1,03", Offset: 200, Size: 100, ModifiedTsNs: 3}, + }, + }, nil) + return fixture, &filer_pb.FileChunk{FileId: "short", IsChunkManifest: true, Offset: 0, Size: 150} +} + +func chunkExtents(chunks []*filer_pb.FileChunk) map[string][2]int64 { + extents := make(map[string][2]int64, len(chunks)) + for _, c := range chunks { + extents[c.GetFileIdString()] = [2]int64{c.Offset, c.Offset + int64(c.Size)} + } + return extents +} + +// Reads see the file as the truncate left it; deletions, which resolve +// without cutToSpan, still see every chunk the manifest references. +func TestResolveChunkManifestCutsAShortenedManifest(t *testing.T) { + fixture, shortened := shortenedManifestFixture(t) + ctx := context.Background() + + data, manifests, err := ResolveChunkManifest(ctx, fixture.lookup, []*filer_pb.FileChunk{shortened}, 0, math.MaxInt64, nil, true) + require.NoError(t, err) + require.Len(t, manifests, 1) + require.Equal(t, map[string][2]int64{"1,01": {0, 100}, "1,02": {100, 150}}, chunkExtents(data)) + + all, _, err := ResolveChunkManifest(ctx, fixture.lookup, []*filer_pb.FileChunk{shortened}, 0, math.MaxInt64, nil, false) + require.NoError(t, err) + require.Equal(t, map[string][2]int64{"1,01": {0, 100}, "1,02": {100, 200}, "1,03": {200, 300}}, chunkExtents(all)) + + visibles, err := NonOverlappingVisibleIntervals(ctx, fixture.lookup, []*filer_pb.FileChunk{shortened}, 0, math.MaxInt64) + require.NoError(t, err) + var end int64 + for v := visibles.Front(); v != nil; v = v.Next { + end = max(end, v.StopOffset) + } + require.Equal(t, int64(150), end, "nothing past the shortened manifest is visible") +} + +// A mount reads through a ChunkGroup, which resolves manifests on its own. +func TestChunkGroupCutsAShortenedManifest(t *testing.T) { + fixture, shortened := shortenedManifestFixture(t) + group, err := NewChunkGroup(fixture.lookup, nil, []*filer_pb.FileChunk{shortened}, 1, nil, nil) + require.NoError(t, err) + + held := make(map[string][2]int64) + for _, section := range group.sections { + for id, extent := range chunkExtents(section.chunks) { + held[id] = extent + } + } + require.Equal(t, map[string][2]int64{"1,01": {0, 100}, "1,02": {100, 150}}, held) +} + +// A manifest that spans its chunks, as every fold makes one, keeps them as +// they are, slice and all. +func TestCutToManifestSpanLeavesAWholeManifestAlone(t *testing.T) { + held := []*filer_pb.FileChunk{ + {FileId: "1,01", Offset: 0, Size: 100}, + {FileId: "1,02", Offset: 100, Size: 100}, + } + whole := &filer_pb.FileChunk{FileId: "m", IsChunkManifest: true, Offset: 0, Size: 200} + cut := cutToManifestSpan(whole, held) + require.Equal(t, held, cut) + require.Same(t, &held[0], &cut[0]) + + short := &filer_pb.FileChunk{FileId: "m", IsChunkManifest: true, Offset: 0, Size: 150} + cut = cutToManifestSpan(short, held) + require.Equal(t, map[string][2]int64{"1,01": {0, 100}, "1,02": {100, 150}}, chunkExtents(cut)) + require.Equal(t, uint64(100), held[1].Size, "the resolved chunk is not changed in place") +} diff --git a/weed/filer/filechunk_manifest_resolve_test.go b/weed/filer/filechunk_manifest_resolve_test.go index 8b1902f8b6..c3f9d8cbaa 100644 --- a/weed/filer/filechunk_manifest_resolve_test.go +++ b/weed/filer/filechunk_manifest_resolve_test.go @@ -132,7 +132,7 @@ func TestResolveChunkManifestParallelReadsAreBounded(t *testing.T) { } fixture := newManifestReadFixture(t, manifests, delays) - data, meta, err := ResolveChunkManifest(context.Background(), fixture.lookup, inputs, 0, 1000, nil) + data, meta, err := ResolveChunkManifest(context.Background(), fixture.lookup, inputs, 0, 1000, nil, false) require.NoError(t, err) require.Len(t, data, len(inputs)) require.Len(t, meta, len(inputs)) @@ -152,7 +152,7 @@ func TestResolveChunkManifestPreservesInputOrderWhenReadsCompleteOutOfOrder(t *t data, meta, err := ResolveChunkManifest(context.Background(), fixture.lookup, []*filer_pb.FileChunk{ resolveTestManifest("slow", 0), resolveTestManifest("fast", 100), - }, 0, 200, nil) + }, 0, 200, nil, false) require.NoError(t, err) require.Equal(t, []string{"slow-data", "fast-data"}, fileIDs(data)) require.Equal(t, []string{"slow", "fast"}, fileIDs(meta)) @@ -172,7 +172,7 @@ func TestResolveChunkManifestNestedManifestsKeepDepthFirstOrder(t *testing.T) { data, meta, err := ResolveChunkManifest(context.Background(), fixture.lookup, []*filer_pb.FileChunk{ resolveTestManifest("parent", 0), resolveTestManifest("sibling", 20), - }, 0, 100, nil) + }, 0, 100, nil, false) require.NoError(t, err) require.Equal(t, []string{"parent-data", "nested-data", "sibling-data"}, fileIDs(data)) require.Equal(t, []string{"parent", "nested", "sibling"}, fileIDs(meta)) @@ -189,7 +189,7 @@ func TestResolveChunkManifestFiltersBeforeReadingAndRecursively(t *testing.T) { data, meta, err := ResolveChunkManifest(context.Background(), fixture.lookup, []*filer_pb.FileChunk{ resolveTestManifest("outside", 0), resolveTestManifest("inside", 90), - }, 100, 200, nil) + }, 100, 200, nil, false) require.NoError(t, err) require.Equal(t, []string{"selected"}, fileIDs(data)) require.Equal(t, []string{"inside"}, fileIDs(meta)) @@ -208,7 +208,7 @@ func TestResolveChunkManifestPropagatesReadAndFormatErrorsInInputOrder(t *testin resolveTestData("plain", 0), resolveTestManifest("valid", 10), resolveTestManifest("broken", 20), - }, 0, 100, nil) + }, 0, 100, nil, false) require.Error(t, err) require.Nil(t, meta) require.Equal(t, []string{"plain", "valid-data"}, fileIDs(data)) @@ -216,7 +216,7 @@ func TestResolveChunkManifestPropagatesReadAndFormatErrorsInInputOrder(t *testin lookupErr := errors.New("lookup failed") lookup := func(context.Context, string) ([]string, error) { return nil, lookupErr } - _, _, err = ResolveChunkManifest(context.Background(), lookup, []*filer_pb.FileChunk{resolveTestManifest("lookup-error", 0)}, 0, 100, nil) + _, _, err = ResolveChunkManifest(context.Background(), lookup, []*filer_pb.FileChunk{resolveTestManifest("lookup-error", 0)}, 0, 100, nil, false) require.ErrorIs(t, err, lookupErr) } @@ -234,7 +234,7 @@ func TestResolveChunkManifestCancellationStopsAllReads(t *testing.T) { _, _, err := ResolveChunkManifest(ctx, fixture.lookup, []*filer_pb.FileChunk{ resolveTestManifest("one", 0), resolveTestManifest("two", 10), - }, 0, 100, nil) + }, 0, 100, nil, false) result <- err }() @@ -323,7 +323,7 @@ func TestResolveChunkManifestFastFailureCancelsSlowSibling(t *testing.T) { } result := make(chan error, 1) go func() { - _, _, err := ResolveChunkManifest(ctx, fixture.lookup, chunks, 0, 200, nil) + _, _, err := ResolveChunkManifest(ctx, fixture.lookup, chunks, 0, 200, nil, false) result <- err }() @@ -364,7 +364,7 @@ func TestResolveChunkManifestFastFailureCancelsEncryptedSibling(t *testing.T) { } result := make(chan error, 1) go func() { - _, _, err := ResolveChunkManifest(ctx, fixture.lookup, chunks, 0, 200, nil) + _, _, err := ResolveChunkManifest(ctx, fixture.lookup, chunks, 0, 200, nil, false) result <- err }() @@ -419,7 +419,7 @@ func TestResolveChunkManifestKeepsRealErrorAfterInternalCancellation(t *testing. _, _, err := ResolveChunkManifest(context.Background(), lookup, []*filer_pb.FileChunk{ resolveTestManifest("early", 0), resolveTestManifest("late", 100), - }, 0, 200, nil) + }, 0, 200, nil, false) result <- err }() waitForManifestFailureSignal(t, earlyStarted) @@ -449,7 +449,7 @@ func TestResolveChunkManifestReturnsLaterFailureWithoutRecursingEarlierChildren( data, meta, err := ResolveChunkManifest(context.Background(), fixture.lookup, []*filer_pb.FileChunk{ resolveTestManifest("a", 0), resolveTestManifest("b", 100), - }, 0, 200, nil) + }, 0, 200, nil, false) elapsed := time.Since(start) require.Error(t, err) @@ -476,7 +476,7 @@ func TestResolveChunkManifestExcludesOutOfRangeChildrenOnLaterFailure(t *testing data, _, err := ResolveChunkManifest(context.Background(), fixture.lookup, []*filer_pb.FileChunk{ resolveTestManifest("a", 0), resolveTestManifest("b", 100), - }, 0, 200, nil) + }, 0, 200, nil, false) require.Error(t, err) require.Contains(t, err.Error(), "fail to unmarshal manifest b") require.Equal(t, []string{"a-in-range"}, fileIDs(data), "out-of-range child chunks must be excluded from partial results") @@ -514,7 +514,7 @@ func TestResolveChunkManifestQueuesJobsBeyondWorkerCount(t *testing.T) { resolveTestManifest("stall-2", 200), resolveTestManifest("stall-3", 300), resolveTestManifest("fail", 400), - }, 0, 500, nil) + }, 0, 500, nil, false) result <- err }() @@ -591,7 +591,7 @@ func BenchmarkResolveChunkManifestSerialVsParallel(b *testing.B) { }) b.Run("parallel", func(b *testing.B) { for i := 0; i < b.N; i++ { - _, _, err := ResolveChunkManifest(context.Background(), fixture.lookup, inputs, 0, 1000, nil) + _, _, err := ResolveChunkManifest(context.Background(), fixture.lookup, inputs, 0, 1000, nil, false) if err != nil { b.Fatal(err) } diff --git a/weed/filer/filechunks.go b/weed/filer/filechunks.go index 37779b2632..f0798e9003 100644 --- a/weed/filer/filechunks.go +++ b/weed/filer/filechunks.go @@ -125,11 +125,11 @@ func FindGarbageChunks(visibles *IntervalList[*VisibleInterval], start int64, st func MinusChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, as, bs []*filer_pb.FileChunk, invalidator CacheInvalidator) (delta []*filer_pb.FileChunk, err error) { - aData, aMeta, aErr := ResolveChunkManifest(ctx, lookupFileIdFn, as, 0, math.MaxInt64, invalidator) + aData, aMeta, aErr := ResolveChunkManifest(ctx, lookupFileIdFn, as, 0, math.MaxInt64, invalidator, false) if aErr != nil { return nil, aErr } - bData, bMeta, bErr := ResolveChunkManifest(ctx, lookupFileIdFn, bs, 0, math.MaxInt64, invalidator) + bData, bMeta, bErr := ResolveChunkManifest(ctx, lookupFileIdFn, bs, 0, math.MaxInt64, invalidator, false) if bErr != nil { return nil, bErr } @@ -336,7 +336,7 @@ func MergeIntoChunkViews(chunkViews *IntervalList[*ChunkView], start int64, stop // If the file chunk content is a chunk manifest func NonOverlappingVisibleIntervals(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, startOffset int64, stopOffset int64) (visibles *IntervalList[*VisibleInterval], err error) { - chunks, _, err = ResolveChunkManifest(ctx, lookupFileIdFn, chunks, startOffset, stopOffset, nil) + chunks, _, err = ResolveChunkManifest(ctx, lookupFileIdFn, chunks, startOffset, stopOffset, nil, true) if err != nil { return } diff --git a/weed/filer/filer_hardlink_chunks.go b/weed/filer/filer_hardlink_chunks.go index 8e35e4e1a4..acc0122c42 100644 --- a/weed/filer/filer_hardlink_chunks.go +++ b/weed/filer/filer_hardlink_chunks.go @@ -67,7 +67,7 @@ func (f *Filer) KeepHardLinkedChunks(ctx context.Context, replaced, replacement // withoutChunksOf returns garbage without chunks, without the manifests among // them, and without every chunk those manifests list, nested ones included. func withoutChunksOf(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator CacheInvalidator, chunks, garbage []*filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) { - data, manifests, err := ResolveChunkManifest(ctx, lookupFileIdFn, chunks, 0, math.MaxInt64, invalidator) + data, manifests, err := ResolveChunkManifest(ctx, lookupFileIdFn, chunks, 0, math.MaxInt64, invalidator, false) if err != nil { return nil, err } diff --git a/weed/mount/peer_fetcher.go b/weed/mount/peer_fetcher.go index 292fe8505b..933f3cfdb9 100644 --- a/weed/mount/peer_fetcher.go +++ b/weed/mount/peer_fetcher.go @@ -65,7 +65,7 @@ func (fh *FileHandle) tryPeerRead(ctx context.Context, fileSize int64, buff []by if readStop > fileSize { readStop = fileSize } - dataChunks, _, err := filer.ResolveChunkManifest(ctx, fh.wfs.LookupFn(), chunks, offset, readStop, fh.wfs.CacheInvalidator()) + dataChunks, _, err := filer.ResolveChunkManifest(ctx, fh.wfs.LookupFn(), chunks, offset, readStop, fh.wfs.CacheInvalidator(), true) if err != nil { return 0, 0, fmt.Errorf("resolve manifest: %w", err) } diff --git a/weed/s3api/s3api_chunk_manifest.go b/weed/s3api/s3api_chunk_manifest.go index c60d39ed77..b41e5fce7d 100644 --- a/weed/s3api/s3api_chunk_manifest.go +++ b/weed/s3api/s3api_chunk_manifest.go @@ -42,14 +42,15 @@ func (s3a *S3ApiServer) manifestizeChunks(filePath string, bucket string, ttlSec return folded } -// flattenManifestChunks resolves manifest chunks into flat data chunks, -// returning the resolved-away manifests for callers that must delete the -// superseded blobs once they own the data chunks. +// flattenManifestChunks resolves manifest chunks into flat data chunks, cut to +// each manifest's span since the flat list no longer carries it, returning the +// resolved-away manifests for callers that must delete the superseded blobs +// once they own the data chunks. func (s3a *S3ApiServer) flattenManifestChunks(ctx context.Context, entry *filer_pb.Entry) ([]*filer_pb.FileChunk, error) { if entry == nil || !filer.HasChunkManifest(entry.GetChunks()) { return nil, nil } - dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, s3a.createLookupFileIdFunction(), entry.GetChunks(), 0, math.MaxInt64, s3a.filerClient) + dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, s3a.createLookupFileIdFunction(), entry.GetChunks(), 0, math.MaxInt64, s3a.filerClient, true) if err != nil { return nil, err } diff --git a/weed/s3api/s3api_chunk_manifest_test.go b/weed/s3api/s3api_chunk_manifest_test.go index 6ce26f8f33..93a59d6375 100644 --- a/weed/s3api/s3api_chunk_manifest_test.go +++ b/weed/s3api/s3api_chunk_manifest_test.go @@ -236,3 +236,53 @@ func TestPartRange(t *testing.T) { } } } + +// A flattened copy source or full-object SSE read must not turn the chunks past +// a shortened manifest's span back into object data. +func TestFlattenManifestChunksCutsAShortenedManifest(t *testing.T) { + held := []*filer_pb.FileChunk{ + {Fid: &filer_pb.FileId{VolumeId: 8, FileKey: 1, Cookie: 1}, Offset: 0, Size: 100}, + {Fid: &filer_pb.FileId{VolumeId: 8, FileKey: 2, Cookie: 1}, Offset: 100, Size: 100}, + {Fid: &filer_pb.FileId{VolumeId: 8, FileKey: 3, Cookie: 1}, Offset: 200, Size: 100}, + } + filer_pb.BeforeEntrySerialization(held) + manifestData, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: held}) + require.NoError(t, err) + manifest := &filer_pb.FileChunk{ + Fid: &filer_pb.FileId{VolumeId: 17, FileKey: 1, Cookie: 1}, + Offset: 0, + Size: 150, + IsChunkManifest: true, + } + + volumeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.TrimPrefix(r.URL.Path, "/") != manifest.GetFileIdString() { + http.NotFound(w, r) + return + } + _, _ = w.Write(manifestData) + })) + t.Cleanup(volumeServer.Close) + filerAddress := startFakeFiler(t, &manifestVolumeFiler{volumeServer: strings.TrimPrefix(volumeServer.URL, "http://")}) + filerClient := wdclient.NewFilerClient( + []pb.ServerAddress{filerAddress}, + grpc.WithTransportCredentials(insecure.NewCredentials()), + "", + ) + t.Cleanup(filerClient.Close) + s3a := &S3ApiServer{option: &S3ApiServerOption{}, filerClient: filerClient} + + entry := &filer_pb.Entry{ + Attributes: &filer_pb.FuseAttributes{FileSize: 150}, + Chunks: []*filer_pb.FileChunk{manifest}, + } + removed, err := s3a.flattenManifestChunks(context.Background(), entry) + require.NoError(t, err) + require.Len(t, removed, 1) + + extents := make(map[string][2]int64) + for _, c := range entry.GetChunks() { + extents[c.GetFileIdString()] = [2]int64{c.Offset, c.Offset + int64(c.Size)} + } + require.Equal(t, map[string][2]int64{"8,0100000001": {0, 100}, "8,0200000001": {100, 150}}, extents) +} diff --git a/weed/s3api/s3api_object_handlers.go b/weed/s3api/s3api_object_handlers.go index 71c1bbf15c..6cb5a855e8 100644 --- a/weed/s3api/s3api_object_handlers.go +++ b/weed/s3api/s3api_object_handlers.go @@ -1955,7 +1955,7 @@ func (s3a *S3ApiServer) streamFromVolumeServersWithSSE(w http.ResponseWriter, r // Returns the number of bytes written and any error func (s3a *S3ApiServer) streamDecryptedRangeFromChunks(ctx context.Context, w io.Writer, entry *filer_pb.Entry, offset int64, size int64, sseType string, decryptionKey interface{}) (int64, error) { lookupFileIdFn := s3a.createLookupFileIdFunction() - resolvedChunks, _, err := filer.ResolveChunkManifest(ctx, lookupFileIdFn, entry.GetChunks(), offset, offset+size, s3a.filerClient) + resolvedChunks, _, err := filer.ResolveChunkManifest(ctx, lookupFileIdFn, entry.GetChunks(), offset, offset+size, s3a.filerClient, true) if err != nil { return 0, err } @@ -2422,7 +2422,7 @@ func (s3a *S3ApiServer) getEncryptedStreamFromVolumes(ctx context.Context, entry lookupFileIdFn := s3a.createLookupFileIdFunction() // Resolve chunks - resolvedChunks, _, err := filer.ResolveChunkManifest(ctx, lookupFileIdFn, chunks, offset, offset+size, s3a.filerClient) + resolvedChunks, _, err := filer.ResolveChunkManifest(ctx, lookupFileIdFn, chunks, offset, offset+size, s3a.filerClient, true) if err != nil { return nil, err } diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index be97723968..1c3850851d 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -1335,7 +1335,7 @@ func (s3a *S3ApiServer) createAfterAmbiguousRoute(filePath, bucket, object strin } continue } - resolved, _, resolveErr := filer.ResolveChunkManifest(lookupCtx, s3a.createLookupFileIdFunction(), existing.GetChunks(), 0, math.MaxInt64, s3a.filerClient) + resolved, _, resolveErr := filer.ResolveChunkManifest(lookupCtx, s3a.createLookupFileIdFunction(), existing.GetChunks(), 0, math.MaxInt64, s3a.filerClient, false) if resolveErr != nil || !sameFileChunks(resolved, uploaded) { glog.Warningf("putToFiler: ambiguous routed PUT for %s was superseded by another write; not committing stale entry", filePath) return s3err.ErrServiceUnavailable @@ -1481,7 +1481,7 @@ func (s3a *S3ApiServer) confirmCreateLanded(filePath, bucket, object, routeObjec return s3err.ErrNone } } else { - resolved, _, resolveErr := filer.ResolveChunkManifest(lookupCtx, s3a.createLookupFileIdFunction(), existing.GetChunks(), 0, math.MaxInt64, s3a.filerClient) + resolved, _, resolveErr := filer.ResolveChunkManifest(lookupCtx, s3a.createLookupFileIdFunction(), existing.GetChunks(), 0, math.MaxInt64, s3a.filerClient, false) if resolveErr != nil || !sameFileChunks(resolved, uploaded) { return s3err.ErrNone } diff --git a/weed/server/filer_grpc_server_batch_lookup.go b/weed/server/filer_grpc_server_batch_lookup.go index 4aa016611a..e59d65a103 100644 --- a/weed/server/filer_grpc_server_batch_lookup.go +++ b/weed/server/filer_grpc_server_batch_lookup.go @@ -115,7 +115,7 @@ func resolveFidsBehindManifests(ctx context.Context, response *filer_pb.LookupDi if result == nil || result.Entry == nil || !filer.HasChunkManifest(result.Entry.Chunks) { continue } - dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, lookupFileIdFn, result.Entry.Chunks, 0, math.MaxInt64, invalidator) + dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, lookupFileIdFn, result.Entry.Chunks, 0, math.MaxInt64, invalidator, false) if err != nil { glog.V(1).InfofCtx(ctx, "read auth: resolve manifests of %s: %v", result.Entry.Name, err) continue diff --git a/weed/server/filer_server_handlers_read.go b/weed/server/filer_server_handlers_read.go index 22c33aee3e..7ce8af4e58 100644 --- a/weed/server/filer_server_handlers_read.go +++ b/weed/server/filer_server_handlers_read.go @@ -134,7 +134,7 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) if entry.Chunks, _, err = filer.ResolveChunkManifest( ctx, fs.filer.MasterClient.GetLookupFileIdFunction(), - entry.GetChunks(), 0, math.MaxInt64, fs.filer.MasterClient); err != nil { + entry.GetChunks(), 0, math.MaxInt64, fs.filer.MasterClient, false); err != nil { err = fmt.Errorf("failed to resolve chunk manifest, err: %s", err.Error()) writeJsonError(w, r, http.StatusInternalServerError, err) return diff --git a/weed/shell/command_fs_distribute_chunks.go b/weed/shell/command_fs_distribute_chunks.go index bb05ce6217..db455db399 100644 --- a/weed/shell/command_fs_distribute_chunks.go +++ b/weed/shell/command_fs_distribute_chunks.go @@ -273,7 +273,8 @@ func lookupFileEntry(commandEnv *CommandEnv, dir, name string) (*filer_pb.Entry, } // resolveEntryDataChunks returns the flattened data chunks of an entry. If the -// entry contains manifest chunks, their contents are resolved. hadManifest +// entry contains manifest chunks, their contents are resolved, cut to each +// manifest's span since the rewritten entry no longer carries it. hadManifest // signals whether any manifest chunks were resolved, so the caller knows to // re-manifestize after redistribution. func resolveEntryDataChunks(commandEnv *CommandEnv, entry *filer_pb.Entry) (dataChunks []*filer_pb.FileChunk, hadManifest bool, err error) { @@ -281,7 +282,7 @@ func resolveEntryDataChunks(commandEnv *CommandEnv, entry *filer_pb.Entry) (data if !filer.HasChunkManifest(chunks) { return chunks, false, nil } - dataChunks, _, err = filer.ResolveChunkManifest(context.Background(), filer.LookupFn(commandEnv), chunks, 0, math.MaxInt64, nil) + dataChunks, _, err = filer.ResolveChunkManifest(context.Background(), filer.LookupFn(commandEnv), chunks, 0, math.MaxInt64, nil, true) if err != nil { return nil, true, fmt.Errorf("resolve chunk manifest: %v", err) } diff --git a/weed/shell/command_fs_distribute_chunks_test.go b/weed/shell/command_fs_distribute_chunks_test.go index 97d94e5643..0dc47f6590 100644 --- a/weed/shell/command_fs_distribute_chunks_test.go +++ b/weed/shell/command_fs_distribute_chunks_test.go @@ -424,3 +424,22 @@ func TestPrintRedistributionPlan_Output(t *testing.T) { assert.Contains(t, out, "5 ->") assert.Contains(t, out, "1 ->") } + +// The entry is rewritten with the resolved chunks, so a chunk past a +// shortened manifest's span must not come back with it. +func TestResolveEntryDataChunksCutsAShortenedManifest(t *testing.T) { + chunk := func(key uint64, offset int64) *filer_pb.FileChunk { + return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: key, Cookie: 1}, Offset: offset, Size: 100} + } + shortened := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: 1, Cookie: 1}, Size: 150, IsChunkManifest: true} + env := startStubFiler(t, &stubFilerServer{volumeUrls: map[string]string{"7": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{ + shortened: {chunk(2, 0), chunk(3, 100), chunk(4, 200)}, + })}}) + + dataChunks, hadManifest, err := resolveEntryDataChunks(env, &filer_pb.Entry{Chunks: []*filer_pb.FileChunk{shortened}}) + require.NoError(t, err) + assert.True(t, hadManifest) + require.Len(t, dataChunks, 2) + assert.Equal(t, [2]int64{0, 100}, [2]int64{dataChunks[0].Offset, dataChunks[0].Offset + int64(dataChunks[0].Size)}) + assert.Equal(t, [2]int64{100, 150}, [2]int64{dataChunks[1].Offset, dataChunks[1].Offset + int64(dataChunks[1].Size)}) +} diff --git a/weed/shell/command_fs_merge_volumes.go b/weed/shell/command_fs_merge_volumes.go index 65f928f897..d341bf23ab 100644 --- a/weed/shell/command_fs_merge_volumes.go +++ b/weed/shell/command_fs_merge_volumes.go @@ -338,7 +338,7 @@ func (c *commandFsMergeVolumes) recordPlanSources(ctx context.Context, lookupFn if len(manifests) == 0 { return found, nil } - dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, lookupFn, manifests, 0, math.MaxInt64, nil) + dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, lookupFn, manifests, 0, math.MaxInt64, nil, false) for _, chunk := range slices.Concat(dataChunks, manifestChunks) { if !slices.Contains(manifests, chunk) { record(chunk) @@ -455,7 +455,7 @@ func unreferencedTargets(ctx context.Context, client filer_pb.SeaweedFilerClient return nil } chunks := resp.Entry.GetChunks() - dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, lookupFn, chunks, 0, math.MaxInt64, nil) + dataChunks, manifestChunks, err := filer.ResolveChunkManifest(ctx, lookupFn, chunks, 0, math.MaxInt64, nil, false) if err != nil { return nil } diff --git a/weed/shell/command_fs_verify.go b/weed/shell/command_fs_verify.go index 3f32db9716..980fceee49 100644 --- a/weed/shell/command_fs_verify.go +++ b/weed/shell/command_fs_verify.go @@ -166,13 +166,14 @@ type ItemEntry struct { attr *filer_pb.FuseAttributes } -// resolveAndVerify expands chunk manifests and verifies the entry's needles. +// resolveAndVerify expands chunk manifests, cut to their spans since chunks +// past a shortened manifest are never read, and verifies the entry's needles. // An unresolvable manifest is an entry-level failure even when raw chunks are // healthy; raw chunks are still checked so a missing manifest needle can be pruned. func (c *commandFsVerify) resolveAndVerify(entryPath string, chunks []*filer_pb.FileChunk, errorChunksCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, hasMissingNeedles bool) { dataChunks := chunks manifestResolveFailed := false - if resolved, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), chunks, 0, math.MaxInt64, nil); resolveErr == nil { + if resolved, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), chunks, 0, math.MaxInt64, nil, true); resolveErr == nil { dataChunks = append(resolved, manifestChunks...) } else { manifestResolveFailed = true @@ -495,7 +496,7 @@ func (c *commandFsVerify) verifyTraverseBfs(path string) (fileCount uint64, errC return nil } } - dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), entry.Entry.GetChunks(), 0, math.MaxInt64, nil) + dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), entry.Entry.GetChunks(), 0, math.MaxInt64, nil, true) if resolveErr != nil { return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr) } diff --git a/weed/shell/command_fs_verify_test.go b/weed/shell/command_fs_verify_test.go index bc895f3846..4729046c60 100644 --- a/weed/shell/command_fs_verify_test.go +++ b/weed/shell/command_fs_verify_test.go @@ -16,6 +16,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/seaweedfs/seaweedfs/weed/wdclient" "go.uber.org/atomic" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -401,3 +402,25 @@ func TestFsVerifyManifestResolutionFailure(t *testing.T) { } }) } + +// A chunk past a shortened manifest's span is never read, so its missing +// needle neither fails the entry nor makes it prunable. +func TestFsVerifyIgnoresChunksPastAManifestSpan(t *testing.T) { + chunk := func(key uint64, offset int64) *filer_pb.FileChunk { + return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: key, Cookie: 1}, Offset: offset, Size: 100} + } + shortened := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: 1, Cookie: 1}, Size: 100, IsChunkManifest: true} + filerServer := &stubFilerServer{volumeUrls: map[string]string{"7": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{ + shortened: {chunk(2, 0), chunk(3, 100)}, + })}} + commandEnv, loc, cleanup := newFsVerifyTestCommandEnv(t, filerServer, &fsVerifyTestVolumeServer{missingNeedles: map[uint64]bool{3: true}}) + defer cleanup() + commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{}) + c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc) + + verified, hasMissing := c.resolveAndVerify("/buckets/b/file", + []*filer_pb.FileChunk{shortened}, atomic.NewUint64(0), &sync.WaitGroup{}) + if !verified || hasMissing { + t.Fatalf("verified=%v hasMissing=%v, want the needle past the span ignored", verified, hasMissing) + } +} diff --git a/weed/shell/command_volume_fsck.go b/weed/shell/command_volume_fsck.go index 276130a2e5..764a452d5a 100644 --- a/weed/shell/command_volume_fsck.go +++ b/weed/shell/command_volume_fsck.go @@ -14,6 +14,7 @@ import ( "os" "path" "path/filepath" + "slices" "sort" "strconv" "strings" @@ -68,6 +69,7 @@ type commandVolumeFsck struct { verifyNeedle *bool filerSigningKey string unresolvedManifestEntries atomic.Int64 + pastSpanChunks sync.Map // pastSpanChunk -> struct{} purgedDirsLock sync.Mutex purgedDirs map[util.FullPath]struct{} } @@ -149,6 +151,7 @@ func (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io. // unresolved-manifest counter so a previous failed run can't permanently // suppress -reallyDeleteFromVolume in this session. c.unresolvedManifestEntries.Store(0) + c.pastSpanChunks.Clear() c.purgedDirs = make(map[util.FullPath]struct{}) if err = commandEnv.confirmIsLocked(args); err != nil { @@ -359,7 +362,8 @@ func (c *commandVolumeFsck) collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo m if *c.verbose && entry.Entry.IsDirectory { fmt.Fprintf(c.writer, "checking directory %s\n", util.NewFullPath(entry.Dir, entry.Entry.Name)) } - dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(ctx, filer.LookupFn(c.env), entry.Entry.GetChunks(), 0, math.MaxInt64, nil) + lookupFn := filer.LookupFn(c.env) + dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(ctx, lookupFn, entry.Entry.GetChunks(), 0, math.MaxInt64, nil, false) if resolveErr != nil { // Cancellation/deadline isn't manifest corruption; surface it // so the BFS bails out cleanly without polluting the @@ -382,6 +386,31 @@ func (c *commandVolumeFsck) collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo m dataChunks = entry.Entry.GetChunks() manifestChunks = nil } + // Chunks past a shortened manifest's span are referenced but never + // read, so they neither trigger nor claim the purge. If the cut view + // cannot be resolved, every resolved chunk counts as past the span. + var pastSpan map[string]bool + if queuePurge != nil && len(manifestChunks) > 0 { + visibleData, visibleManifests, visibleErr := filer.ResolveChunkManifest(ctx, lookupFn, entry.Entry.GetChunks(), 0, math.MaxInt64, nil, true) + if errors.Is(visibleErr, context.Canceled) || errors.Is(visibleErr, context.DeadlineExceeded) { + return visibleErr + } + visible := make(map[string]bool) + if visibleErr != nil { + fmt.Fprintf(c.writer, "WARNING: ResolveChunkManifest failed for %s: %v — not purging for its manifest chunks\n", + util.NewFullPath(entry.Dir, entry.Entry.Name), visibleErr) + } else { + for _, chunk := range slices.Concat(visibleData, visibleManifests) { + visible[chunk.GetFileIdString()] = true + } + } + pastSpan = make(map[string]bool) + for _, chunk := range slices.Concat(dataChunks, manifestChunks) { + if fid := chunk.GetFileIdString(); !visible[fid] { + pastSpan[fid] = true + } + } + } dataChunks = append(dataChunks, manifestChunks...) // One Filer entry can have many missing chunks; delete the path only once. purgePathQueued := false @@ -396,10 +425,15 @@ func (c *commandVolumeFsck) collectFilerFileIdAndPaths(dataNodeVolumeIdToVInfo m if len(c.volumeIds) > 0 { _, selectedVolume = c.volumeIds[chunk.Fid.VolumeId] } + chunkPastSpan := pastSpan[chunk.GetFileIdString()] + if chunkPastSpan { + c.pastSpanChunks.Store(pastSpanChunk{path: util.NewFullPath(entry.Dir, entry.Entry.Name), volumeId: chunk.Fid.VolumeId, needleId: types.NeedleId(chunk.Fid.FileKey)}, struct{}{}) + } purgePath := purgeAbsent && selectedVolume && !c.knownVolumeIds[chunk.Fid.VolumeId] && - !purgePathQueued && c.collectionMatcher == nil + !purgePathQueued && c.collectionMatcher == nil && + !chunkPastSpan if purgePath { purgePathQueued = true } @@ -755,17 +789,21 @@ func (c *commandVolumeFsck) oneVolumeFileIdsCheckOneVolume(dataNodeId string, vo if err = db.LoadFromIdx(getVolumeFileIdFile(c.tempFolder, dataNodeId, volumeId)); err != nil { return } - seenPaths := make(map[util.FullPath]struct{}) + // path -> whether its purge is queued + seenPaths := make(map[util.FullPath]bool) if err = c.readFilerFileIdFile(volumeId, func(needleId types.NeedleId, itemPath util.FullPath, hardLinkId []byte) { - if _, found := db.Get(needleId); !found { - if _, seen := seenPaths[itemPath]; seen { - return - } - seenPaths[itemPath] = struct{}{} + if _, found := db.Get(needleId); found { + return + } + queued, seen := seenPaths[itemPath] + if !seen { fmt.Fprintf(c.writer, "%s\n", itemPath) - if queuePurge != nil { - queuePurge(purgeItem{path: itemPath, hardLinkId: hardLinkId}) - } + } + _, pastSpan := c.pastSpanChunks.Load(pastSpanChunk{path: itemPath, volumeId: volumeId, needleId: needleId}) + purge := !queued && queuePurge != nil && !pastSpan + seenPaths[itemPath] = queued || purge + if purge { + queuePurge(purgeItem{path: itemPath, hardLinkId: hardLinkId}) } }); err != nil { return @@ -778,6 +816,12 @@ type purgeItem struct { hardLinkId []byte } +type pastSpanChunk struct { + path util.FullPath + volumeId uint32 + needleId types.NeedleId +} + const ( purgeBatchSize = 64 purgeChannelBufferSize = 4096 diff --git a/weed/shell/command_volume_fsck_missing_volume_test.go b/weed/shell/command_volume_fsck_missing_volume_test.go index f19e28aa30..9babc1cb66 100644 --- a/weed/shell/command_volume_fsck_missing_volume_test.go +++ b/weed/shell/command_volume_fsck_missing_volume_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/storage/needle_map" "github.com/seaweedfs/seaweedfs/weed/storage/types" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/wildcard" @@ -182,3 +183,119 @@ func TestVolumeFsckPurgesEntryWhoseManifestIsOnMissingVolume(t *testing.T) { t.Fatalf("purged paths = %v, want /big, whose manifest is on missing volume 99", purged) } } + +// An older truncate could shorten a manifest and leave its chunks whole. A +// chunk past the cut on a missing volume loses nothing a reader sees, so it +// must not purge the path; it is still reported as a reference. +func TestVolumeFsckPurgesOnlyForChunksWithinAManifestSpan(t *testing.T) { + chunk := func(volumeID uint32, fileKey uint64, offset int64) *filer_pb.FileChunk { + return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: volumeID, FileKey: fileKey, Cookie: 1}, Offset: offset, Size: 100} + } + manifest := func(fileKey uint64, size uint64) *filer_pb.FileChunk { + return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: fileKey, Cookie: 1}, Size: size, IsChunkManifest: true} + } + shortened, whole := manifest(1, 100), manifest(4, 200) + stub := &stubFilerServer{ + entries: map[string]*filer_pb.Entry{ + "/": {IsDirectory: true}, + "/short": {Chunks: []*filer_pb.FileChunk{shortened}}, + "/lost": {Chunks: []*filer_pb.FileChunk{whole}}, + }, + volumeUrls: map[string]string{"7": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{ + shortened: {chunk(7, 2, 0), chunk(99, 3, 100)}, + whole: {chunk(99, 5, 0), chunk(7, 6, 100)}, + })}, + } + verbose := false + findMissing := true + var output bytes.Buffer + c := &commandVolumeFsck{ + tempFolder: t.TempDir(), + verbose: &verbose, + findMissingChunksInFiler: &findMissing, + writer: &output, + env: startStubFiler(t, stub), + volumeIds: map[uint32]bool{99: true}, + knownVolumeIds: map[uint32]bool{7: true}, + } + var purged []purgeItem + if err := c.collectFilerFileIdAndPaths(map[string]map[uint32]VInfo{"dn1": {7: {}}}, true, func(item purgeItem) { + purged = append(purged, item) + }, 0, 0); err != nil { + t.Fatalf("collect filer references: %v", err) + } + + if len(purged) != 1 || purged[0].path != util.FullPath("/lost") { + t.Fatalf("purged paths = %v, want only /lost, whose visible chunk is on missing volume 99", purged) + } + if !strings.Contains(output.String(), "99,300000001 /short volume not found\n") { + t.Fatalf("missing-volume report %q lacks the chunk past /short's span", output.String()) + } +} + +func TestVolumeFsckListedVolumePurgesOnlyForChunksWithinAManifestSpan(t *testing.T) { + chunk := func(fileKey uint64, offset int64) *filer_pb.FileChunk { + return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: fileKey, Cookie: 1}, Offset: offset, Size: 100} + } + manifest := func(fileKey uint64, size uint64) *filer_pb.FileChunk { + return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: fileKey, Cookie: 1}, Size: size, IsChunkManifest: true} + } + shortened, whole, both := manifest(1, 100), manifest(4, 200), manifest(7, 100) + stub := &stubFilerServer{ + entries: map[string]*filer_pb.Entry{ + "/": {IsDirectory: true}, + "/short": {Chunks: []*filer_pb.FileChunk{shortened}}, + "/lost": {Chunks: []*filer_pb.FileChunk{whole}}, + "/both": {Chunks: []*filer_pb.FileChunk{both}}, + }, + volumeUrls: map[string]string{"7": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{ + shortened: {chunk(2, 0), chunk(3, 100)}, + whole: {chunk(5, 0), chunk(6, 100)}, + both: {chunk(8, 0), chunk(9, 100)}, + })}, + } + tempDir := t.TempDir() + verbose := false + findMissing := true + var output bytes.Buffer + c := &commandVolumeFsck{ + tempFolder: tempDir, + verbose: &verbose, + findMissingChunksInFiler: &findMissing, + writer: &output, + env: startStubFiler(t, stub), + volumeIds: map[uint32]bool{}, + knownVolumeIds: map[uint32]bool{7: true}, + } + var purged []purgeItem + queuePurge := func(item purgeItem) { purged = append(purged, item) } + if err := c.collectFilerFileIdAndPaths(map[string]map[uint32]VInfo{"dn1": {7: {}}}, false, queuePurge, 0, 0); err != nil { + t.Fatalf("collect filer references: %v", err) + } + // The index lacks 3, past /short's span, 5, within /lost's, and both + // 9, past /both's span, and /both's manifest 7, listed after it. + db := needle_map.NewMemDb() + for _, needleId := range []types.NeedleId{1, 2, 4, 6, 8} { + if err := db.Set(needleId, types.ToOffset(16), types.Size(1)); err != nil { + t.Fatalf("seed volume idx: %v", err) + } + } + if err := db.SaveToIdx(getVolumeFileIdFile(tempDir, "dn1", 7)); err != nil { + t.Fatalf("write volume idx: %v", err) + } + db.Close() + + if err := c.oneVolumeFileIdsCheckOneVolume("dn1", 7, queuePurge); err != nil { + t.Fatalf("check volume: %v", err) + } + purgedPaths := make(map[util.FullPath]bool) + for _, item := range purged { + purgedPaths[item.path] = true + } + if len(purged) != 2 || !purgedPaths["/lost"] || !purgedPaths["/both"] { + t.Fatalf("purged paths = %v, want /lost and /both, whose visible chunks are missing", purged) + } + if !strings.Contains(output.String(), "/short\n") { + t.Fatalf("missing-chunk report %q lacks /short", output.String()) + } +} diff --git a/weed/shell/command_volume_fsck_test.go b/weed/shell/command_volume_fsck_test.go index 33281872fd..373111cc67 100644 --- a/weed/shell/command_volume_fsck_test.go +++ b/weed/shell/command_volume_fsck_test.go @@ -21,8 +21,10 @@ import ( "github.com/seaweedfs/seaweedfs/weed/storage/needle_map" "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" ) func TestVolumeFsckCanPurgeDirectory(t *testing.T) { @@ -86,6 +88,18 @@ type stubFilerServer struct { entries map[string]*filer_pb.Entry writtenAfterLookup map[string]bool deleted []string + // volumeUrls locates volumes for LookupVolume; other volumes are not found. + volumeUrls map[string]string +} + +func (s *stubFilerServer) LookupVolume(ctx context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) { + resp := &filer_pb.LookupVolumeResponse{LocationsMap: make(map[string]*filer_pb.Locations)} + for _, vid := range req.VolumeIds { + if url, found := s.volumeUrls[vid]; found { + resp.LocationsMap[vid] = &filer_pb.Locations{Locations: []*filer_pb.Location{{Url: url, PublicUrl: url}}} + } + } + return resp, nil } func (s *stubFilerServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { @@ -167,10 +181,37 @@ func startStubFiler(t *testing.T, stub *stubFilerServer) *CommandEnv { filer_pb.RegisterSeaweedFilerServer(srv, stub) go srv.Serve(lis) t.Cleanup(srv.Stop) - return &CommandEnv{option: &ShellOptions{ - FilerAddress: pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", lis.Addr().(*net.TCPAddr).Port)), - GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), - }} + return &CommandEnv{ + option: &ShellOptions{ + FilerAddress: pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", lis.Addr().(*net.TCPAddr).Port)), + GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + }, + MasterClient: wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{}), + } +} + +// startStubManifestVolume serves each manifest's chunks as its blob and returns +// the server's address, for a stubFilerServer's volumeUrls. +func startStubManifestVolume(t *testing.T, manifests map[*filer_pb.FileChunk][]*filer_pb.FileChunk) string { + t.Helper() + blobs := make(map[string][]byte, len(manifests)) + for manifest, held := range manifests { + blob, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: held}) + if err != nil { + t.Fatalf("marshal manifest: %v", err) + } + blobs["/"+manifest.GetFileIdString()] = blob + } + volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + blob, found := blobs[r.URL.Path] + if !found { + http.NotFound(w, r) + return + } + w.Write(blob) + })) + t.Cleanup(volume.Close) + return strings.TrimPrefix(volume.URL, "http://") } func TestVolumeFsckPurgeEmptyDirectories(t *testing.T) {