Files
seaweedfs/weed/mount/chunk_proofs.go
T
394e9d247e mount: keep assignment proofs until the filer stores their chunks (#13186)
* 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>
2026-11-30 18:18:29 -08:00

272 lines
7.8 KiB
Go

package mount
import (
"context"
"fmt"
"sync"
"time"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
)
var (
// chunkProofLimit bounds the assignment proofs a mount keeps at once, a few
// hundred bytes each. Reaching it means that many uploaded chunks still
// wait for their entry to be stored.
chunkProofLimit = 1 << 16
// chunkProofWait is how long an upload waits for room to keep its proof
// before it fails. Tests shorten it.
chunkProofWait = time.Minute
// chunkProofExpiryGrace keeps a proof past its expiry for as long as a
// filer's clock leeway may still accept it.
chunkProofExpiryGrace = 5 * time.Minute
)
// chunkProofs keeps the assignment proofs that a filer returns with
// AssignVolume to a scoped token. Such a filer stores a chunk it does not
// already hold at that path only when the request carries the chunk's proof
// in chunk_auth, so every proof is kept from the upload until a filer has
// acknowledged an entry that names the chunk. A failed or timed out commit
// may or may not have been stored, so it releases nothing: the retry still
// carries the proof, and a proof for a chunk the filer already holds is
// ignored there.
//
// The store is bounded. Once it is full an upload waits, before it is
// assigned a file id, for commits to make room, and fails after
// chunkProofWait instead of evicting a proof a pending commit still needs.
// Only proofs past their expiry are dropped to make room: a filer refuses
// them anyway.
//
// A nil *chunkProofs keeps nothing and attaches nothing: a mount without a
// filer token is never given proofs, and its requests are left as they are.
type chunkProofs struct {
mu sync.Mutex
held map[string]chunkProof // by the file id a chunk names
reserved int // uploads under way that may add a proof
limit int
room chan struct{} // closed and replaced when room may have been made
}
type chunkProof struct {
auth string
expires time.Time // zero when the proof does not say
}
func newChunkProofs(limit int) *chunkProofs {
return &chunkProofs{held: make(map[string]chunkProof), limit: limit, room: make(chan struct{})}
}
// reserve makes room for the proofs of an upload of n file ids before it is
// assigned, waiting up to chunkProofWait for commits to release some.
func (p *chunkProofs) reserve(n int) error {
if p == nil {
return nil
}
if n > p.limit {
return fmt.Errorf("an upload of %d file ids needs more assignment proofs than the %d a mount keeps", n, p.limit)
}
deadline := time.Now().Add(chunkProofWait)
logged := false
p.mu.Lock()
defer p.mu.Unlock()
for len(p.held)+p.reserved+n > p.limit {
if p.dropExpiredLocked() {
continue
}
wait := time.Until(deadline)
if wait <= 0 {
return fmt.Errorf("%d uploaded chunks still wait for their entries to be stored: no room to keep another assignment proof", len(p.held))
}
if !logged {
logged = true
glog.V(0).Infof("%d uploaded chunks still wait for their entries to be stored: the next upload waits for a commit", len(p.held))
}
room := p.room
p.mu.Unlock()
timer := time.NewTimer(wait)
select {
case <-room:
case <-timer.C:
}
timer.Stop()
p.mu.Lock()
}
p.reserved += n
return nil
}
// keep ends the reservation of n file ids made for an upload that stored its
// data under fileId, and keeps the proof the filer returned for them. An
// empty proof keeps nothing: the filer did not ask for one.
func (p *chunkProofs) keep(fileId, auth string, n int) {
if p == nil {
return
}
covered := n
var expires time.Time
if claims, ok := security.AssignProofClaims(security.EncodedJwt(auth)); ok {
if claims.ExpiresAt != nil {
expires = claims.ExpiresAt.Time
}
// A proof covers fileId and fileId_1 up to its count.
if int(claims.Count) < covered {
covered = int(claims.Count)
}
}
p.mu.Lock()
defer p.mu.Unlock()
p.reserved -= n
if auth != "" {
for i := 0; i < covered; i++ {
fid := fileId
if i > 0 {
fid = fmt.Sprintf("%s_%d", fileId, i)
}
p.held[fid] = chunkProof{auth: auth, expires: expires}
}
}
p.signalLocked()
}
// unreserve ends the reservation of n file ids made for a failed upload.
func (p *chunkProofs) unreserve(n int) {
if p == nil {
return
}
p.mu.Lock()
defer p.mu.Unlock()
p.reserved -= n
p.signalLocked()
}
// attach adds to *auth the proof of each chunk the store holds one for, and
// reports whether there was any. It writes nothing once *auth carries them,
// so a request already handed to a send that is still in flight can be
// attached to again for its retry: the proofs of the chunks a request names
// are kept before the request is built.
func (p *chunkProofs) attach(chunks []*filer_pb.FileChunk, auth *map[string]string) (held bool) {
if p == nil || len(chunks) == 0 {
return false
}
p.mu.Lock()
defer p.mu.Unlock()
if len(p.held) == 0 {
return false
}
for _, chunk := range chunks {
fid := chunk.GetFileIdString()
proof, ok := p.held[fid]
if !ok {
continue
}
held = true
if current, ok := (*auth)[fid]; ok && current == proof.auth {
continue
}
if *auth == nil {
*auth = make(map[string]string)
}
(*auth)[fid] = proof.auth
}
return held
}
// release drops the proofs of chunks once a filer acknowledged an entry that
// names them: it holds the chunks now and asks for no proof again.
func (p *chunkProofs) release(chunks []*filer_pb.FileChunk) {
if p == nil {
return
}
p.mu.Lock()
defer p.mu.Unlock()
released := false
for _, chunk := range chunks {
fid := chunk.GetFileIdString()
if _, ok := p.held[fid]; ok {
delete(p.held, fid)
released = true
}
}
if released {
p.signalLocked()
}
}
// count reports how many file ids have a proof kept.
func (p *chunkProofs) count() int {
if p == nil {
return 0
}
p.mu.Lock()
defer p.mu.Unlock()
return len(p.held)
}
func (p *chunkProofs) dropExpiredLocked() (dropped bool) {
now := time.Now()
for fid, proof := range p.held {
if !proof.expires.IsZero() && now.After(proof.expires.Add(chunkProofExpiryGrace)) {
delete(p.held, fid)
dropped = true
}
}
return dropped
}
func (p *chunkProofs) signalLocked() {
close(p.room)
p.room = make(chan struct{})
}
// requestChunks returns the chunks a filer request stores and the map their
// proofs go in, or nil for a request that stores none.
func requestChunks(req any) ([]*filer_pb.FileChunk, *map[string]string) {
switch r := req.(type) {
case *filer_pb.CreateEntryRequest:
return r.GetEntry().GetChunks(), &r.ChunkAuth
case *filer_pb.UpdateEntryRequest:
return r.GetEntry().GetChunks(), &r.ChunkAuth
case *filer_pb.AppendToEntryRequest:
return r.GetChunks(), &r.ChunkAuth
}
return nil, nil
}
// stored reports whether reply acknowledges that the filer stored the
// request's entry. A create reports a refused condition in its reply.
func stored(reply any) bool {
if r, ok := reply.(*filer_pb.CreateEntryResponse); ok {
return r.GetError() == "" && r.GetErrorCode() == filer_pb.FilerError_OK
}
return true
}
// conn attaches the kept proofs to every unary create, update and append the
// mount sends through cc, on each attempt, and releases them once the filer
// acknowledged the request.
func (p *chunkProofs) conn(cc grpc.ClientConnInterface) grpc.ClientConnInterface {
if p == nil {
return cc
}
return &chunkProofConn{ClientConnInterface: cc, proofs: p}
}
type chunkProofConn struct {
grpc.ClientConnInterface
proofs *chunkProofs
}
func (c *chunkProofConn) Invoke(ctx context.Context, method string, args, reply any, opts ...grpc.CallOption) error {
chunks, auth := requestChunks(args)
held := auth != nil && c.proofs.attach(chunks, auth)
err := c.ClientConnInterface.Invoke(ctx, method, args, reply, opts...)
if err == nil && held && stored(reply) {
c.proofs.release(chunks)
}
return err
}