mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
* operation: return the assignment proof of an upload A filer serving a scoped token returns an assignment proof with AssignVolume and stores a new chunk in an entry only when the request presents that proof in chunk_auth. UploadWithRetry dropped it, so a client had no way to commit the chunks it uploaded. UploadResult.AssignAuth now carries the proof of the assignment the data was finally stored under. A proof from an assignment the upload abandoned after a failed attempt is never returned. The field is not serialized and stays empty when the filer sends none, so existing callers are unchanged. * mount: keep assignment proofs until the filer stores their chunks A mount with a scoped filer token was refused whenever it wrote new chunks: the filer asks for the assignment proof of every chunk the stored entry does not hold, and the mount never kept it. The mount now keeps the proof of every chunk it uploads and attaches the proofs of the chunks a request names to each create, update and append it sends, over the mutation stream and over unary calls, on every attempt. A proof is released only once a filer acknowledged an entry that names the chunk, or a manifest that holds it. A failed, refused or timed out commit releases nothing, since it may have been stored: the retry still carries the proof, and a filer ignores proofs for chunks it holds. Proofs are stateless, so a commit retried on another filer of the cluster is accepted there. The store is bounded. When it is full an upload waits for commits to make room before it is assigned a file id, and fails after a minute instead of evicting a proof a pending commit still needs. Only proofs well past their expiry, which a filer refuses anyway, are dropped to make room. Without a filer token the mount keeps no store: its requests and chunk lists are as before. A token without path grants is given no proofs, so nothing is attached either. * mount: keep chunk lists flat with a filer token file A filer serving a scoped token stores no new chunk in an entry that holds manifests, so once a mount folded a file's small chunks into a manifest, every later write to that file was refused. A mount with a filer token now keeps chunk lists flat; mounts without one fold as before. * mount: test the unscoped-token path with a signed token GenJwtForFilerScope returns an empty token when it is given no path grants, so both cases of TestUnscopedMountRequestsCarryNoProofs ran a tokenless mount. Sign an unscoped filer token instead and check that it is not empty, so the test covers a mount holding a token the filer issues no proofs for. * mount: fold chunk lists unless the filer scopes the mount's token A mount with -filer.tokenFile kept every chunk list flat, also when the token is an unscoped one the filer issues no proofs for. Such a mount stopped folding chunks into manifests, so its small-chunk runs were never folded and, on FoundationDB, a file past about 1000 chunks no longer fit its entry. Keep lists flat only while the current token has path grants or a method list, which the filer scopes; fold as before otherwise. 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>
234 lines
8.3 KiB
Go
234 lines
8.3 KiB
Go
package mount
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"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 locks below serialize within this mount: like a
|
|
// close, the publication waits for a rename of the file in flight and then
|
|
// writes the name the rename left.
|
|
func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
|
|
dir, name := fh.FullPath().DirAndName()
|
|
fileFullPath, dir, name, release, err := wfs.lockFlushTarget(fh, "flushMetadata", dir, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer release()
|
|
|
|
// Double-check dirty flag under lock
|
|
if !fh.dirtyMetadata {
|
|
return nil
|
|
}
|
|
// Unlink marks under this lock; publishing would recreate the name.
|
|
if fh.isDeleted {
|
|
return nil
|
|
}
|
|
|
|
glog.V(4).Infof("flushFileMetadata %s fh %d", fileFullPath, fh.fh)
|
|
|
|
if fh.GetEntry() == nil {
|
|
return nil
|
|
}
|
|
if fh.linkRefresh != nil {
|
|
if err := wfs.adoptStoredLink(context.Background(), fh, fileFullPath, fh.linkRefresh); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// 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, covered, err := filer.CompactFileChunks(context.Background(), wfs.LookupFn(), nonManifestChunks)
|
|
if err != nil {
|
|
return fmt.Errorf("compact chunks of %s: %w", fileFullPath, err)
|
|
}
|
|
|
|
// Try to create manifest chunks for large files
|
|
// no chunk deleter here: a failed fold reports the blobs it saved
|
|
unfolded := compactedChunks
|
|
compactedChunks, manifestErr := wfs.maybeManifestize(fileFullPath, compactedChunks)
|
|
if manifestErr != nil {
|
|
glog.V(0).Infof("flushFileMetadata MaybeManifestize: %v", manifestErr)
|
|
}
|
|
fold := newChunkFold(unfolded, compactedChunks)
|
|
|
|
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)
|
|
requestEntry.Chunks = append(requestEntry.Chunks, fh.unpublishedChunks(covered, requestEntry.Chunks)...)
|
|
wfs.mapPbIdFromLocalToFiler(request.Entry)
|
|
|
|
resp, merged, err := wfs.createContentEntry(context.Background(), fh, request, baseSnapshot, true, &contentPublication{}, fold)
|
|
if err != nil {
|
|
fold.revert(fh)
|
|
return err
|
|
}
|
|
if merged != nil {
|
|
// Install what the filer stored, which becomes the base: it may have
|
|
// folded the merged chunks the request sent unfolded.
|
|
merged = wfs.ackedBase(resp, merged)
|
|
fh.rebaseEntry(merged, requestEntry)
|
|
baseSnapshot = merged
|
|
} else {
|
|
fh.installStoredChunks(wfs.ackedBase(resp, baseSnapshot), baseSnapshot)
|
|
}
|
|
|
|
event := resp.GetMetadataEvent()
|
|
if event == nil {
|
|
event = metadataUpdateEvent(string(dir), request.Entry)
|
|
if event != nil {
|
|
event.TsNs = ackVersionTsNs(resp)
|
|
}
|
|
}
|
|
fh.setAuthoritativeBase(wfs.ackedBase(resp, 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
|
|
}
|