mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-09-14 02:20:41 +02:00
* feat(mount): pre-allocate file IDs in pool for writeback cache mode When writeback caching is enabled, chunk uploads no longer block on a per-chunk AssignVolume RPC. Instead, a FileIdPool pre-allocates file IDs in batches using a single AssignVolume(Count=N, ExpectedDataSize=ChunkSize) call and hands them out instantly to upload workers. Pool size is 2x ConcurrentWriters, refilled in background when it drops below ConcurrentWriters. Entries expire after 25s to respect JWT TTL. Sequential needle keys are generated from the base file ID returned by the master, so one Assign RPC produces N usable IDs. This cuts per-chunk upload latency from 2 RTTs (assign + upload) to 1 RTT (upload only), with the assign cost amortized across the batch. * test: add benchmarks for file ID pool vs direct assign Benchmarks measure: - Pool Get vs Direct AssignVolume at various simulated latencies - Batch assign scaling (Count=1 through Count=32) - Concurrent pool access with 1-64 workers Results on Apple M4: - Pool Get: constant ~3ns regardless of assign latency - Batch=16: 15.7x more IDs/sec than individual assigns - 64 concurrent workers: 19M IDs/sec throughput * fix(mount): address review feedback on file ID pool 1. Fix race condition in Get(): use sync.Cond so callers wait for an in-flight refill instead of returning an error when the pool is empty. 2. Match default pool size to async flush worker count (128, not 16) when ConcurrentWriters is unset. 3. Add logging to UploadWithAssignFunc for consistency with UploadWithRetry. 4. Document that pooled assigns omit the Path field, bypassing path-based storage rules (filer.conf). This is an intentional tradeoff for writeback cache performance. 5. Fix flaky expiry test: widen time margin from 50ms to 1s. 6. Add TestFileIdPoolGetWaitsForRefill to verify concurrent waiters. * fix(mount): use individual Count=1 assigns to get per-fid JWTs The master generates one JWT per AssignResponse, bound to the base file ID (master_grpc_server_assign.go:158). The volume server validates that the JWT's Fid matches the upload exactly (volume_server_handlers.go:367). Using Count=N and deriving sequential IDs would fail this check. Switch to individual Count=1 RPCs over a single gRPC connection. This still amortizes connection overhead while getting a correct per-fid JWT for each entry. Partial batches are accepted if some requests fail. Remove unused needle import now that sequential ID generation is gone. * fix(mount): separate pprof from FUSE protocol debug logging The -debug flag was enabling both the pprof HTTP server and the noisy go-fuse protocol logging (rx/tx lines for every FUSE operation). This makes profiling impractical as the log output dominates. Split into two flags: - -debug: enables pprof HTTP server only (for profiling) - -debug.fuse: enables raw FUSE protocol request/response logging * perf(mount): replace LevelDB read+write with in-memory overlay for dir mtime Profile showed TouchDirMtimeCtime at 0.22s — every create/rename/unlink in a directory did a LevelDB FindEntry (read) + UpdateEntry (write) just to bump the parent dir's mtime/ctime. Replace with an in-memory map (same pattern as existing atime overlay): - touchDirMtimeCtimeLocal now stores inode→timestamp in dirMtimeMap - applyInMemoryDirMtime overlays onto GetAttr/Lookup output - No LevelDB I/O on the mutation hot path The overlay only advances timestamps forward (max of stored vs overlay), so stale entries are harmless. Map is bounded at 8192 entries. * perf(mount): skip self-originated metadata subscription events in writeback mode With writeback caching, this mount is the single writer. All local mutations are already applied to the local meta cache (via applyLocalMetadataEvent or direct InsertEntry). The filer subscription then delivers the same event back, causing redundant work: proto.Clone, enqueue to apply loop, dedup ring check, and sometimes redundant LevelDB writes when the dedup ring misses (deferred creates). Check EventNotification.Signatures against selfSignature and skip events that originated from this mount. This eliminates the redundant processing for every self-originated mutation. * perf(mount): increase kernel FUSE cache TTL in writeback cache mode With writeback caching, this mount is the single writer — the local meta cache is authoritative. Increase EntryValid and AttrValid from 1s to 10s so the kernel doesn't re-issue Lookup/GetAttr for every path component and stat call. This reduces FUSE /dev/fuse round-trips which dominate the profile at 38% of CPU (syscall.rawsyscalln). Each saved round-trip eliminates a kernel→userspace→kernel transition. Normal (non-writeback) mode retains the 1s TTL for multi-mount consistency.
182 lines
5.2 KiB
Go
182 lines
5.2 KiB
Go
package mount
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
)
|
|
|
|
// FileIdEntry holds a pre-allocated file ID from the filer/master, ready for
|
|
// immediate use by an upload worker without an AssignVolume round-trip.
|
|
type FileIdEntry struct {
|
|
FileId string
|
|
Host string // volume server address (already adjusted for access mode)
|
|
Auth security.EncodedJwt
|
|
Time time.Time
|
|
}
|
|
|
|
// FileIdPool pre-allocates file IDs in batches so that chunk uploads can grab
|
|
// one instantly instead of blocking on an AssignVolume RPC per chunk.
|
|
//
|
|
// The pool is refilled in the background when it drops below a low-water mark.
|
|
// All IDs are allocated with the mount's global (replication, collection, ttl,
|
|
// diskType, dataCenter) parameters. Path-based storage rules (filer.conf) are
|
|
// NOT applied to pooled IDs since the pool allocates ahead of any specific file
|
|
// path. This is an intentional tradeoff for writeback cache performance.
|
|
type FileIdPool struct {
|
|
wfs *WFS
|
|
|
|
mu sync.Mutex
|
|
cond *sync.Cond
|
|
entries []FileIdEntry // available pre-allocated IDs
|
|
filling bool // true when a background refill is in progress
|
|
|
|
poolSize int // target pool capacity
|
|
batchSize int // how many IDs to request per Assign RPC
|
|
lowWater int // refill trigger threshold
|
|
maxAge time.Duration
|
|
}
|
|
|
|
func NewFileIdPool(wfs *WFS) *FileIdPool {
|
|
concurrency := wfs.option.ConcurrentWriters
|
|
if concurrency <= 0 {
|
|
concurrency = 128 // match default async flush worker count
|
|
}
|
|
pool := &FileIdPool{
|
|
wfs: wfs,
|
|
poolSize: concurrency * 2,
|
|
batchSize: concurrency,
|
|
lowWater: concurrency,
|
|
maxAge: 25 * time.Second, // conservative; JWT TTL is typically 30s+
|
|
}
|
|
pool.cond = sync.NewCond(&pool.mu)
|
|
return pool
|
|
}
|
|
|
|
// Get returns a pre-allocated file ID entry. If the pool is empty and a refill
|
|
// is in progress, callers wait for it to complete rather than failing. Returns
|
|
// an error only if the Assign RPC fails.
|
|
func (p *FileIdPool) Get() (FileIdEntry, error) {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
|
|
for {
|
|
p.evictExpired()
|
|
|
|
if len(p.entries) > 0 {
|
|
entry := p.entries[0]
|
|
p.entries = p.entries[1:]
|
|
if len(p.entries) < p.lowWater && !p.filling {
|
|
p.filling = true
|
|
go p.doRefill()
|
|
}
|
|
return entry, nil
|
|
}
|
|
|
|
// Pool empty.
|
|
if p.filling {
|
|
// Wait for the in-flight refill to complete.
|
|
p.cond.Wait()
|
|
continue
|
|
}
|
|
|
|
// No refill in progress — start one synchronously.
|
|
p.filling = true
|
|
p.mu.Unlock()
|
|
entries, err := p.assignBatch(p.batchSize)
|
|
p.mu.Lock()
|
|
p.filling = false
|
|
p.cond.Broadcast()
|
|
|
|
if err != nil {
|
|
return FileIdEntry{}, fmt.Errorf("fileIdPool: %w", err)
|
|
}
|
|
p.entries = append(p.entries, entries...)
|
|
// Loop back to pop from entries.
|
|
}
|
|
}
|
|
|
|
func (p *FileIdPool) evictExpired() {
|
|
cutoff := time.Now().Add(-p.maxAge)
|
|
i := 0
|
|
for i < len(p.entries) && p.entries[i].Time.Before(cutoff) {
|
|
i++
|
|
}
|
|
if i > 0 {
|
|
p.entries = p.entries[i:]
|
|
}
|
|
}
|
|
|
|
// doRefill runs in a background goroutine to refill the pool.
|
|
func (p *FileIdPool) doRefill() {
|
|
entries, err := p.assignBatch(p.batchSize)
|
|
if err != nil {
|
|
glog.V(1).Infof("fileIdPool refill: %v", err)
|
|
}
|
|
|
|
p.mu.Lock()
|
|
if err == nil {
|
|
p.entries = append(p.entries, entries...)
|
|
}
|
|
p.filling = false
|
|
p.cond.Broadcast()
|
|
p.mu.Unlock()
|
|
}
|
|
|
|
// assignBatch requests `count` file IDs from the filer using individual
|
|
// Count=1 RPCs over a single gRPC connection. Each response includes a
|
|
// per-fid JWT, so uploads work correctly when JWT security is enabled.
|
|
//
|
|
// We use individual requests instead of Count=N because the master generates
|
|
// one JWT for the base file ID only (master_grpc_server_assign.go:158), and
|
|
// the volume server validates that the JWT's Fid matches the upload's file ID
|
|
// exactly (volume_server_handlers.go:367). Sequential IDs derived from a
|
|
// Count=N response would fail this check.
|
|
//
|
|
// Note: the AssignVolumeRequest intentionally omits the Path field. Pooled IDs
|
|
// use the mount's global storage parameters, not per-path rules from filer.conf
|
|
// (detectStorageOption / MatchStorageRule). This is a writeback cache tradeoff.
|
|
func (p *FileIdPool) assignBatch(count int) ([]FileIdEntry, error) {
|
|
var entries []FileIdEntry
|
|
err := p.wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
now := time.Now()
|
|
req := &filer_pb.AssignVolumeRequest{
|
|
Count: 1,
|
|
Replication: p.wfs.option.Replication,
|
|
Collection: p.wfs.option.Collection,
|
|
TtlSec: p.wfs.option.TtlSec,
|
|
DiskType: string(p.wfs.option.DiskType),
|
|
DataCenter: p.wfs.option.DataCenter,
|
|
ExpectedDataSize: uint64(p.wfs.option.ChunkSizeLimit),
|
|
}
|
|
for i := 0; i < count; i++ {
|
|
resp, assignErr := client.AssignVolume(context.Background(), req)
|
|
if assignErr != nil {
|
|
if len(entries) > 0 {
|
|
break // partial batch is fine
|
|
}
|
|
return assignErr
|
|
}
|
|
if resp.Error != "" {
|
|
if len(entries) > 0 {
|
|
break
|
|
}
|
|
return fmt.Errorf("assign: %s", resp.Error)
|
|
}
|
|
entries = append(entries, FileIdEntry{
|
|
FileId: resp.FileId,
|
|
Host: p.wfs.AdjustedUrl(resp.Location),
|
|
Auth: security.EncodedJwt(resp.Auth),
|
|
Time: now,
|
|
})
|
|
}
|
|
return nil
|
|
})
|
|
return entries, err
|
|
}
|