Files
seaweedfs/weed/server/filer_grpc_server_batch_lookup.go
T
c7fc40c76c filer, mount: read a manifest's chunks only within its span (#13048)
* filer, mount: read a manifest's chunks only within its span

Until #13042, a truncate through a manifest only shortened the manifest
chunk; the chunks it holds stayed whole. Reads resolve those chunks at
their own offsets and sizes, so once such a file grows over the cut again
without writing it, by an extending truncate or a write past the end, the
cut bytes come back where zeros belong. #13042 keeps new truncates from
leaving such manifests, but files a mount truncated between #12462 and
#13042 still have them.

Reproduced with weed mount on a local cluster: a mount from before #13042
appends 700 lines with one close() each, so the first 256 fold into a
manifest, and truncates the file to 100 lines; a mount from current master
then extends it past its old end with ftruncate. The extended range read
8,580 bytes of the cut lines instead of zeros, through that mount and
through the filer.

Reads now cut each manifest's chunks to the manifest's span:
ResolveChunkManifestForRead, used by NonOverlappingVisibleIntervals (filer
and S3 streaming, WebDAV, the mount's merge reads), the S3 ranged reads and
the mount's peer reads, and ChunkGroup for the mount's reads. A manifest
made by MaybeManifestize spans its chunks exactly, so only shortened ones
change. ResolveChunkManifest still returns the chunks whole: MinusChunks,
deletions and the other chunk-list comparisons need every chunk a manifest
references, or the chunks past the cut would never be deleted.

* sw-client: read a manifest's chunks only within its span

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: read a manifest's chunks only within its span

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: drop PR numbers from the manifest span comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: fold ResolveChunkManifestForRead into ResolveChunkManifest

ResolveChunkManifest takes cutToSpan: the read paths pass true, the
deletion and chunk-list comparison paths pass false.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: cut manifests to their span when flattening an object's chunks

A full-object SSE GET, CopyObject and UploadPartCopy flatten the
source's manifests into a plain chunk list, which drops each manifest's
span, so the chunks a truncate left past a shortened manifest came back
as object data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: purge a volume.fsck path only for chunks within a manifest's span

A chunk past a shortened manifest's span is still referenced but never
read, so a missing volume under it loses nothing. The purge decision now
uses the span-cut chunks while the inventory keeps every reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: cut manifests to their span in fs.distribute_chunks

The entry is rewritten with the resolved chunks as a flat list or a new
manifest that spans them, so chunks past a shortened manifest's span
became readable again. The filer's update still deletes them, since it
compares against the old entry's uncut chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: verify only the chunks within a manifest's span in fs.verify

A chunk past a shortened manifest's span is never read, so a missing
needle under it failed the entry and, with -pruneEntries, deleted a file
whose readable bytes were intact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: mark the chunks past a manifest's span instead of allowing the visible ones

The purge gate now skips only the resolved chunks that the span cut drops,
so chunks that come from outside the manifests keep their purge behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: skip the purge for a missing past-span chunk on a listed volume

volume.fsck -findMissingChunksInFiler queued a path for deletion when a
listed volume's index lacked any chunk the uncut inventory recorded,
including a chunk past a shortened manifest's span that no read reaches.
Record those chunks per path during the filer walk and let only a missing
chunk within the span queue the purge. The path is still reported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:51:15 -08:00

323 lines
12 KiB
Go

package weed_server
import (
"context"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
maxFilerBatchLookupRequests = 4096
maxFilerBatchLookupWorkers = 32
)
type filerBatchEntryFinder func(context.Context, util.FullPath) (*filer.Entry, int64, error)
type filerBatchVolumeLookup func(context.Context, []string) (map[string][]wdclient.Location, error)
// LookupDirectoryEntries performs exact entry lookups concurrently while
// preserving request order, then resolves every referenced volume in one
// deduplicated master lookup.
func (fs *FilerServer) LookupDirectoryEntries(ctx context.Context, req *filer_pb.LookupDirectoryEntriesRequest) (*filer_pb.LookupDirectoryEntriesResponse, error) {
lookupVolumes := selectFilerBatchVolumeLookup(req,
fs.filer.MasterClient.LookupVolumeIdsWithFallback,
fs.filer.MasterClient.LookupVolumeIdsAuthoritative)
response, err := lookupDirectoryEntries(ctx, req, fs.filer.Signature, fs.fencedFindEntry, lookupVolumes)
if err != nil {
return nil, err
}
if fs.volumeGuard != nil {
readSigningEnabled := len(fs.volumeGuard.ReadSigningKey()) > 0
populateReadAuth(ctx, response, readSigningEnabled, fs.filer.MasterClient.GetLookupFileIdFunction(), fs.filer.MasterClient, fs.maybeGetVolumeReadJwtAuthorizationToken)
}
return response, nil
}
func selectFilerBatchVolumeLookup(req *filer_pb.LookupDirectoryEntriesRequest, cached, authoritative filerBatchVolumeLookup) filerBatchVolumeLookup {
if req != nil && req.GetUnavailableVolumeIsMiss() {
// DeletedVids is an asynchronous cache invalidation hint and its delivery
// is deliberately best-effort. Cache reads must therefore confirm the
// unique Volume IDs with Master before treating a location as live.
return authoritative
}
return cached
}
func populateBatchReadAuth(response *filer_pb.LookupDirectoryEntriesResponse, mint func(string) string) {
response.ReadAuth = make(map[string]string)
for _, result := range response.Results {
if result == nil || result.Entry == nil {
continue
}
for _, chunk := range result.Entry.Chunks {
fid := chunk.GetFileIdString()
if fid == "" {
continue
}
if token := mint(fid); token != "" {
response.ReadAuth[fid] = token
}
}
}
}
// populateReadAuth mints read_auth tokens for every chunk a reader must fetch:
// the chunks listed on each entry, plus the chunks behind any manifest chunks --
// the data chunks and any intermediate (nested) manifest chunks, since the entry
// lists only the top-level manifests and a client reading with filer-issued
// tokens could fetch those but not the chunks they resolve to.
//
// It resolves manifests first and mints every token afterwards. Read JWTs are
// short-lived (default 60s), so a token must not be signed before the manifest
// downloads this lookup needs have run: otherwise a token minted early -- for a
// listed chunk, an ordinary file, or an earlier entry's chunks -- could expire
// while later entries' manifests download, and the response would carry an
// already-expired token.
func populateReadAuth(ctx context.Context, response *filer_pb.LookupDirectoryEntriesResponse, readSigningEnabled bool, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator filer.CacheInvalidator, mint func(string) string) {
manifestBackedFids := resolveFidsBehindManifests(ctx, response, readSigningEnabled, lookupFileIdFn, invalidator)
populateBatchReadAuth(response, mint)
mintReadAuth(response, manifestBackedFids, mint)
}
// resolveFidsBehindManifests returns the fids a reader must fetch to read the
// files behind the response's manifest chunks: the leaf data chunks and every
// intermediate (nested) manifest chunk ResolveChunkManifest traverses to reach
// them. The top-level manifest chunks are listed on the entry and already minted
// by populateBatchReadAuth; the dedup in mintReadAuth drops that overlap, so the
// net new tokens are the data chunks and any nested manifests.
//
// It resolves manifests -- which downloads and expands them from the volume
// servers -- only when read signing is enabled: with no read key the volume
// server does not enforce read JWTs and mint returns "" for every chunk, so the
// download would be wasted I/O that yields no token. The invalidator (the master
// client, as the filer's own resolveManifest read path passes) lets a manifest
// whose volume moved refresh the stale cached location and retry instead of
// failing and leaving its data chunks without tokens.
func resolveFidsBehindManifests(ctx context.Context, response *filer_pb.LookupDirectoryEntriesResponse, readSigningEnabled bool, lookupFileIdFn wdclient.LookupFileIdFunctionType, invalidator filer.CacheInvalidator) []string {
if !readSigningEnabled {
return nil
}
var fids []string
for _, result := range response.Results {
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, false)
if err != nil {
glog.V(1).InfofCtx(ctx, "read auth: resolve manifests of %s: %v", result.Entry.Name, err)
continue
}
for _, chunk := range dataChunks {
if fid := chunk.GetFileIdString(); fid != "" {
fids = append(fids, fid)
}
}
for _, chunk := range manifestChunks {
if fid := chunk.GetFileIdString(); fid != "" {
fids = append(fids, fid)
}
}
}
return fids
}
// mintReadAuth adds a read_auth token for each fid not already covered.
func mintReadAuth(response *filer_pb.LookupDirectoryEntriesResponse, fids []string, mint func(string) string) {
for _, fid := range fids {
if response.ReadAuth[fid] != "" {
continue
}
if token := mint(fid); token != "" {
response.ReadAuth[fid] = token
}
}
}
func lookupDirectoryEntries(
ctx context.Context,
req *filer_pb.LookupDirectoryEntriesRequest,
logSignature int32,
findEntry filerBatchEntryFinder,
lookupVolumes filerBatchVolumeLookup,
) (*filer_pb.LookupDirectoryEntriesResponse, error) {
if err := validateFilerBatchLookupRequest(req); err != nil {
return nil, err
}
results := make([]*filer_pb.LookupDirectoryEntryResult, len(req.Requests))
resultVolumeIDs := make([]map[string]struct{}, len(req.Requests))
jobs := make(chan int)
workerCount := min(len(req.Requests), maxFilerBatchLookupWorkers)
var workers sync.WaitGroup
workers.Add(workerCount)
for range workerCount {
go func() {
defer workers.Done()
for index := range jobs {
request := req.Requests[index]
entry, logTsNs, err := findEntry(ctx, util.JoinPath(request.Directory, request.Name))
result := &filer_pb.LookupDirectoryEntryResult{
LogTsNs: logTsNs,
LogSignature: logSignature,
}
switch {
case errors.Is(err, filer_pb.ErrNotFound):
results[index] = result
case err != nil:
result.Error = err.Error()
results[index] = result
case entry == nil:
result.Error = "entry lookup returned no entry"
results[index] = result
default:
pbEntry := entry.ToProtoEntry()
volumeIDs, volumeErr := filerBatchEntryVolumeIDs(pbEntry)
result.Found = true
result.Entry = pbEntry
if volumeErr != nil {
result.Error = volumeErr.Error()
}
results[index] = result
resultVolumeIDs[index] = volumeIDs
}
}
}()
}
for index := range req.Requests {
select {
case jobs <- index:
case <-ctx.Done():
close(jobs)
workers.Wait()
return nil, status.FromContextError(ctx.Err()).Err()
}
}
close(jobs)
workers.Wait()
if err := ctx.Err(); err != nil {
return nil, status.FromContextError(err).Err()
}
allVolumeIDs := make(map[string]struct{})
for _, volumeIDs := range resultVolumeIDs {
for volumeID := range volumeIDs {
allVolumeIDs[volumeID] = struct{}{}
}
}
volumeIDs := make([]string, 0, len(allVolumeIDs))
for volumeID := range allVolumeIDs {
volumeIDs = append(volumeIDs, volumeID)
}
sort.Strings(volumeIDs)
response := &filer_pb.LookupDirectoryEntriesResponse{
Results: results,
LocationsMap: make(map[string]*filer_pb.Locations, len(volumeIDs)),
}
if len(volumeIDs) == 0 {
return response, nil
}
locationsByVolume, lookupErr := lookupVolumes(ctx, volumeIDs)
// The provider returns a nil map when it got no answer, and a populated map
// with the volumes the master does not serve reported as errors when it did,
// so a nil map is the only sign of an unanswered lookup. Only a volume the
// master itself left out may become a miss; anything else stays an error.
missIsAuthoritative := req.UnavailableVolumeIsMiss && locationsByVolume != nil
for _, volumeID := range volumeIDs {
locations := locationsByVolume[volumeID]
if len(locations) != 0 {
response.LocationsMap[volumeID] = &filer_pb.Locations{
Locations: wdclientLocationsToPb(locations),
}
continue
}
if !missIsAuthoritative {
response.LocationsMap[volumeID] = &filer_pb.Locations{}
}
for index, entryVolumeIDs := range resultVolumeIDs {
if _, affected := entryVolumeIDs[volumeID]; !affected {
continue
}
if missIsAuthoritative && results[index].Error == "" {
results[index].Found = false
results[index].Entry = nil
resultVolumeIDs[index] = nil
continue
}
message := fmt.Sprintf("volume %s has no locations", volumeID)
if lookupErr != nil {
message += ": " + lookupErr.Error()
}
results[index].Error = appendFilerBatchLookupError(results[index].Error, message)
}
}
return response, nil
}
func validateFilerBatchLookupRequest(req *filer_pb.LookupDirectoryEntriesRequest) error {
if req == nil || len(req.Requests) == 0 {
return status.Error(codes.InvalidArgument, "batch lookup requires at least one request")
}
if len(req.Requests) > maxFilerBatchLookupRequests {
return status.Errorf(codes.ResourceExhausted, "batch lookup has %d requests; maximum is %d", len(req.Requests), maxFilerBatchLookupRequests)
}
for index, request := range req.Requests {
if request == nil {
return status.Errorf(codes.InvalidArgument, "batch lookup request %d is missing", index)
}
if request.Directory == "" || !strings.HasPrefix(request.Directory, "/") || strings.ContainsRune(request.Directory, '\x00') {
return status.Errorf(codes.InvalidArgument, "batch lookup request %d has invalid directory", index)
}
if request.Name == "" || request.Name == "." || request.Name == ".." || strings.ContainsAny(request.Name, "/\x00") {
return status.Errorf(codes.InvalidArgument, "batch lookup request %d has invalid name", index)
}
}
return nil
}
func filerBatchEntryVolumeIDs(entry *filer_pb.Entry) (map[string]struct{}, error) {
volumeIDs := make(map[string]struct{})
for index, chunk := range entry.GetChunks() {
if chunk == nil {
return volumeIDs, fmt.Errorf("entry chunk %d is missing", index)
}
if chunk.Fid != nil {
volumeIDs[strconv.FormatUint(uint64(chunk.Fid.VolumeId), 10)] = struct{}{}
continue
}
if chunk.FileId == "" {
return volumeIDs, fmt.Errorf("entry chunk %d has no file id", index)
}
fid, err := needle.ParseFileIdFromString(chunk.FileId)
if err != nil {
return volumeIDs, fmt.Errorf("entry chunk %d has invalid file id: %w", index, err)
}
volumeIDs[strconv.FormatUint(uint64(fid.VolumeId), 10)] = struct{}{}
}
return volumeIDs, nil
}
func appendFilerBatchLookupError(existing, next string) string {
if existing == "" {
return next
}
return existing + "; " + next
}