Files
seaweedfs/weed/server/master_grpc_server_test.go
T
Chris LuandClaude Opus 5.5 139c1d6d04 mq broker: survive startup, non-balancer brokers, and restarts (#13181)
* mq broker: turn a panic in an RPC into an error

The broker's gRPC servers had no recovery, so a nil dereference in any
handler took the whole process down. Once the broker runs inside
another server, that process is the host.

* mq broker: guard the filer set

The master's peer updates and the startup peer listing both write the
filers map and currentFiler from different goroutines, and every filer
call reads currentFiler. Two writers on the map at startup is a fatal
concurrent map write.

* mq broker: answer balancer requests before the balancer lock exists

The balancer lock is created only once the broker has found a filer,
while the gRPC server already serves. Every lookup, configure, publish
and balance request dereferenced it, so an early request crashed the
broker. Those requests now answer Unavailable until a balancer is
elected.

Ownership is the lock's unexpired lease instead of the owner name it
last saw, so a broker whose renewals have failed stops acting as
balancer once the lease runs out. A lapsed lease can still name this
broker, so proxying refuses to send a request to itself.

* mq broker: follow the filer lock ring

The balancer lock client was seeded with the first filer the broker
found and never given the ring, so it kept dialing that filer after it
left and no broker could become balancer. The broker now takes the
master's lock ring updates the way S3 gateways and mounts do, and the
master sends brokers the ring snapshot on connect.

* mq: never pick a partition's leader as its follower

pickBrokersExcluded ignored the leader it was told to exclude. With one
broker, the first assignment repair made that broker its own follower,
and it then replicated every publish to itself.

A dead follower that has no replacement is now dropped and counted as a
change, so the cleared name is saved; picking the leader had hidden
that.

* mq: keep a partition's leader unless a live broker replaces it

The repair cleared the leader of any partition whose leader it did not
see, even with no broker to take over, and the cleared assignment was
cached. With an empty broker set every leader went blank. A leader now
moves only to a live broker, the only live follower is promoted when it
is all that is left, and a follower that names its own leader is
replaced.

* mq broker: only a settled balancer repairs assignments

Every broker repaired topic assignments on a cache miss, but only the
balancer tracks which brokers are live. Any other broker saw an empty
set, cleared the topic's leaders, and could not load a partition it
did own, so a publish to it dereferenced a nil partition.

A newly elected balancer also waits 30 seconds, long enough for every
broker to notice the change and reconnect, before it treats a broker
it has not heard from as gone.

* mq broker: refuse a publish for a partition not assigned here

When the balancer named this broker as leader but its own copy of the
topic config did not, the partition lookup returned nil and the
publish dereferenced it. It now answers not-leader, and the publisher
looks the partition up again.

* mq broker: compare the publish leader as an address

The leader check built "ip:port" with Sprintf and compared strings,
while broker addresses are joined with JoinHostPort. On IPv6 the
brackets never matched and every publish was refused as not-leader.

* mq broker: flush partitions on stop

The broker had no Stop. Its loops ran on context.Background, and the
standalone command registered nothing for SIGTERM, so every restart
dropped the publishes still in the open flush window.

Stop now cancels the broker's loops, releases the balancer lock, and
waits until every partition has flushed. The command calls it on
interrupt before stopping its gRPC servers. The startup peer listing,
which blocked the constructor until a master answered, now runs in the
background with the balancer election.

* mq topic: flush partitions added or retired while stopping

Shutdown took one snapshot of the partition list, so a partition a
publish created after the snapshot was never flushed, and one that idle
cleanup had just retired was not waited on. Adding a partition now
fails once Shutdown starts, Shutdown waits out an idle cleanup pass in
progress, and every retired partition is waited on until its last
flush.

* mq broker: release the balancer lock once on stop

Stop and the balancer election could both release the lock when a stop
landed just as the lock was published, and a second LiveLock.Stop
closes its channel again and panics. Each path now takes the lock out
with Swap, so only one releases it.

* mq broker: forget the buffered ring version on a master change

Before the balancer lock client exists, the broker keeps the last ring
it got. A master change then reset nothing, so the client attached with
the old master's version and refused the new master's lower one.

* mq broker: restart the settle window when the balancer lease is regained

The window started when the lock owner's name changed. A balancer that
lost a renewal and got the lease back still had the same name, so it
skipped the wait and could repair assignments before brokers
reconnected. The window now counts from the first sight of the lease's
generation, which changes on every fresh acquisition and stays put on
renewal.

* mq broker: expire configs cached while the balancer settles

A balancer reading a topic during its settle window skipped the repair
and then cached the config for the full 30 seconds, so a dead leader
was served well past the window. Those entries now expire at the
settle deadline.

* mq topic: wait for drained partitions on shutdown

A partition removed by a drain or by its last client leaving was shut
down but not tracked, so a stop right after a resize could exit before
its final flush. Every removal now retires the partition through the
manager, and Shutdown waits on the set of retiring partitions instead
of a WaitGroup that a late removal could Add to while Wait ran.

* mq broker: update the settle window's lease and start together

The lease generation and its start were two atomics written one after
the other, so a concurrent reader could pair a regained lease's new
generation with the old start and see the window as already over. They
are now read and written under one lock.

* mq broker: refuse an assignment while stopping

A partition assigned after shutdown started was shut down, but the
handler still answered success, so the balancer recorded an assignment
this broker never installed. It now answers Unavailable.

* mq topic: signal a subscriber to stop only once

Shutdown leaves partitions registered, so a drain that arrives while the
broker flushes shuts the same partition down again, and closing a still
registered subscriber's stop channel a second time panicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq broker: bound flush retries once stopping

Stop waits for every partition's last flush, and a flush retried a failing
write forever, so a broker whose filer or volumes were unreachable never
exited on SIGTERM. In weed server it also held back the filer and volume
shutdown hooks, which run after it. Like the filer's metadata log, a flush
now gives up 15s into Stop and drops the window instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq.broker: flush before closing the localhost listener too

The localhost server's stop hook was registered after the broker's, so it
ran first and cut loopback clients before the partitions flushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq topic: gofmt local_manager.go

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq broker: end a shutdown flush stalled in a filer call

The shutdown budget was checked only after a failed append returned, and
the entry lookup and update ran under context.Background(), so a filer
that accepted the call and never answered still held Stop open. Flushes
now append under a context that Stop cancels once the budget runs out,
as the filer does for its metadata log. Every window after a dropped one
then drops too, so a later success cannot advance the watermark or tell
the follower to discard a window that never reached the filer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq topic: leave a partition to Shutdown once it starts

RemoveLocalPartition detached a partition before registering it as
retiring, so a Shutdown snapshot taken in between missed it and returned
before its last flush. Once Shutdown starts, removal now reports false and
the partition stays registered for Shutdown to retire, as idle cleanup
already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq broker: refuse an assignment for a hosted partition while stopping

Only a new partition was refused once Shutdown started. A partition the
broker already hosted stays registered after Shutdown retires it, so its
assignment was acknowledged although the broker no longer serves it. Both
paths now answer Unavailable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq broker: expire a settling balancer's config from when it was validated

The expiry was computed when the config was cached. A lookup that skipped
validation just before the settle deadline and cached the config just after
it kept the unrepaired assignments for the full TTL. The expiry now counts
from the time of validation, so such a config expires at the deadline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq broker: stop waiting on an upload once the flush budget ends

Cancelling the flush context ended retries and the filer metadata calls,
but not a volume assignment or upload already in flight. Those ran on
their own timeouts and retries, so a filer or volume server that never
answered held Stop past the budget, for minutes in the worst case. The
upload now runs on its own copy of the window, and the flush stops
waiting for it when the context ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:21:23 -08:00

244 lines
9.7 KiB
Go

package weed_server
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestInitialLockRingUpdateReturnsLastBroadcastForFilers(t *testing.T) {
ms := &MasterServer{
LockRingManager: cluster.NewLockRingManager(nil),
}
ms.LockRingManager.AddServer("group-a", "filer1:8888")
ms.LockRingManager.AddServer("group-a", "filer2:8888")
ms.LockRingManager.FlushPending("group-a")
resp := ms.initialLockRingUpdate(cluster.FilerType, "group-a")
require.NotNil(t, resp)
require.NotNil(t, resp.LockRingUpdate)
assert.Equal(t, "group-a", resp.LockRingUpdate.FilerGroup)
assert.ElementsMatch(t, []string{"filer1:8888", "filer2:8888"}, resp.LockRingUpdate.Servers)
assert.Greater(t, resp.LockRingUpdate.Version, int64(0))
}
func TestLeaveLockRingDropsOnlyTheLeavingFiler(t *testing.T) {
ms := &MasterServer{
LockRingManager: cluster.NewLockRingManager(nil),
}
ms.LockRingManager.AddServer("group-a", "filer1:8888")
ms.LockRingManager.AddServer("group-a", "filer2:8888")
ms.LockRingManager.FlushPending("group-a")
registered := &master_pb.KeepConnectedRequest{ClientType: cluster.FilerType, FilerGroup: "group-a"}
ms.onKeepConnectedMessage(registered, "filer1:8888", &master_pb.KeepConnectedRequest{})
ms.LockRingManager.FlushPending("group-a")
assert.ElementsMatch(t, []string{"filer1:8888", "filer2:8888"}, ms.LockRingManager.GetServers("group-a"))
ms.onKeepConnectedMessage(registered, "filer1:8888", &master_pb.KeepConnectedRequest{LeaveLockRing: true})
ms.LockRingManager.FlushPending("group-a")
assert.ElementsMatch(t, []string{"filer2:8888"}, ms.LockRingManager.GetServers("group-a"))
s3 := &master_pb.KeepConnectedRequest{ClientType: cluster.S3Type, FilerGroup: "group-a"}
ms.onKeepConnectedMessage(s3, "filer2:8888", &master_pb.KeepConnectedRequest{LeaveLockRing: true})
ms.LockRingManager.FlushPending("group-a")
assert.ElementsMatch(t, []string{"filer2:8888"}, ms.LockRingManager.GetServers("group-a"))
}
// A filer's replacement can register under the same address before the master
// ends the old stream; that stream's cleanup must leave the live filer in the ring.
func TestOverlappedFilerRegistrationStaysInLockRing(t *testing.T) {
ms := &MasterServer{
Cluster: cluster.NewCluster(),
LockRingManager: cluster.NewLockRingManager(nil),
}
registered := &master_pb.KeepConnectedRequest{ClientType: cluster.FilerType, FilerGroup: "group-a"}
register := func(address pb.ServerAddress) {
ms.Cluster.AddClusterNode(registered.FilerGroup, registered.ClientType, "", "", address, "")
ms.updateLockRing(registered, address)
}
ringServers := func() []string {
ms.LockRingManager.FlushPending("group-a")
return ms.LockRingManager.GetServers("group-a")
}
register("filer0:8888")
register("filer1:8888")
register("filer0:8888")
ms.removeClusterNode(registered, "filer0:8888")
assert.True(t, ms.Cluster.IsKnownNode(cluster.FilerType, "filer0:8888"))
assert.ElementsMatch(t, []string{"filer0:8888", "filer1:8888"}, ringServers())
ms.removeClusterNode(registered, "filer0:8888")
assert.False(t, ms.Cluster.IsKnownNode(cluster.FilerType, "filer0:8888"))
assert.ElementsMatch(t, []string{"filer1:8888"}, ringServers())
}
// A leaving filer's reconnect can register before the master ends its broken
// stream; the filer must leave the ring without waiting for either stream.
func TestLeavingFilerReconnectLeavesLockRing(t *testing.T) {
ms := &MasterServer{
Cluster: cluster.NewCluster(),
LockRingManager: cluster.NewLockRingManager(nil),
}
registered := &master_pb.KeepConnectedRequest{ClientType: cluster.FilerType, FilerGroup: "group-a"}
leaving := &master_pb.KeepConnectedRequest{ClientType: cluster.FilerType, FilerGroup: "group-a", LeaveLockRing: true}
register := func(req *master_pb.KeepConnectedRequest, address pb.ServerAddress) {
ms.Cluster.AddClusterNode(req.FilerGroup, req.ClientType, "", "", address, "")
ms.updateLockRing(req, address)
}
ringServers := func() []string {
ms.LockRingManager.FlushPending("group-a")
return ms.LockRingManager.GetServers("group-a")
}
register(registered, "filer0:8888")
register(registered, "filer1:8888")
register(leaving, "filer0:8888")
assert.ElementsMatch(t, []string{"filer1:8888"}, ringServers())
ms.removeClusterNode(registered, "filer0:8888")
assert.True(t, ms.Cluster.IsKnownNode(cluster.FilerType, "filer0:8888"))
assert.ElementsMatch(t, []string{"filer1:8888"}, ringServers())
ms.removeClusterNode(leaving, "filer0:8888")
assert.False(t, ms.Cluster.IsKnownNode(cluster.FilerType, "filer0:8888"))
assert.ElementsMatch(t, []string{"filer1:8888"}, ringServers())
}
// A filer that left the ring and is replaced before its stream ends must not
// take the replacement out of the ring with it.
func TestLeftFilerStreamEndKeepsReplacementInLockRing(t *testing.T) {
ms := &MasterServer{
Cluster: cluster.NewCluster(),
LockRingManager: cluster.NewLockRingManager(nil),
}
registered := &master_pb.KeepConnectedRequest{ClientType: cluster.FilerType, FilerGroup: "group-a"}
for _, address := range []pb.ServerAddress{"filer0:8888", "filer1:8888"} {
ms.Cluster.AddClusterNode(registered.FilerGroup, registered.ClientType, "", "", address, "")
ms.LockRingManager.AddServer(cluster.FilerGroupName(registered.FilerGroup), address)
}
ms.onKeepConnectedMessage(registered, "filer0:8888", &master_pb.KeepConnectedRequest{LeaveLockRing: true})
ms.LockRingManager.FlushPending("group-a")
assert.ElementsMatch(t, []string{"filer1:8888"}, ms.LockRingManager.GetServers("group-a"))
ms.Cluster.AddClusterNode(registered.FilerGroup, registered.ClientType, "", "", "filer0:8888", "")
ms.LockRingManager.AddServer(cluster.FilerGroupName(registered.FilerGroup), "filer0:8888")
ms.removeClusterNode(registered, "filer0:8888")
ms.LockRingManager.FlushPending("group-a")
assert.ElementsMatch(t, []string{"filer0:8888", "filer1:8888"}, ms.LockRingManager.GetServers("group-a"))
}
func TestInitialLockRingUpdateSkipsNonFilers(t *testing.T) {
ms := &MasterServer{
LockRingManager: cluster.NewLockRingManager(nil),
}
ms.LockRingManager.AddServer("group-a", "filer1:8888")
ms.LockRingManager.FlushPending("group-a")
assert.Nil(t, ms.initialLockRingUpdate(cluster.VectorType, "group-a"))
}
func TestInitialLockRingUpdateReachesLockClients(t *testing.T) {
ms := &MasterServer{
LockRingManager: cluster.NewLockRingManager(nil),
}
ms.LockRingManager.AddServer("group-a", "filer1:8888")
ms.LockRingManager.FlushPending("group-a")
for _, clientType := range []string{cluster.S3Type, cluster.MountType, cluster.BrokerType} {
resp := ms.initialLockRingUpdate(clientType, "group-a")
require.NotNil(t, resp, clientType)
assert.Equal(t, []string{"filer1:8888"}, resp.LockRingUpdate.Servers, clientType)
}
}
// TestReconnectedClientSurvivesOldHandlerCleanup covers a client reconnecting
// KeepConnected under the same name before the old handler has exited: the old
// handler's deferred cleanup must not close the channel the reconnected stream
// registered, or that stream reads nil from its closed channel forever and
// floods the client with empty responses.
func TestReconnectedClientSurvivesOldHandlerCleanup(t *testing.T) {
ms := &MasterServer{
clientChans: make(map[string]chan *master_pb.KeepConnectedResponse),
}
clientName, oldChan := ms.addClient("", cluster.MasterType, "peer:19333")
_, newChan := ms.addClient("", cluster.MasterType, "peer:19333")
// the old handler's deferred cleanup runs after the reconnect registered
ms.deleteClient(clientName, oldChan)
// the old channel is closed so its drain goroutine can exit
select {
case _, ok := <-oldChan:
assert.False(t, ok, "old channel should be closed")
default:
t.Fatal("old channel left open")
}
// the reconnected stream's channel is untouched and still receives broadcasts
ms.broadcastToClients(&master_pb.KeepConnectedResponse{
VolumeLocation: &master_pb.VolumeLocation{Url: "volume-a:8080"},
})
select {
case message, ok := <-newChan:
require.True(t, ok, "reconnected client's channel was closed by the old handler's cleanup")
require.NotNil(t, message.GetVolumeLocation())
default:
t.Fatal("no broadcast reached the reconnected client")
}
// the reconnected handler's own cleanup still removes the registration
ms.deleteClient(clientName, newChan)
ms.clientChansLock.RLock()
_, found := ms.clientChans[clientName]
ms.clientChansLock.RUnlock()
assert.False(t, found)
}
// TestBroadcastVolumeLocationsToClients verifies grown volume locations are sent to registered clients.
func TestBroadcastVolumeLocationsToClients(t *testing.T) {
clientChan := make(chan *master_pb.KeepConnectedResponse, 2)
ms := &MasterServer{
clientChans: map[string]chan *master_pb.KeepConnectedResponse{
"default.filer@127.0.0.1:8888": clientChan,
},
}
ms.broadcastVolumeLocationsToClients([]*master_pb.VolumeLocation{
{Url: "volume-a:8080", NewVids: []uint32{7}},
{Url: "volume-b:8080", NewVids: []uint32{8}},
})
var first *master_pb.KeepConnectedResponse
select {
case first = <-clientChan:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for first broadcast")
}
require.NotNil(t, first.GetVolumeLocation())
assert.Equal(t, []uint32{7}, first.GetVolumeLocation().GetNewVids())
assert.Equal(t, "volume-a:8080", first.GetVolumeLocation().GetUrl())
var second *master_pb.KeepConnectedResponse
select {
case second = <-clientChan:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for second broadcast")
}
require.NotNil(t, second.GetVolumeLocation())
assert.Equal(t, []uint32{8}, second.GetVolumeLocation().GetNewVids())
assert.Equal(t, "volume-b:8080", second.GetVolumeLocation().GetUrl())
}