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 }