mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* security: filer token source read from a file FilerTokenFile is the token source of a client that holds a pre-issued filer token rather than a signing key. It reads the file on every call, so an atomic replacement that keeps size and mtime takes effect on the next attempt, and trims surrounding whitespace. A missing, unreadable, empty or malformed file fails the call: there is no fallback to anonymous or admin authority, and errors name the path but not the contents. FilerTokenClaims decodes a token's claims without a key, and FilerTokenGrantCovers compares two grants, so a client can plan reconnects before expiry and know when a replacement narrows what it may see. * mount: -filer.tokenFile authorizes filer calls with a pre-issued token A mount that should not hold a filer signing key can now present a token issued for it. -filer.tokenFile (or -o filer.tokenFile=) names the file; it is read for every filer gRPC attempt, so a replaced file takes effect on the next call or retry without a restart, and a missing or empty file fails the call locally. The source reaches every filer client the mount builds: the startup handshake, each attempt of WithFilerClient, the volume location client, the SSE-S3 reader's configuration call, the peer registrar dial and the lock client. It is attached per call, never to the cached channel, and never to master, volume or peer mount RPCs. The filer refuses MountRegister, MountList and distributed locks to scoped tokens, so the mount refuses to start when -filer.tokenFile is combined with -peer.enable or -dlm instead of failing at run time. Server-side copy_file_range signs its filer HTTP request with the HTTP key, not this token, and is unsupported with it. Without the flag the mount behaves as before. * mount: resubscribe metadata with a replaced filer token A metadata subscription keeps the authority it opened with, so a mount reading -filer.tokenFile would follow with the old token until the filer ended the stream at expiry, and every such end took the gap path that distrusts all cached listings. SubscribeMetaEvents now takes the credentials of each attempt. The mount opens each subscription with the token current at that moment and watches the file; once it holds a different token the attempt ends and the follow resubscribes at once from its checkpoint. This planned resubscribe is not a gap: cached listings stay, unless the new grant may show less than the old one or either token cannot be decoded, in which case they are read again so nothing the old grant showed outlives it. The filer walk treats a resubscribe like a stopped follow, so the same attempt is not replayed on the next filer. Without a token file nothing changes. * mount: hand the mutation stream over to a replaced filer token The mutation stream keeps the token it opened with, and a filer refuses to send on a scoped stream once that token has expired. A mutation applied at that moment loses its reply, the mount reads that as a transport failure, and the unary fallback sends it again. The stream now opens with a snapshot of the token source. Before admitting a request it checks the source: when the file holds another token, or the stream's token would expire before a reply could come back, the stream is retired. New requests wait while the admitted ones are answered, the stream is half-closed so the filer finishes it, and a successor opens with the new token. The waits give up only after filerRPCWait without a response, so a rename that keeps answering is not cut short. A request is never resent by the handover: one still unanswered when the wait gives up fails as on any lost stream, as before. A token too close to expiry to open a stream with is refused before anything is sent, so the request goes out once as a unary call, which the filer checks when it starts. Without a token file nothing changes. * mount: review fixes for the filer token file - A distrust of cached listings now also discards the directory builds in flight, in the meta cache's apply loop: such a build publishes nothing, its entries are wiped and the visit lists the directory again, so a listing read under a grant that has since narrowed is never cached after the distrust. The cached flags are reset again in the loop, after any build that completed before it. - Retiring the mutation stream runs in the background, and a request that waits for the retirement gives up on its own context, unadmitted. - With a token file and no filer signing key, server-side whole-file copy is not tried: its filer HTTP request would go out unsigned and fail as ambiguous. The copy streams through the chunk path instead. - On Windows the token file is opened with delete sharing, so a renewer can replace it by rename while a read holds it open; the missing-file test checks os.ErrNotExist instead of Unix wording. * mount: review fixes for the mutation stream handover A request admitted to the mutation stream with just over one RPC wait left on its token could wait behind a slow send until that margin was gone; its reply could then be refused at expiry and the request was resent over unary. The send loop now checks the margin again right before sending and holds back a request that no longer has it, which is safe to send over unary because the filer never saw it. A sent request whose reply is lost while the token has one RPC wait or less left now fails with EIO instead of a transport error: the filer may have applied it, so it is not resent. Losses with the margin intact fall back to unary as before. A newly opened stream now admits its first request through the same checks as an open one, so a token file replaced, or a token that neared expiry, while the stream opened is caught before anything is sent. A retirement keeps a cancel handle for its stream. Close uses it, so unmount no longer waits for admitted requests to be answered, and a waiter that gives up on a retiring stream stops it as it would stop an open one, so a request still queued there is never sent after that waiter fell back to unary. An ordinary rotation still drains admitted requests. * mount: drop kernel listings when the filer token's grant narrows A replacement token whose grant may not cover the old one already distrusts the mount's own cached listings. The kernel kept its own copy: OpenDir sets FOPEN_CACHE_DIR | FOPEN_KEEP_CACHE, so a directory still reachable under the new grant was listed again from the page cache with names the new grant may hide, until something else invalidated it. On a narrowed or undecodable grant the mount now also notifies the kernel for every directory inode it holds, from the subscription goroutine as the metadata apply path already does, so the next readdir reaches the mount. A readdir already under way on an open handle still finishes from what it read. * mount: drop kernel listings after a subscription gap too distrustCachedListings serves both the narrowed-grant path and the gap path. A gap can lose the very events that would have dropped the kernel's cached listings one directory at a time, and with FOPEN_KEEP_CACHE on OpenDir the kernel then serves those listings on every reopen. Move the kernel drop into distrustCachedListings so both paths get it. 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>
662 lines
22 KiB
Go
662 lines
22 KiB
Go
package mount
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
)
|
|
|
|
type mutateRecord struct {
|
|
stream int // 1-based stream number, 0 for a unary CreateEntry
|
|
token string
|
|
name string
|
|
}
|
|
|
|
// tokenMutateFiler answers creates on StreamMutateEntry and CreateEntry,
|
|
// recording which stream and token carried each one. A create for a name in
|
|
// held is answered only once that name is released.
|
|
type tokenMutateFiler struct {
|
|
filer_pb.UnimplementedSeaweedFilerServer
|
|
|
|
mu sync.Mutex
|
|
records []mutateRecord
|
|
held map[string]chan struct{}
|
|
arrived chan string
|
|
streams int
|
|
finished []int // streams the client half-closed cleanly
|
|
}
|
|
|
|
func newTokenMutateFiler() *tokenMutateFiler {
|
|
return &tokenMutateFiler{held: map[string]chan struct{}{}, arrived: make(chan string, 16)}
|
|
}
|
|
|
|
func (f *tokenMutateFiler) hold(name string) {
|
|
f.mu.Lock()
|
|
f.held[name] = make(chan struct{})
|
|
f.mu.Unlock()
|
|
}
|
|
|
|
func (f *tokenMutateFiler) release(name string) {
|
|
f.mu.Lock()
|
|
close(f.held[name])
|
|
f.mu.Unlock()
|
|
}
|
|
|
|
func (f *tokenMutateFiler) record(r mutateRecord) chan struct{} {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.records = append(f.records, r)
|
|
return f.held[r.name]
|
|
}
|
|
|
|
func (f *tokenMutateFiler) snapshot() (records []mutateRecord, streams int, finished []int) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return append([]mutateRecord(nil), f.records...), f.streams, append([]int(nil), f.finished...)
|
|
}
|
|
|
|
func (f *tokenMutateFiler) StreamMutateEntry(stream filer_pb.SeaweedFiler_StreamMutateEntryServer) error {
|
|
md, _ := metadata.FromIncomingContext(stream.Context())
|
|
f.mu.Lock()
|
|
f.streams++
|
|
n := f.streams
|
|
f.mu.Unlock()
|
|
for {
|
|
req, err := stream.Recv()
|
|
if err == io.EOF {
|
|
f.mu.Lock()
|
|
f.finished = append(f.finished, n)
|
|
f.mu.Unlock()
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
create := req.GetCreateRequest()
|
|
gate := f.record(mutateRecord{stream: n, token: joinAuthorization(md), name: create.GetEntry().GetName()})
|
|
f.arrived <- create.GetEntry().GetName()
|
|
if gate != nil {
|
|
select {
|
|
case <-gate:
|
|
case <-stream.Context().Done():
|
|
return stream.Context().Err()
|
|
}
|
|
}
|
|
if err := stream.Send(&filer_pb.StreamMutateEntryResponse{
|
|
RequestId: req.RequestId,
|
|
IsLast: true,
|
|
Response: &filer_pb.StreamMutateEntryResponse_CreateResponse{CreateResponse: &filer_pb.CreateEntryResponse{}},
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
func (f *tokenMutateFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
|
md, _ := metadata.FromIncomingContext(ctx)
|
|
f.record(mutateRecord{token: joinAuthorization(md), name: req.GetEntry().GetName()})
|
|
f.arrived <- req.GetEntry().GetName()
|
|
return &filer_pb.CreateEntryResponse{}, nil
|
|
}
|
|
|
|
func newTokenMutateMount(t *testing.T, source security.FilerTokenSource) (*WFS, *tokenMutateFiler) {
|
|
t.Helper()
|
|
fake := newTokenMutateFiler()
|
|
wfs := newInvalidateTestWFS(t)
|
|
wfs.filerCallTimeout = 5 * time.Second
|
|
wfs.option.FilerAddresses = []pb.ServerAddress{listenFiler(t, fake)}
|
|
atomic.StoreInt32(&wfs.option.filerIndex, 0)
|
|
wfs.option.FilerTokenSource = source
|
|
wfs.streamMutate = newStreamMutateMux(wfs)
|
|
t.Cleanup(wfs.streamMutate.Close)
|
|
return wfs, fake
|
|
}
|
|
|
|
func createThroughMount(wfs *WFS, name string) error {
|
|
_, err := wfs.streamCreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
|
Directory: "/dir",
|
|
Entry: &filer_pb.Entry{Name: name},
|
|
})
|
|
return err
|
|
}
|
|
|
|
func awaitArrival(t *testing.T, fake *tokenMutateFiler, want string) {
|
|
t.Helper()
|
|
select {
|
|
case got := <-fake.arrived:
|
|
if got != want {
|
|
t.Fatalf("filer received %q, want %q", got, want)
|
|
}
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatalf("filer never received %q", want)
|
|
}
|
|
}
|
|
|
|
func wantRecords(t *testing.T, got []mutateRecord, want ...mutateRecord) {
|
|
t.Helper()
|
|
if len(got) != len(want) {
|
|
t.Fatalf("filer received %+v, want %+v", got, want)
|
|
}
|
|
for i := range want {
|
|
if got[i] != want[i] {
|
|
t.Fatalf("filer received %+v, want %+v", got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Without a token source the mux runs one stream with no bearer, as before.
|
|
func TestStreamMutateWithoutTokenSourceKeepsOneStream(t *testing.T) {
|
|
wfs, fake := newTokenMutateMount(t, nil)
|
|
for _, name := range []string{"a", "b"} {
|
|
if err := createThroughMount(wfs, name); err != nil {
|
|
t.Fatalf("create %s: %v", name, err)
|
|
}
|
|
awaitArrival(t, fake, name)
|
|
}
|
|
records, streams, _ := fake.snapshot()
|
|
wantRecords(t, records, mutateRecord{stream: 1, name: "a"}, mutateRecord{stream: 1, name: "b"})
|
|
if streams != 1 {
|
|
t.Fatalf("streams = %d, want 1", streams)
|
|
}
|
|
}
|
|
|
|
// A replaced token retires the stream only after its admitted request is
|
|
// answered: the next request waits, then goes out once, on a new stream that
|
|
// carries the new token. Nothing falls back to unary, so nothing is replayed.
|
|
func TestStreamMutateDrainsBeforeReopeningWithReplacedToken(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "token")
|
|
writeMountTokenFile(t, path, "token-a")
|
|
wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path))
|
|
|
|
fake.hold("first")
|
|
first := make(chan error, 1)
|
|
go func() { first <- createThroughMount(wfs, "first") }()
|
|
awaitArrival(t, fake, "first")
|
|
|
|
writeMountTokenFile(t, path, "token-b")
|
|
second := make(chan error, 1)
|
|
go func() { second <- createThroughMount(wfs, "second") }()
|
|
|
|
select {
|
|
case name := <-fake.arrived:
|
|
t.Fatalf("filer received %q while the old stream still had a request unanswered", name)
|
|
case <-time.After(200 * time.Millisecond):
|
|
}
|
|
|
|
fake.release("first")
|
|
if err := <-first; err != nil {
|
|
t.Fatalf("first create: %v", err)
|
|
}
|
|
awaitArrival(t, fake, "second")
|
|
if err := <-second; err != nil {
|
|
t.Fatalf("second create: %v", err)
|
|
}
|
|
|
|
records, streams, finished := fake.snapshot()
|
|
wantRecords(t, records,
|
|
mutateRecord{stream: 1, token: "Bearer token-a", name: "first"},
|
|
mutateRecord{stream: 2, token: "Bearer token-b", name: "second"})
|
|
if streams != 2 || len(finished) != 1 || finished[0] != 1 {
|
|
t.Fatalf("streams = %d, cleanly finished %v; want the first half-closed before the second", streams, finished)
|
|
}
|
|
}
|
|
|
|
// A request cancelled while the retiring stream drains returns at once and is
|
|
// never sent; the retirement and the next stream carry on.
|
|
func TestStreamMutateCancelledWhileDrainingIsNotSent(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "token")
|
|
writeMountTokenFile(t, path, "token-a")
|
|
wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path))
|
|
|
|
fake.hold("first")
|
|
first := make(chan error, 1)
|
|
go func() { first <- createThroughMount(wfs, "first") }()
|
|
awaitArrival(t, fake, "first")
|
|
|
|
writeMountTokenFile(t, path, "token-b")
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancelled := make(chan error, 1)
|
|
go func() {
|
|
_, err := wfs.streamMutate.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
|
Directory: "/dir", Entry: &filer_pb.Entry{Name: "cancelled"},
|
|
})
|
|
cancelled <- err
|
|
}()
|
|
select {
|
|
case err := <-cancelled:
|
|
t.Fatalf("request returned %v before the old stream drained", err)
|
|
case <-time.After(200 * time.Millisecond):
|
|
}
|
|
cancel()
|
|
select {
|
|
case err := <-cancelled:
|
|
if !errors.Is(err, context.Canceled) {
|
|
t.Fatalf("cancelled request returned %v, want context.Canceled", err)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("a cancelled request kept waiting for the old stream to drain")
|
|
}
|
|
|
|
fake.release("first")
|
|
if err := <-first; err != nil {
|
|
t.Fatalf("first create: %v", err)
|
|
}
|
|
if err := createThroughMount(wfs, "after"); err != nil {
|
|
t.Fatalf("create after: %v", err)
|
|
}
|
|
awaitArrival(t, fake, "after")
|
|
records, _, _ := fake.snapshot()
|
|
wantRecords(t, records,
|
|
mutateRecord{stream: 1, token: "Bearer token-a", name: "first"},
|
|
mutateRecord{stream: 2, token: "Bearer token-b", name: "after"})
|
|
}
|
|
|
|
// Each replacement retires the stream in turn; requests in between share it.
|
|
func TestStreamMutateConsecutiveTokenReplacements(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "token")
|
|
writeMountTokenFile(t, path, "token-1")
|
|
wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path))
|
|
|
|
steps := []struct{ token, name string }{
|
|
{"token-1", "a"}, {"token-1", "b"}, {"token-2", "c"}, {"token-3", "d"}, {"token-3", "e"},
|
|
}
|
|
for _, step := range steps {
|
|
writeMountTokenFile(t, path, step.token)
|
|
if err := createThroughMount(wfs, step.name); err != nil {
|
|
t.Fatalf("create %s: %v", step.name, err)
|
|
}
|
|
awaitArrival(t, fake, step.name)
|
|
}
|
|
|
|
records, streams, finished := fake.snapshot()
|
|
wantRecords(t, records,
|
|
mutateRecord{stream: 1, token: "Bearer token-1", name: "a"},
|
|
mutateRecord{stream: 1, token: "Bearer token-1", name: "b"},
|
|
mutateRecord{stream: 2, token: "Bearer token-2", name: "c"},
|
|
mutateRecord{stream: 3, token: "Bearer token-3", name: "d"},
|
|
mutateRecord{stream: 3, token: "Bearer token-3", name: "e"})
|
|
if streams != 3 || len(finished) != 2 {
|
|
t.Fatalf("streams = %d, cleanly finished %v; want 3 streams, the first two half-closed", streams, finished)
|
|
}
|
|
}
|
|
|
|
// A stream stops admitting requests once its token would expire before a
|
|
// reply could come back. With no replacement in the file, the request is not
|
|
// sent on any stream and goes out once as a unary call, which the filer
|
|
// checks when it starts.
|
|
func TestStreamMutateRetiresStreamBeforeTokenExpiry(t *testing.T) {
|
|
key := randomFilerKey(t)
|
|
token := security.GenJwtForFilerScope(key, 2*time.Second, "short", []string{"/dir"}, nil)
|
|
path := filepath.Join(t.TempDir(), "token")
|
|
writeMountTokenFile(t, path, string(token))
|
|
wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path))
|
|
wfs.filerCallTimeout = 500 * time.Millisecond
|
|
expiresAt := filerTokenExpiry(token)
|
|
if time.Until(expiresAt) <= wfs.filerCallTimeout {
|
|
t.Skip("token already too close to expiry to open a stream")
|
|
}
|
|
|
|
if err := createThroughMount(wfs, "early"); err != nil {
|
|
t.Fatalf("early create: %v", err)
|
|
}
|
|
awaitArrival(t, fake, "early")
|
|
|
|
time.Sleep(time.Until(expiresAt.Add(-wfs.filerCallTimeout)) + 50*time.Millisecond)
|
|
_, err := wfs.streamMutate.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
|
Directory: "/dir", Entry: &filer_pb.Entry{Name: "refused"},
|
|
})
|
|
if !errors.Is(err, ErrStreamTransport) {
|
|
t.Fatalf("stream create near expiry = %v, want a transport error before sending", err)
|
|
}
|
|
if err := createThroughMount(wfs, "late"); err != nil {
|
|
t.Fatalf("late create: %v", err)
|
|
}
|
|
awaitArrival(t, fake, "late")
|
|
|
|
records, streams, finished := fake.snapshot()
|
|
wantRecords(t, records,
|
|
mutateRecord{stream: 1, token: "Bearer " + string(token), name: "early"},
|
|
mutateRecord{stream: 0, token: "Bearer " + string(token), name: "late"})
|
|
if streams != 1 || len(finished) != 1 {
|
|
t.Fatalf("streams = %d, cleanly finished %v; want the expiring stream half-closed and none reopened", streams, finished)
|
|
}
|
|
}
|
|
|
|
// A token file that cannot be read fails the mutation on both paths without
|
|
// reaching the filer.
|
|
func TestStreamMutateFailsClosedWithoutTokenFile(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "token")
|
|
writeMountTokenFile(t, path, "token-a")
|
|
wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path))
|
|
if err := createThroughMount(wfs, "before"); err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
awaitArrival(t, fake, "before")
|
|
|
|
if err := os.Remove(path); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := createThroughMount(wfs, "after"); err == nil {
|
|
t.Fatal("create succeeded without a readable token file")
|
|
}
|
|
records, _, _ := fake.snapshot()
|
|
wantRecords(t, records, mutateRecord{stream: 1, token: "Bearer token-a", name: "before"})
|
|
}
|
|
|
|
// A request whose reply does not come back while the stream's token is about
|
|
// to expire may have been applied by the filer, which refuses to answer on an
|
|
// expired stream. It fails as unknown instead of going out again over unary,
|
|
// so the filer sees it exactly once.
|
|
func TestStreamMutateReplyLostNearExpiryIsNotReplayed(t *testing.T) {
|
|
key := randomFilerKey(t)
|
|
token := security.GenJwtForFilerScope(key, 6*time.Second, "short", []string{"/dir"}, nil)
|
|
path := filepath.Join(t.TempDir(), "token")
|
|
writeMountTokenFile(t, path, string(token))
|
|
wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path))
|
|
wfs.filerCallTimeout = time.Second
|
|
expiresAt := filerTokenExpiry(token)
|
|
// Half a wait before the margin ends: the request is still admitted and
|
|
// sent, and its reply wait ends within the margin.
|
|
sendAt := expiresAt.Add(-wfs.filerCallTimeout * 3 / 2)
|
|
if time.Until(sendAt) <= 0 {
|
|
t.Skip("token already too close to expiry")
|
|
}
|
|
|
|
if err := createThroughMount(wfs, "early"); err != nil {
|
|
t.Fatalf("early create: %v", err)
|
|
}
|
|
awaitArrival(t, fake, "early")
|
|
|
|
// Admitted and sent with the margin intact; the filer applies it and does
|
|
// not answer before the reply wait ends, inside the margin.
|
|
fake.hold("held")
|
|
defer fake.release("held")
|
|
time.Sleep(time.Until(sendAt))
|
|
err := createThroughMount(wfs, "held")
|
|
records, _, _ := fake.snapshot()
|
|
if len(records) != 2 {
|
|
t.Fatalf("filer received %+v, want early and held once each", records)
|
|
}
|
|
if records[1].stream == 0 {
|
|
// The expiry is wall-clock time; a clock step during the sleep can
|
|
// leave too little margin to send, and the request then correctly
|
|
// went out once over unary instead.
|
|
t.Skipf("wall clock passed the margin before the send (%v left); held went out over unary once", time.Until(expiresAt))
|
|
}
|
|
if err == nil || errors.Is(err, ErrStreamTransport) {
|
|
t.Fatalf("create whose reply was lost near expiry = %v, want a failure that is not resent", err)
|
|
}
|
|
wantRecords(t, records,
|
|
mutateRecord{stream: 1, token: "Bearer " + string(token), name: "early"},
|
|
mutateRecord{stream: 1, token: "Bearer " + string(token), name: "held"})
|
|
}
|
|
|
|
// The send loop checks the token's margin again right before sending: a
|
|
// request admitted with the margin that waited behind a slow send until the
|
|
// margin was gone is not sent, and fails with a transport error so it goes out
|
|
// once over unary.
|
|
func TestStreamMutateSendLoopHoldsBackRequestOnceMarginIsGone(t *testing.T) {
|
|
wfs := newInvalidateTestWFS(t)
|
|
wfs.filerCallTimeout = 300 * time.Millisecond
|
|
m := newStreamMutateMux(wfs)
|
|
stream := newFakeMutateClientStream("slow")
|
|
expiresAt := time.Now().Add(wfs.filerCallTimeout + 200*time.Millisecond)
|
|
stop, done := make(chan struct{}), make(chan struct{})
|
|
go m.sendLoop(stream, stop, done, 1, expiresAt)
|
|
defer func() {
|
|
close(stop)
|
|
stream.cancel()
|
|
<-done
|
|
}()
|
|
|
|
slow, late := queueFakeCreate(m, "slow"), queueFakeCreate(m, "late")
|
|
stream.awaitSend(t, "slow")
|
|
time.Sleep(time.Until(expiresAt.Add(-wfs.filerCallTimeout)) + 50*time.Millisecond)
|
|
close(stream.unblock)
|
|
|
|
if err := <-slow; err != nil {
|
|
t.Fatalf("slow send: %v", err)
|
|
}
|
|
if err := <-late; !errors.Is(err, ErrStreamTransport) {
|
|
t.Fatalf("send after the margin was gone = %v, want a transport error", err)
|
|
}
|
|
if sent := stream.sentNames(); len(sent) != 1 || sent[0] != "slow" {
|
|
t.Fatalf("stream sent %v, want only slow", sent)
|
|
}
|
|
}
|
|
|
|
// A token file replaced while the stream opens is caught when the first
|
|
// request is admitted: that stream is retired unused and the request goes out
|
|
// on a successor carrying the new token.
|
|
func TestStreamMutateTokenReplacedWhileOpeningIsNotUsed(t *testing.T) {
|
|
var reads atomic.Int32
|
|
source := func(context.Context) (security.EncodedJwt, error) {
|
|
if reads.Add(1) == 1 {
|
|
return "token-a", nil
|
|
}
|
|
return "token-b", nil
|
|
}
|
|
wfs, fake := newTokenMutateMount(t, source)
|
|
if err := createThroughMount(wfs, "first"); err != nil {
|
|
t.Fatalf("create: %v", err)
|
|
}
|
|
awaitArrival(t, fake, "first")
|
|
records, streams, finished := fake.snapshot()
|
|
wantRecords(t, records, mutateRecord{stream: 2, token: "Bearer token-b", name: "first"})
|
|
if streams != 2 || len(finished) != 1 || finished[0] != 1 {
|
|
t.Fatalf("streams = %d, cleanly finished %v; want the first retired unused", streams, finished)
|
|
}
|
|
}
|
|
|
|
// Unmount during a retirement does not wait for the admitted requests to be
|
|
// answered: the retiring stream is cancelled, and its waiters return.
|
|
func TestStreamMutateCloseCutsRetirementShort(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "token")
|
|
writeMountTokenFile(t, path, "token-a")
|
|
wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path))
|
|
m := wfs.streamMutate
|
|
|
|
fake.hold("first")
|
|
defer fake.release("first")
|
|
first := goFakeCreate(m, "first")
|
|
awaitArrival(t, fake, "first")
|
|
writeMountTokenFile(t, path, "token-b")
|
|
second := goFakeCreate(m, "second")
|
|
awaitRetiring(t, m)
|
|
|
|
start := time.Now()
|
|
m.Close()
|
|
limit := wfs.filerCallTimeout / 5
|
|
if elapsed := time.Since(start); elapsed > limit {
|
|
t.Fatalf("Close took %v during a retirement, want under %v", elapsed, limit)
|
|
}
|
|
for _, ch := range []chan error{first, second} {
|
|
select {
|
|
case err := <-ch:
|
|
if err == nil {
|
|
t.Fatal("a request succeeded after Close")
|
|
}
|
|
case <-time.After(limit):
|
|
t.Fatal("a request kept waiting after Close")
|
|
}
|
|
}
|
|
records, _, _ := fake.snapshot()
|
|
wantRecords(t, records, mutateRecord{stream: 1, token: "Bearer token-a", name: "first"})
|
|
}
|
|
|
|
// A waiter that gives up on a retiring stream stops it at once, as on an open
|
|
// stream: its request, possibly still queued behind a stuck send, falls back to
|
|
// unary and must never go out on the old stream afterwards.
|
|
func TestStreamMutateSendTimeoutStopsRetiringStream(t *testing.T) {
|
|
wfs := newInvalidateTestWFS(t)
|
|
wfs.filerCallTimeout = 500 * time.Millisecond
|
|
var current atomic.Value
|
|
current.Store(security.EncodedJwt("token-a"))
|
|
wfs.option.FilerTokenSource = func(context.Context) (security.EncodedJwt, error) {
|
|
return current.Load().(security.EncodedJwt), nil
|
|
}
|
|
// The successor opens on a real filer.
|
|
wfs.option.FilerAddresses = []pb.ServerAddress{listenFiler(t, newTokenMutateFiler())}
|
|
atomic.StoreInt32(&wfs.option.filerIndex, 0)
|
|
m := newStreamMutateMux(wfs)
|
|
t.Cleanup(m.Close)
|
|
stream := newFakeMutateClientStream("stuck")
|
|
m.mu.Lock()
|
|
m.startLocked(stream, "token-a", time.Time{})
|
|
m.cancel = stream.cancel
|
|
m.mu.Unlock()
|
|
|
|
stuck := goFakeCreate(m, "stuck")
|
|
stream.awaitSend(t, "stuck")
|
|
queued := goFakeCreate(m, "queued")
|
|
awaitActive(t, m, 2)
|
|
current.Store(security.EncodedJwt("token-b"))
|
|
next := goFakeCreate(m, "next")
|
|
awaitRetiring(t, m)
|
|
|
|
for _, ch := range []chan error{stuck, queued} {
|
|
if err := <-ch; !errors.Is(err, ErrStreamTransport) {
|
|
t.Fatalf("timed-out send = %v, want a transport error", err)
|
|
}
|
|
}
|
|
if stream.ctx.Err() == nil {
|
|
t.Fatal("the retiring stream kept running after its waiters fell back to unary")
|
|
}
|
|
if err := <-next; err != nil {
|
|
t.Fatalf("create on the successor: %v", err)
|
|
}
|
|
if sent := stream.sentNames(); len(sent) != 0 {
|
|
t.Fatalf("the retiring stream sent %v after its waiters gave up", sent)
|
|
}
|
|
}
|
|
|
|
// fakeMutateClientStream is the client end of a mutation stream whose Send of
|
|
// the named message blocks until unblock closes or the stream is cancelled.
|
|
type fakeMutateClientStream struct {
|
|
grpc.ClientStream
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
block string
|
|
unblock chan struct{}
|
|
entered chan string
|
|
mu sync.Mutex
|
|
sent []string
|
|
}
|
|
|
|
func newFakeMutateClientStream(block string) *fakeMutateClientStream {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
return &fakeMutateClientStream{ctx: ctx, cancel: cancel, block: block, unblock: make(chan struct{}), entered: make(chan string, 16)}
|
|
}
|
|
|
|
func (s *fakeMutateClientStream) Send(req *filer_pb.StreamMutateEntryRequest) error {
|
|
name := req.GetCreateRequest().GetEntry().GetName()
|
|
s.entered <- name
|
|
if name == s.block {
|
|
select {
|
|
case <-s.unblock:
|
|
case <-s.ctx.Done():
|
|
return s.ctx.Err()
|
|
}
|
|
}
|
|
if s.ctx.Err() != nil {
|
|
return s.ctx.Err()
|
|
}
|
|
s.mu.Lock()
|
|
s.sent = append(s.sent, name)
|
|
s.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
func (s *fakeMutateClientStream) Recv() (*filer_pb.StreamMutateEntryResponse, error) {
|
|
<-s.ctx.Done()
|
|
return nil, s.ctx.Err()
|
|
}
|
|
|
|
func (s *fakeMutateClientStream) CloseSend() error { return nil }
|
|
|
|
func (s *fakeMutateClientStream) sentNames() []string {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return append([]string(nil), s.sent...)
|
|
}
|
|
|
|
func (s *fakeMutateClientStream) awaitSend(t *testing.T, want string) {
|
|
t.Helper()
|
|
select {
|
|
case got := <-s.entered:
|
|
if got != want {
|
|
t.Fatalf("stream sending %q, want %q", got, want)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatalf("stream never started sending %q", want)
|
|
}
|
|
}
|
|
|
|
// queueFakeCreate queues a create for generation 1 straight onto the send
|
|
// loop and returns its send result.
|
|
func queueFakeCreate(m *streamMutateMux, name string) chan error {
|
|
errCh := make(chan error, 1)
|
|
m.sendCh <- &streamMutateReq{
|
|
req: &filer_pb.StreamMutateEntryRequest{
|
|
Request: &filer_pb.StreamMutateEntryRequest_CreateRequest{CreateRequest: &filer_pb.CreateEntryRequest{
|
|
Directory: "/dir", Entry: &filer_pb.Entry{Name: name},
|
|
}},
|
|
},
|
|
errCh: errCh,
|
|
gen: 1,
|
|
}
|
|
return errCh
|
|
}
|
|
|
|
// goFakeCreate runs a create through the mux, without the unary fallback.
|
|
func goFakeCreate(m *streamMutateMux, name string) chan error {
|
|
done := make(chan error, 1)
|
|
go func() {
|
|
_, err := m.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{
|
|
Directory: "/dir", Entry: &filer_pb.Entry{Name: name},
|
|
})
|
|
done <- err
|
|
}()
|
|
return done
|
|
}
|
|
|
|
func awaitRetiring(t *testing.T, m *streamMutateMux) {
|
|
t.Helper()
|
|
awaitMux(t, m, "a retirement", func() bool { return m.draining != nil })
|
|
}
|
|
|
|
func awaitActive(t *testing.T, m *streamMutateMux, n int) {
|
|
t.Helper()
|
|
awaitMux(t, m, "admissions", func() bool { return m.active == n })
|
|
}
|
|
|
|
func awaitMux(t *testing.T, m *streamMutateMux, what string, cond func() bool) {
|
|
t.Helper()
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for {
|
|
m.mu.Lock()
|
|
ok := cond()
|
|
m.mu.Unlock()
|
|
if ok {
|
|
return
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("mux never reached %s", what)
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
}
|