mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +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>
854 lines
28 KiB
Go
854 lines
28 KiB
Go
package mount
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"sync"
|
|
"sync/atomic"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
grpcMetadata "google.golang.org/grpc/metadata"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// streamMutateError is returned when the server reports a structured errno.
|
|
// It is also used by helpers to distinguish application errors (don't retry
|
|
// on unary fallback) from transport errors (do retry).
|
|
type streamMutateError struct {
|
|
msg string
|
|
errno syscall.Errno
|
|
}
|
|
|
|
func (e *streamMutateError) Error() string { return e.msg }
|
|
func (e *streamMutateError) Errno() syscall.Errno { return e.errno }
|
|
|
|
// hasCreateResponse reports whether resp carries a nested CreateEntryResponse to
|
|
// unwrap. A create wrapper without one has no structured code to recover, and
|
|
// CreateEntry would dereference the nil.
|
|
func hasCreateResponse(resp *filer_pb.StreamMutateEntryResponse) bool {
|
|
cr, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_CreateResponse)
|
|
return ok && cr.CreateResponse != nil
|
|
}
|
|
|
|
// ErrStreamTransport is a sentinel error type for transport-level stream
|
|
// failures (disconnects, send errors). Callers use errors.Is to decide
|
|
// whether to fall back to unary RPCs.
|
|
var ErrStreamTransport = errors.New("stream transport error")
|
|
|
|
// streamMutateMux multiplexes filer mutation RPCs (create, update, delete,
|
|
// rename) over a single bidirectional gRPC stream. Multiple goroutines can
|
|
// call the mutation methods concurrently; requests are serialized through
|
|
// sendCh and responses are dispatched back via per-request channels.
|
|
type streamMutateMux struct {
|
|
wfs *WFS
|
|
|
|
mu sync.Mutex // protects the fields below, up to draining
|
|
stream filer_pb.SeaweedFiler_StreamMutateEntryClient
|
|
cancel context.CancelFunc
|
|
grpcConn *grpc.ClientConn // dedicated connection, closed on stream teardown
|
|
filerIdx int32 // FilerAddresses index the current stream dialed
|
|
closed bool
|
|
disabled bool // permanently disabled if filer doesn't support the RPC
|
|
stopSend chan struct{} // closed to signal the current sendLoop to exit
|
|
sendDone chan struct{} // closed when the current sendLoop has exited
|
|
generation uint64 // incremented each time a new stream is created
|
|
|
|
// A stream keeps the filer token it opened with. token and expiresAt
|
|
// (zero when unknown) describe it; a replaced or expiring token retires
|
|
// the stream before a successor opens (see retireLocked). active counts
|
|
// requests admitted to the current generation and not yet released;
|
|
// idle is closed when it reaches zero during a retirement, and draining
|
|
// is non-nil while one runs. retireCancel cancels the retiring stream,
|
|
// for Close and for a waiter that gives up on it.
|
|
token security.EncodedJwt
|
|
expiresAt time.Time
|
|
active int
|
|
idle chan struct{}
|
|
draining chan struct{}
|
|
retireCancel context.CancelFunc
|
|
received atomic.Uint64 // responses received, on any generation
|
|
|
|
nextID atomic.Uint64
|
|
|
|
// pending maps request_id → response channel. The recvLoop dispatches
|
|
// each response to the correct waiter. For rename (multi-response),
|
|
// the channel receives multiple messages until is_last=true.
|
|
pending sync.Map // map[uint64]chan *filer_pb.StreamMutateEntryResponse
|
|
|
|
sendCh chan *streamMutateReq
|
|
recvDone chan struct{} // closed when recvLoop exits
|
|
}
|
|
|
|
type streamMutateReq struct {
|
|
req *filer_pb.StreamMutateEntryRequest
|
|
errCh chan error // send error feedback
|
|
gen uint64 // stream generation this request targets
|
|
}
|
|
|
|
func newStreamMutateMux(wfs *WFS) *streamMutateMux {
|
|
return &streamMutateMux{
|
|
wfs: wfs,
|
|
sendCh: make(chan *streamMutateReq, 512),
|
|
}
|
|
}
|
|
|
|
// CreateEntry sends a CreateEntryRequest over the stream and waits for the response.
|
|
// The request carries the assignment proofs of the new chunks it stores,
|
|
// released once the filer acknowledged it.
|
|
func (m *streamMutateMux) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
|
proofs := m.wfs.chunkProofs
|
|
held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth)
|
|
resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{
|
|
Request: &filer_pb.StreamMutateEntryRequest_CreateRequest{CreateRequest: req},
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cr, err := createEntryFromResponse(resp, req)
|
|
if err == nil && held {
|
|
proofs.release(req.GetEntry().GetChunks())
|
|
}
|
|
return cr, err
|
|
}
|
|
|
|
// createEntryFromResponse unwraps a create's nested response, mapping its
|
|
// structured code back to the sentinel callers match on (same logic as
|
|
// CreateEntryWithResponse).
|
|
func createEntryFromResponse(resp *filer_pb.StreamMutateEntryResponse, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
|
r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_CreateResponse)
|
|
if !ok {
|
|
return nil, fmt.Errorf("unexpected response type %T", resp.Response)
|
|
}
|
|
cr := r.CreateResponse
|
|
if cr == nil {
|
|
return nil, &streamMutateError{msg: "create response missing", errno: syscall.EIO}
|
|
}
|
|
if cr.ErrorCode != filer_pb.FilerError_OK {
|
|
if sentinel := filer_pb.FilerErrorToSentinel(cr.ErrorCode); sentinel != nil {
|
|
return nil, fmt.Errorf("CreateEntry %s/%s: %w", req.Directory, req.Entry.Name, sentinel)
|
|
}
|
|
return nil, &streamMutateError{msg: cr.Error, errno: syscall.EIO}
|
|
}
|
|
if cr.Error != "" {
|
|
// An older filer sends a read-only verdict as bare text, without the code.
|
|
if readOnly := filer_pb.LegacyReadOnlyError(cr.Error); readOnly != nil {
|
|
return nil, fmt.Errorf("CreateEntry %s/%s: %w", req.Directory, req.Entry.Name, readOnly)
|
|
}
|
|
return nil, &streamMutateError{msg: cr.Error, errno: syscall.EIO}
|
|
}
|
|
if resp.Error != "" {
|
|
// The nested response explained nothing, so the top-level failure is all
|
|
// there is: reporting success here would lose the create's error entirely.
|
|
return nil, &streamMutateError{msg: resp.Error, errno: syscall.Errno(resp.Errno)}
|
|
}
|
|
return cr, nil
|
|
}
|
|
|
|
// UpdateEntry sends an UpdateEntryRequest over the stream and waits for the response.
|
|
// Proofs are attached and released as for CreateEntry.
|
|
func (m *streamMutateMux) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
|
|
proofs := m.wfs.chunkProofs
|
|
held := proofs.attach(req.GetEntry().GetChunks(), &req.ChunkAuth)
|
|
resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{
|
|
Request: &filer_pb.StreamMutateEntryRequest_UpdateRequest{UpdateRequest: req},
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_UpdateResponse); ok {
|
|
if held {
|
|
proofs.release(req.GetEntry().GetChunks())
|
|
}
|
|
return r.UpdateResponse, nil
|
|
}
|
|
return nil, fmt.Errorf("unexpected response type %T", resp.Response)
|
|
}
|
|
|
|
// DeleteEntry sends a DeleteEntryRequest over the stream and waits for the response.
|
|
func (m *streamMutateMux) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) {
|
|
resp, err := m.doUnary(ctx, &filer_pb.StreamMutateEntryRequest{
|
|
Request: &filer_pb.StreamMutateEntryRequest_DeleteRequest{DeleteRequest: req},
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_DeleteResponse)
|
|
if !ok {
|
|
return nil, fmt.Errorf("unexpected response type %T", resp.Response)
|
|
}
|
|
// Check nested error field.
|
|
if r.DeleteResponse.Error != "" {
|
|
return nil, &streamMutateError{msg: r.DeleteResponse.Error, errno: syscall.EIO}
|
|
}
|
|
return r.DeleteResponse, nil
|
|
}
|
|
|
|
// Rename sends a StreamRenameEntryRequest over the stream and collects all
|
|
// response events until is_last=true. The callback is invoked for each
|
|
// intermediate rename event (same as the current StreamRenameEntry recv loop).
|
|
func (m *streamMutateMux) Rename(ctx context.Context, req *filer_pb.StreamRenameEntryRequest, onEvent func(*filer_pb.StreamRenameEntryResponse) error) error {
|
|
gen, expiresAt, err := m.ensureStream(ctx)
|
|
if err != nil {
|
|
if ctx.Err() != nil && errors.Is(err, ctx.Err()) {
|
|
return err
|
|
}
|
|
return fmt.Errorf("%w: %v", ErrStreamTransport, err)
|
|
}
|
|
defer m.release(gen)
|
|
|
|
id := m.nextID.Add(1)
|
|
ch := make(chan *filer_pb.StreamMutateEntryResponse, 64)
|
|
m.pending.Store(id, ch)
|
|
defer m.pending.Delete(id)
|
|
|
|
sendReq := &streamMutateReq{
|
|
req: &filer_pb.StreamMutateEntryRequest{
|
|
RequestId: id,
|
|
Request: &filer_pb.StreamMutateEntryRequest_RenameRequest{RenameRequest: req},
|
|
},
|
|
errCh: make(chan error, 1),
|
|
gen: gen,
|
|
}
|
|
select {
|
|
case m.sendCh <- sendReq:
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
sendTimer := time.NewTimer(m.wfs.filerRPCWait())
|
|
select {
|
|
case err := <-sendReq.errCh:
|
|
sendTimer.Stop()
|
|
if err != nil {
|
|
return fmt.Errorf("rename send: %w: %v", ErrStreamTransport, err)
|
|
}
|
|
case <-sendTimer.C:
|
|
m.teardownStream(gen)
|
|
return fmt.Errorf("rename send: %w: timed out", ErrStreamTransport)
|
|
case <-ctx.Done():
|
|
sendTimer.Stop()
|
|
return ctx.Err()
|
|
}
|
|
|
|
// Collect rename events until is_last=true. The timer bounds silence
|
|
// between events, not the whole rename.
|
|
respTimer := time.NewTimer(m.wfs.filerRPCWait())
|
|
defer respTimer.Stop()
|
|
for {
|
|
select {
|
|
case resp, ok := <-ch:
|
|
if !ok {
|
|
return m.lostReply(expiresAt, fmt.Errorf("rename recv: %w: stream closed", ErrStreamTransport))
|
|
}
|
|
// Applying an event can legitimately outlast the silence bound —
|
|
// a directory rename migrates an open child's DLM lock under
|
|
// another writer. The timer bounds wire silence only, so stop it
|
|
// for the local work and re-arm it before the next wait.
|
|
if !respTimer.Stop() {
|
|
select {
|
|
case <-respTimer.C:
|
|
default:
|
|
}
|
|
}
|
|
if r, ok := resp.Response.(*filer_pb.StreamMutateEntryResponse_RenameResponse); ok {
|
|
if r.RenameResponse != nil && r.RenameResponse.EventNotification != nil {
|
|
if err := onEvent(r.RenameResponse); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
if resp.IsLast {
|
|
if resp.Error != "" {
|
|
return &streamMutateError{
|
|
msg: resp.Error,
|
|
errno: syscall.Errno(resp.Errno),
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
respTimer.Reset(m.wfs.filerRPCWait())
|
|
case <-respTimer.C:
|
|
m.teardownStream(gen)
|
|
return m.lostReply(expiresAt, fmt.Errorf("rename recv: %w: timed out", ErrStreamTransport))
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
}
|
|
|
|
// doUnary sends a single-response request and waits for the reply.
|
|
func (m *streamMutateMux) doUnary(ctx context.Context, req *filer_pb.StreamMutateEntryRequest) (*filer_pb.StreamMutateEntryResponse, error) {
|
|
gen, expiresAt, err := m.ensureStream(ctx)
|
|
if err != nil {
|
|
if ctx.Err() != nil && errors.Is(err, ctx.Err()) {
|
|
return nil, err
|
|
}
|
|
return nil, fmt.Errorf("%w: %v", ErrStreamTransport, err)
|
|
}
|
|
defer m.release(gen)
|
|
|
|
id := m.nextID.Add(1)
|
|
req.RequestId = id
|
|
ch := make(chan *filer_pb.StreamMutateEntryResponse, 1)
|
|
m.pending.Store(id, ch)
|
|
defer m.pending.Delete(id)
|
|
|
|
sendReq := &streamMutateReq{
|
|
req: req,
|
|
errCh: make(chan error, 1),
|
|
gen: gen,
|
|
}
|
|
select {
|
|
case m.sendCh <- sendReq:
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
}
|
|
// Most callers pass context.Background(), so a stream blocked on Send or
|
|
// Recv over a dead transport would never surface an error here. Bound the
|
|
// wait and tear the stream down so the call can fall back to a unary RPC
|
|
// on another filer.
|
|
sendTimer := time.NewTimer(m.wfs.filerRPCWait())
|
|
select {
|
|
case err := <-sendReq.errCh:
|
|
sendTimer.Stop()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%w: %v", ErrStreamTransport, err)
|
|
}
|
|
case <-sendTimer.C:
|
|
m.teardownStream(gen)
|
|
return nil, fmt.Errorf("%w: send timed out", ErrStreamTransport)
|
|
case <-ctx.Done():
|
|
sendTimer.Stop()
|
|
return nil, ctx.Err()
|
|
}
|
|
|
|
respTimer := time.NewTimer(m.wfs.filerRPCWait())
|
|
select {
|
|
case resp, ok := <-ch:
|
|
respTimer.Stop()
|
|
if !ok {
|
|
return nil, m.lostReply(expiresAt, fmt.Errorf("%w: stream closed", ErrStreamTransport))
|
|
}
|
|
// A failed create still carries a structured error code in its nested
|
|
// CreateEntryResponse, so hand that back for CreateEntry to unwrap and
|
|
// the sentinel (entry-already-exists → EEXIST) survives instead of
|
|
// collapsing into the top-level generic errno.
|
|
if resp.Error != "" && !hasCreateResponse(resp) {
|
|
return nil, &streamMutateError{
|
|
msg: resp.Error,
|
|
errno: syscall.Errno(resp.Errno),
|
|
}
|
|
}
|
|
return resp, nil
|
|
case <-respTimer.C:
|
|
m.teardownStream(gen)
|
|
return nil, m.lostReply(expiresAt, fmt.Errorf("%w: response timed out", ErrStreamTransport))
|
|
case <-ctx.Done():
|
|
respTimer.Stop()
|
|
return nil, ctx.Err()
|
|
}
|
|
}
|
|
|
|
// ensureStream opens the bidi stream if not already open and admits one
|
|
// request to it. It returns the stream generation so callers can tag outgoing
|
|
// requests, and when the stream's token expires (zero when unknown); the
|
|
// caller releases its admission with release(gen) once it stops waiting for
|
|
// that request's replies. A caller whose ctx ends while a retiring stream
|
|
// drains returns ctx's error unadmitted; the retirement carries on.
|
|
func (m *streamMutateMux) ensureStream(ctx context.Context) (uint64, time.Time, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
for {
|
|
if m.closed {
|
|
return 0, time.Time{}, fmt.Errorf("stream mux is closed")
|
|
}
|
|
if m.disabled {
|
|
return 0, time.Time{}, fmt.Errorf("StreamMutateEntry not supported by filer")
|
|
}
|
|
// A retiring stream admits nothing; its successor opens after it.
|
|
if draining := m.draining; draining != nil {
|
|
m.mu.Unlock()
|
|
select {
|
|
case <-draining:
|
|
case <-ctx.Done():
|
|
m.mu.Lock()
|
|
return 0, time.Time{}, ctx.Err()
|
|
}
|
|
m.mu.Lock()
|
|
continue
|
|
}
|
|
if m.stream != nil {
|
|
retire, err := m.mustRetireLocked()
|
|
if err != nil {
|
|
return 0, time.Time{}, err
|
|
}
|
|
if !retire {
|
|
m.active++
|
|
return m.generation, m.expiresAt, nil
|
|
}
|
|
m.retireLocked()
|
|
continue
|
|
}
|
|
// Wait for prior generation's recvLoop to fully tear down before
|
|
// opening a new stream. This guarantees all pending waiters from the
|
|
// old stream have been failed before we create a new generation.
|
|
if done := m.recvDone; done != nil {
|
|
select {
|
|
case <-done:
|
|
default:
|
|
m.mu.Unlock()
|
|
<-done
|
|
m.mu.Lock()
|
|
continue
|
|
}
|
|
}
|
|
// A new stream is admitted through the checks above like an open one:
|
|
// the token file may have been replaced, or the token neared expiry,
|
|
// while it opened.
|
|
if err := m.openLocked(); err != nil {
|
|
return 0, time.Time{}, err
|
|
}
|
|
}
|
|
}
|
|
|
|
// openLocked opens a stream with the current filer token and starts its loops,
|
|
// with no request admitted yet. Called with mu held.
|
|
func (m *streamMutateMux) openLocked() error {
|
|
token, expiresAt, err := m.streamToken()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var stream filer_pb.SeaweedFiler_StreamMutateEntryClient
|
|
err = m.openStream(&stream, token)
|
|
if err != nil {
|
|
if s, ok := status.FromError(err); ok && s.Code() == codes.Unimplemented {
|
|
m.disabled = true
|
|
glog.V(0).Infof("filer does not support StreamMutateEntry, falling back to unary RPCs")
|
|
}
|
|
return err
|
|
}
|
|
m.startLocked(stream, token, expiresAt)
|
|
return nil
|
|
}
|
|
|
|
// startLocked makes stream, opened with token, the current generation and
|
|
// starts its loops. Called with mu held.
|
|
func (m *streamMutateMux) startLocked(stream filer_pb.SeaweedFiler_StreamMutateEntryClient, token security.EncodedJwt, expiresAt time.Time) {
|
|
m.generation++
|
|
m.stream = stream
|
|
m.token, m.expiresAt = token, expiresAt
|
|
m.active = 0
|
|
m.stopSend = make(chan struct{})
|
|
m.sendDone = make(chan struct{})
|
|
recvDone := make(chan struct{})
|
|
m.recvDone = recvDone
|
|
go m.sendLoop(stream, m.stopSend, m.sendDone, m.generation, expiresAt)
|
|
go m.recvLoop(stream, m.generation, recvDone)
|
|
}
|
|
|
|
// release ends one request's admission to generation gen.
|
|
func (m *streamMutateMux) release(gen uint64) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if gen != m.generation || m.active == 0 {
|
|
return
|
|
}
|
|
m.active--
|
|
if m.active == 0 && m.idle != nil {
|
|
close(m.idle)
|
|
m.idle = nil
|
|
}
|
|
}
|
|
|
|
// streamToken resolves the filer token a new stream opens with. The stream
|
|
// keeps it for its whole life, so a token that would expire before a request
|
|
// sent now could be answered is refused: the caller's unary fallback, which
|
|
// the filer checks when each call starts, is safe where the stream is not.
|
|
func (m *streamMutateMux) streamToken() (security.EncodedJwt, time.Time, error) {
|
|
source := m.wfs.option.FilerTokenSource
|
|
if source == nil {
|
|
return "", time.Time{}, nil
|
|
}
|
|
token, err := source(context.Background())
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
expiresAt := filerTokenExpiry(token)
|
|
if m.tokenExpiring(expiresAt) {
|
|
return "", time.Time{}, fmt.Errorf("filer token expires within %v", m.wfs.filerRPCWait())
|
|
}
|
|
return token, expiresAt, nil
|
|
}
|
|
|
|
// tokenExpiring reports whether a stream token expiring at expiresAt (zero
|
|
// when unknown) has filerRPCWait or less left, so that a reply to a request
|
|
// sent now might come after the filer stops answering on that stream.
|
|
func (m *streamMutateMux) tokenExpiring(expiresAt time.Time) bool {
|
|
return !expiresAt.IsZero() && !time.Now().Add(m.wfs.filerRPCWait()).Before(expiresAt)
|
|
}
|
|
|
|
// lostReply returns err, the transport error for a sent request whose reply
|
|
// never came, unless the stream's token is about to expire or has expired.
|
|
// The filer may then have applied the request and refused to send its reply,
|
|
// so the outcome is unknown: the request is reported as failed with EIO,
|
|
// which callers do not resend over the unary path.
|
|
func (m *streamMutateMux) lostReply(expiresAt time.Time, err error) error {
|
|
if !m.tokenExpiring(expiresAt) {
|
|
return err
|
|
}
|
|
return &streamMutateError{
|
|
msg: fmt.Sprintf("%v near filer token expiry; the filer may have applied it", err),
|
|
errno: syscall.EIO,
|
|
}
|
|
}
|
|
|
|
// mustRetireLocked reports whether the open stream must stop admitting
|
|
// requests: the token source now holds another token, or the stream's own
|
|
// token would expire before a request sent now could be answered. The filer
|
|
// refuses to send on a scoped stream once its token has expired, so a request
|
|
// it applied at that moment would lose its reply. A source that cannot be
|
|
// read fails the request.
|
|
func (m *streamMutateMux) mustRetireLocked() (bool, error) {
|
|
source := m.wfs.option.FilerTokenSource
|
|
if source == nil {
|
|
return false, nil
|
|
}
|
|
token, err := source(context.Background())
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if token != m.token {
|
|
return true, nil
|
|
}
|
|
return m.tokenExpiring(m.expiresAt), nil
|
|
}
|
|
|
|
// retireLocked ends the current stream so a successor can open with a new
|
|
// token. It stops admitting requests and, in the background, waits for the
|
|
// admitted ones to be answered, half-closes the stream so the filer finishes
|
|
// it, and waits for the receive loop to end; m.draining closes when that is
|
|
// done. Running it in the background lets a request that triggered or waits
|
|
// for the retirement give up on its own context without cutting the admitted
|
|
// requests short. A wait gives up only after filerRPCWait without a response,
|
|
// as a waiter's own timer does, so a long rename that keeps answering is not
|
|
// cut short; the stream is then cancelled instead of closed. Nothing is resent
|
|
// here: a request still unanswered when the wait gives up fails as on a lost
|
|
// stream. Close cancels the stream through m.retireCancel instead of waiting.
|
|
// Called with mu held; returns with mu held and no stream open.
|
|
func (m *streamMutateMux) retireLocked() {
|
|
draining := make(chan struct{})
|
|
m.draining = draining
|
|
stream, cancel, conn := m.stream, m.cancel, m.grpcConn
|
|
stopSend, sendDone, recvDone := m.stopSend, m.sendDone, m.recvDone
|
|
// The generation is this retirement's to end: teardownStream sees no
|
|
// stream and only cancels it, and the filer index stays where it is.
|
|
m.stream, m.cancel, m.grpcConn, m.stopSend = nil, nil, nil, nil
|
|
m.retireCancel = cancel
|
|
var idle chan struct{}
|
|
if m.active > 0 {
|
|
idle = make(chan struct{})
|
|
m.idle = idle
|
|
}
|
|
|
|
go func() {
|
|
wait := m.wfs.filerRPCWait()
|
|
quiet := idle == nil || m.waitWhileAnswering(idle)
|
|
close(stopSend)
|
|
if quiet {
|
|
// CloseSend must not race the send loop's Send.
|
|
select {
|
|
case <-sendDone:
|
|
case <-time.After(wait):
|
|
quiet = false
|
|
}
|
|
}
|
|
if !quiet {
|
|
cancel()
|
|
}
|
|
<-sendDone
|
|
if quiet {
|
|
stream.CloseSend()
|
|
m.waitWhileAnswering(recvDone)
|
|
}
|
|
cancel()
|
|
<-recvDone
|
|
if conn != nil {
|
|
conn.Close()
|
|
}
|
|
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.idle = nil
|
|
m.draining = nil
|
|
m.retireCancel = nil
|
|
close(draining)
|
|
}()
|
|
}
|
|
|
|
// waitWhileAnswering waits for done until filerRPCWait passes without a
|
|
// response arriving, and reports whether done closed.
|
|
func (m *streamMutateMux) waitWhileAnswering(done <-chan struct{}) bool {
|
|
wait := m.wfs.filerRPCWait()
|
|
timer := time.NewTimer(wait)
|
|
defer timer.Stop()
|
|
last := m.received.Load()
|
|
for {
|
|
select {
|
|
case <-done:
|
|
return true
|
|
case <-timer.C:
|
|
current := m.received.Load()
|
|
if current == last {
|
|
return false
|
|
}
|
|
last = current
|
|
timer.Reset(wait)
|
|
}
|
|
}
|
|
}
|
|
|
|
// openStream dials the first filer that accepts the stream, opening it with
|
|
// token (none when empty).
|
|
func (m *streamMutateMux) openStream(out *filer_pb.SeaweedFiler_StreamMutateEntryClient, token security.EncodedJwt) error {
|
|
streamToken := func(context.Context) (security.EncodedJwt, error) { return token, nil }
|
|
i := atomic.LoadInt32(&m.wfs.option.filerIndex)
|
|
n := int32(len(m.wfs.option.FilerAddresses))
|
|
var lastErr error
|
|
|
|
for x := int32(0); x < n; x++ {
|
|
idx := (i + x) % n
|
|
filerGrpcAddress := m.wfs.option.FilerAddresses[idx].ToGrpcAddress()
|
|
|
|
ctx := context.Background()
|
|
if m.wfs.signature != 0 {
|
|
ctx = grpcMetadata.AppendToOutgoingContext(ctx, "sw-client-id", fmt.Sprintf("%d", m.wfs.signature))
|
|
}
|
|
grpcConn, err := pb.GrpcDial(ctx, filerGrpcAddress, false, m.wfs.option.GrpcDialOption)
|
|
if err != nil {
|
|
lastErr = fmt.Errorf("stream dial %s: %v", filerGrpcAddress, err)
|
|
continue
|
|
}
|
|
|
|
client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(grpcConn, streamToken))
|
|
streamCtx, cancel := context.WithCancel(ctx)
|
|
stream, err := client.StreamMutateEntry(streamCtx)
|
|
if err != nil {
|
|
cancel()
|
|
grpcConn.Close()
|
|
lastErr = err
|
|
// Unimplemented means all filers lack it — stop rotating.
|
|
if s, ok := status.FromError(err); ok && s.Code() == codes.Unimplemented {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
|
|
atomic.StoreInt32(&m.wfs.option.filerIndex, idx)
|
|
m.filerIdx = idx
|
|
m.cancel = cancel
|
|
m.grpcConn = grpcConn
|
|
*out = stream
|
|
return nil
|
|
}
|
|
return lastErr
|
|
}
|
|
|
|
// sendLoop sends the requests queued for generation gen, whose token expires
|
|
// at expiresAt (zero when unknown).
|
|
func (m *streamMutateMux) sendLoop(stream filer_pb.SeaweedFiler_StreamMutateEntryClient, stop <-chan struct{}, done chan<- struct{}, gen uint64, expiresAt time.Time) {
|
|
defer close(done)
|
|
defer m.drainSendCh()
|
|
for {
|
|
select {
|
|
case req, ok := <-m.sendCh:
|
|
if !ok {
|
|
return // defensive: sendCh should not be closed
|
|
}
|
|
if req.gen != gen {
|
|
req.errCh <- fmt.Errorf("%w: stream generation mismatch", ErrStreamTransport)
|
|
continue
|
|
}
|
|
// A request admitted with the token's margin may have waited here
|
|
// until the margin was gone; its reply could then be refused. Not
|
|
// sending it lets it go out over unary, which is safe because the
|
|
// filer never saw it.
|
|
if m.tokenExpiring(expiresAt) {
|
|
req.errCh <- fmt.Errorf("%w: filer token expires within %v, not sent", ErrStreamTransport, m.wfs.filerRPCWait())
|
|
continue
|
|
}
|
|
err := stream.Send(req.req)
|
|
req.errCh <- err
|
|
if err != nil {
|
|
m.teardownStream(gen)
|
|
return
|
|
}
|
|
case <-stop:
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (m *streamMutateMux) recvLoop(stream filer_pb.SeaweedFiler_StreamMutateEntryClient, gen uint64, recvDone chan struct{}) {
|
|
defer func() {
|
|
m.failAllPending()
|
|
close(recvDone)
|
|
}()
|
|
for {
|
|
resp, err := stream.Recv()
|
|
if err != nil {
|
|
if err != io.EOF {
|
|
glog.V(1).Infof("stream mutate recv error (gen=%d): %v", gen, err)
|
|
}
|
|
m.teardownStream(gen)
|
|
return
|
|
}
|
|
m.received.Add(1)
|
|
|
|
if ch, ok := m.pending.Load(resp.RequestId); ok {
|
|
ch.(chan *filer_pb.StreamMutateEntryResponse) <- resp
|
|
// For single-response ops, the caller deletes from pending after recv.
|
|
// For rename, the caller collects until is_last.
|
|
}
|
|
}
|
|
}
|
|
|
|
// teardownStream cleans up the stream for the given generation. It is safe to
|
|
// call from both sendLoop and recvLoop; only the first call for a given
|
|
// generation takes effect (idempotent via generation + nil-stream check).
|
|
func (m *streamMutateMux) teardownStream(gen uint64) {
|
|
m.mu.Lock()
|
|
if m.generation != gen || m.stream == nil {
|
|
// A retiring stream is ended by its retirement, but one a waiter gave
|
|
// up on must stop at once, as a torn-down stream does: a request still
|
|
// queued on it must not go out after its waiter fell back to unary.
|
|
if m.generation == gen && m.retireCancel != nil {
|
|
m.retireCancel()
|
|
}
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
filerIdx := m.filerIdx
|
|
m.stream = nil
|
|
if m.stopSend != nil {
|
|
close(m.stopSend)
|
|
m.stopSend = nil
|
|
}
|
|
if m.cancel != nil {
|
|
m.cancel()
|
|
m.cancel = nil
|
|
}
|
|
conn := m.grpcConn
|
|
m.grpcConn = nil
|
|
// Rotate while still holding mu: a new generation cannot open until
|
|
// teardown releases the lock, so the index advanced here always belongs
|
|
// to the stream that just died — never to a successor ensureStream may
|
|
// have opened in between.
|
|
if n := int32(len(m.wfs.option.FilerAddresses)); n > 0 {
|
|
atomic.CompareAndSwapInt32(&m.wfs.option.filerIndex, filerIdx, (filerIdx+1)%n)
|
|
}
|
|
m.mu.Unlock()
|
|
|
|
// Do NOT call failAllPending here — recvLoop is the sole owner of
|
|
// pending channel teardown. This avoids a race where teardownStream
|
|
// closes a channel that recvLoop is about to send on.
|
|
if conn != nil {
|
|
conn.Close()
|
|
}
|
|
}
|
|
|
|
// failAllPending closes all pending response channels, causing waiters to
|
|
// receive ok=false. It is idempotent: entries are deleted before channels are
|
|
// closed, so concurrent calls cannot double-close.
|
|
func (m *streamMutateMux) failAllPending() {
|
|
var channels []chan *filer_pb.StreamMutateEntryResponse
|
|
m.pending.Range(func(key, value any) bool {
|
|
m.pending.Delete(key)
|
|
channels = append(channels, value.(chan *filer_pb.StreamMutateEntryResponse))
|
|
return true
|
|
})
|
|
for _, ch := range channels {
|
|
close(ch)
|
|
}
|
|
}
|
|
|
|
// drainSendCh drains buffered requests from sendCh, sending an error to each
|
|
// request's errCh so callers don't block. Called by sendLoop's defer on exit
|
|
// and by Close for any stragglers.
|
|
func (m *streamMutateMux) drainSendCh() {
|
|
for {
|
|
select {
|
|
case req, ok := <-m.sendCh:
|
|
if !ok {
|
|
return // defensive: sendCh should not be closed
|
|
}
|
|
req.errCh <- fmt.Errorf("%w: stream shutting down", ErrStreamTransport)
|
|
default:
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// IsAvailable returns true if the stream mux is usable (not permanently disabled).
|
|
func (m *streamMutateMux) IsAvailable() bool {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return !m.disabled
|
|
}
|
|
|
|
// Close shuts down the stream. Called during unmount after all flushes complete.
|
|
func (m *streamMutateMux) Close() {
|
|
m.mu.Lock()
|
|
if m.closed {
|
|
m.mu.Unlock()
|
|
return
|
|
}
|
|
m.closed = true
|
|
stream := m.stream
|
|
m.stream = nil // prevent teardownStream from acting after Close
|
|
cancel := m.cancel
|
|
m.cancel = nil
|
|
// A retirement would wait for its admitted requests to be answered;
|
|
// unmount cuts it short instead.
|
|
if cancel == nil {
|
|
cancel = m.retireCancel
|
|
}
|
|
grpcConn := m.grpcConn
|
|
m.grpcConn = nil
|
|
recvDone := m.recvDone
|
|
if m.stopSend != nil {
|
|
close(m.stopSend)
|
|
m.stopSend = nil
|
|
}
|
|
m.mu.Unlock()
|
|
|
|
// CloseSend triggers EOF on recvLoop; cancel ensures Recv unblocks
|
|
// even if the transport is broken.
|
|
if stream != nil {
|
|
stream.CloseSend()
|
|
}
|
|
if cancel != nil {
|
|
cancel()
|
|
}
|
|
// Wait for recvLoop to finish — it calls failAllPending on exit.
|
|
if recvDone != nil {
|
|
<-recvDone
|
|
}
|
|
if grpcConn != nil {
|
|
grpcConn.Close()
|
|
}
|
|
// Drain any remaining requests buffered in sendCh. sendLoop's defer
|
|
// drain handles most items, but stragglers enqueued during shutdown
|
|
// (between ensureStream and the sendCh send) are caught here.
|
|
// sendCh is intentionally left open to prevent send-on-closed panics.
|
|
m.drainSendCh()
|
|
}
|