Files
seaweedfs/weed/mount/weedfs_metadata_flush.go
T
Eliah RusinandChris Lu cfa8afec92 filer: guard FoundationDB 100KB value limit and pack earlier (#11161)
* filer: guard the FoundationDB value size limit, not the transaction limit

An entry's whole chunk list is one FoundationDB value, and FDB caps a value at
100,000 bytes while a transaction may reach 10MB. UpdateEntry checked the
transaction limit, so every entry between the two limits passed the guard and
was rejected by FDB itself with error 2103 (Value length exceeds limit). The
failure surfaced inside the store rather than at the guard, so the S3 layer
dropped the connection and clients saw a network fault instead of an error.

Check the value limit in UpdateEntry and KvPut instead, after gzip and before
the transaction, with an error that names the limit it hit. The removed
transaction-size constant guarded nothing else: DeleteFolderChildren batches by
entry count.

Refs #11158

* filer: fold at 500 chunks in the foundationdb build

Manifest packing is what keeps a large file's entry small, but it only ran once
a flat chunk list reached 10000 chunks. A FoundationDB value stops at 100,000
bytes and an entry's whole chunk list is one value, which at ~100 bytes per
chunk record is about 1000 chunks -- so on FDB the write always failed before
packing could help: a 3.3 GiB PutObject at the default -maxMB=4 was already
past the limit.

FoundationDB support is its own build (`go build -tags foundationdb`, shipped
as its own image), so the batch is a build-time choice and needs no negotiation
at run time. The tagged build folds at 500, every other build keeps 10000 and
is untouched.

500 is not arbitrary: a single fold level leaves (chunks/batch) manifest
pointers plus up to (batch-1) unfolded chunks in the entry, so the reachable
chunk count is highest when the two terms are near equal. For a 100,000-byte
budget that optimum is 500, which holds an entry inside the limit up to
~250,000 chunks -- ~1 TB at -maxMB=4, against ~4 GB before. Larger files need
nested packing, which no batch size substitutes for.

One binary serves every role in that image, so the filer and each client that
folds -- S3, mount, WebDAV, weed shell, filer.copy -- agree on the batch by
construction. A binary built with the tag but pointed at another store folds
earlier than that store requires, costing one manifest blob per 500 chunks and
one read to resolve it.

Fixes #11158

* filer: fold with rollback inside MaybeManifestize, not beside it

A fold that fails midway has already uploaded manifest blobs for its earlier
batches, and returns only the data chunks -- dropping the manifests it had
separated out of the caller's list. Both were wrong in ways that mattered:

  - AppendToEntry assigned that shortened list straight to entry.Chunks and
    created the entry, so an append to an already-folded file whose fold
    failed lost every previously folded chunk. weed mount had the same shape.
  - cleanupChunks logged the error as "not good, but should be ok" and then
    returned it through a named result, failing the whole CreateEntry or
    UpdateEntry, while the blobs it had written stayed behind referenced by
    nothing.

The S3 path was alone in handling this, through a private helper beside
MaybeManifestize. A second entry point next to the one everything else calls
just means the wrong one gets used, so the behaviour moves inside
MaybeManifestize: on failure it returns inputChunks as it received them, and
hands the blobs it saved to a deleteChunks callback. The filer, S3 and
filer.copy pass their existing deleters -- filer.copy already cleans up this
way after a failed upload -- and mount, WebDAV and weed shell pass nil, which
reports the blobs rather than collecting them, as before. Each caller keeps its
own error policy: the filer HTTP PUT path and filer.copy still fail the request,
the rest still continue with the flat list, which is a correct entry.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-09-04 23:12:27 -07:00

206 lines
7.3 KiB
Go

package mount
import (
"context"
"sync"
"time"
"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/util"
"google.golang.org/protobuf/proto"
)
// loopFlushDirtyMetadata periodically flushes dirty file metadata to the filer.
// This protects newly uploaded chunks from being purged by volume.fsck orphan cleanup
// for files that remain open for extended periods without being closed.
//
// The problem: When a file is opened and written to continuously, chunks are uploaded
// to volume servers but the file metadata (containing chunk references) is only saved
// to the filer on file close or fsync. If volume.fsck runs during this window, it may
// identify these chunks as orphans (since they're not referenced in filer metadata)
// and purge them.
//
// This background task periodically flushes metadata for open files, ensuring chunk
// references are visible to volume.fsck even before files are closed.
func (wfs *WFS) loopFlushDirtyMetadata() {
if wfs.option.MetadataFlushSeconds <= 0 {
glog.V(0).Infof("periodic metadata flush disabled")
return
}
flushInterval := time.Duration(wfs.option.MetadataFlushSeconds) * time.Second
glog.V(0).Infof("periodic metadata flush enabled, interval: %v", flushInterval)
ticker := time.NewTicker(flushInterval)
defer ticker.Stop()
for range ticker.C {
wfs.flushAllDirtyMetadata()
}
}
// flushAllDirtyMetadata iterates through all open file handles and flushes
// metadata for files that have dirty metadata (chunks uploaded but not yet persisted).
func (wfs *WFS) flushAllDirtyMetadata() {
// Collect file handles with dirty metadata under a read lock
var dirtyHandles []*FileHandle
wfs.fhMap.RLock()
for _, fh := range wfs.fhMap.inode2fh {
if fh.dirtyMetadata {
dirtyHandles = append(dirtyHandles, fh)
}
}
wfs.fhMap.RUnlock()
if len(dirtyHandles) == 0 {
return
}
glog.V(3).Infof("flushing metadata for %d open files", len(dirtyHandles))
// Process dirty handles in parallel with limited concurrency
var wg sync.WaitGroup
concurrency := wfs.option.ConcurrentWriters
if concurrency <= 0 {
concurrency = 16
}
sem := make(chan struct{}, concurrency)
for _, fh := range dirtyHandles {
wg.Add(1)
sem <- struct{}{}
go func(handle *FileHandle) {
defer wg.Done()
defer func() { <-sem }()
if err := wfs.flushFileMetadata(handle); err != nil {
glog.Warningf("failed to flush metadata for %s: %v", handle.FullPath(), err)
}
}(fh)
}
wg.Wait()
}
// flushFileMetadata flushes the current file metadata to the filer without
// flushing dirty pages from memory. This updates chunk references in the filer
// so volume.fsck can see them, while keeping data in the write buffer.
//
// When -dlm is enabled, the distributed lock is already held by the FileHandle
// from open-for-write through close, so no additional distributed lock is
// needed here. The local fhLockTable lock below serializes within this mount.
func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
// Acquire exclusive lock on the file handle
fhActiveLock := fh.wfs.fhLockTable.AcquireLock("flushMetadata", fh.fh, util.ExclusiveLock)
defer fh.wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
// Double-check dirty flag under lock
if !fh.dirtyMetadata {
return nil
}
fileFullPath := fh.FullPath()
dir, name := fileFullPath.DirAndName()
glog.V(4).Infof("flushFileMetadata %s fh %d", fileFullPath, fh.fh)
if fh.GetEntry() == nil {
return nil
}
// Snapshot the current chunk list. Async uploader goroutines call
// entry.AppendChunks while we run CompactFileChunks / MaybeManifestize
// below — those steps can take seconds (manifest upload is a round trip).
// We must remember the snapshot length so we can splice any chunks that
// land after the snapshot back in once we reassign entry.Chunks; without
// that, the naked overwrite below clobbers them and the file ends up
// missing chunk references for data the volumes already store.
var snapshotChunks []*filer_pb.FileChunk
var snapshotLen int
fh.UpdateEntry(func(e *filer_pb.Entry) {
// Do not stamp mtime/ctime here. Write/SetAttr already maintain
// them on the entry; overwriting at periodic-flush time clobbered
// user-set mtime (utimes/touch -m -d) once the timer fired.
e.Name = name
snapshotLen = len(e.Chunks)
if snapshotLen > 0 {
snapshotChunks = append([]*filer_pb.FileChunk(nil), e.Chunks...)
}
})
if snapshotLen == 0 {
return nil
}
// Separate manifest and non-manifest chunks
manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(snapshotChunks)
// Compact chunks to remove fully overlapped ones
compactedChunks, _ := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
// Try to create manifest chunks for large files
// no chunk deleter here: a failed fold reports the blobs it saved
compactedChunks, manifestErr := filer.MaybeManifestize(wfs.saveDataAsChunk(fileFullPath), nil, compactedChunks)
if manifestErr != nil {
glog.V(0).Infof("flushFileMetadata MaybeManifestize: %v", manifestErr)
}
processedPrefix := append(compactedChunks, manifestChunks...)
// Splice the processed snapshot back in, preserving any chunks that
// async uploaders appended after our snapshot, and clone the resulting
// entry for the filer request while still holding the lock so the
// request can't observe a half-merged state.
var requestEntry *filer_pb.Entry
fh.UpdateEntry(func(e *filer_pb.Entry) {
// e.Chunks[snapshotLen:] is whatever async uploaders appended while
// we processed the snapshot. processedPrefix is freshly built and not
// referenced elsewhere, so we can append straight onto it.
var tail []*filer_pb.FileChunk
if len(e.Chunks) > snapshotLen {
tail = e.Chunks[snapshotLen:]
}
e.Chunks = append(processedPrefix, tail...)
requestEntry = proto.Clone(e).(*filer_pb.Entry)
})
request := &filer_pb.CreateEntryRequest{
Directory: string(dir),
Entry: requestEntry,
Signatures: []int32{wfs.signature},
SkipCheckParentDirectory: true,
}
// Snapshot with local ids before the request mapping mutates the clone:
// on ack this becomes the handle's base, judged against future events.
baseSnapshot := proto.Clone(requestEntry).(*filer_pb.Entry)
wfs.mapPbIdFromLocalToFiler(request.Entry)
resp, err := wfs.streamCreateEntry(context.Background(), request)
if err != nil {
return err
}
event := resp.GetMetadataEvent()
if event == nil {
event = metadataUpdateEvent(string(dir), request.Entry)
if event != nil {
event.TsNs = ackVersionTsNs(resp)
}
}
fh.setAuthoritativeBase(baseSnapshot)
fh.advanceEntryVersion(ackVersionTsNs(resp), resp.GetLogSignature())
if applyErr := wfs.applyLocalMetadataEvent(context.Background(), event); applyErr != nil {
glog.Warningf("flushFileMetadata %s: best-effort metadata apply failed: %v", fileFullPath, applyErr)
wfs.inodeToPath.InvalidateChildrenCache(util.FullPath(dir))
}
glog.V(3).Infof("flushed metadata for %s with %d chunks", fileFullPath, len(requestEntry.GetChunks()))
// Note: We do NOT clear dirtyMetadata here because:
// 1. There may still be dirty pages in the write buffer
// 2. The file may receive more writes before close
// 3. dirtyMetadata will be cleared on the final flush when the file is closed
return nil
}