Files
seaweedfs/weed/mq/topic/replicator.go
T
Chris Lu d63c225d78 mq: replicate each partition to a follower and hand it to a new pair when one is lost (#13203)
* mq: carry offsets, epoch and heartbeats on the follow stream

The follow stream sent the publisher's raw message, so the follower
could not keep the leader's offsets, and nothing named the generation
or told a quiet leader from a dead one. The stream now carries log
entries with their offsets, the epoch and leader in its init,
heartbeats, and the flushed offset; acks report the follower's offset.
EndPartitionGeneration lets a broker of a broken pair report it to the
balancer.

* mq broker: hand a partition's fence between generations

A fence could only be taken by the next leader, at once. A pair that
breaks needs more: the survivor must keep persisting what it holds
before a new leader writes, and a follower must be able to take the
fence from a leader it lost. The holder can now renew the fence,
which tells a new leader it is still persisting, and seal it when it
is done; a new leader takes an earlier generation's fence once it is
sealed or left unrenewed for 30 seconds. Within one generation the
fence moves only from the leader to its follower, and a sealed one
stays sealed.

Sealing writes a new token, so a follower that read the fence before
the seal cannot take it over after; a plain renewal keeps the token,
so flushes under way still match. A stale leader that reloads seals
its old fence once its last flush lands, so the reload does not wait.

* mq broker: ack a publish once the follower holds it

The leader acked a publish as soon as it was in its own memory, sent
the follower the raw message without its offset, learned its follower
only from the publisher's init message (which the Kafka gateway never
sets), and wrote to one follower stream from every publisher at once.

The leader now takes its follower from the partition's assignment when
it loads the partition and streams each entry, with its offset, from
one sender goroutine in offset order; a publish is acked once the
follower acks that offset. Heartbeats and a 5 second silence limit
tell a lost follower from a quiet one, and a broken pair answers the
publisher GENERATION_ENDED. The follower holds the entries the leader
has not stored yet, drops them as flush notices arrive, and the leader
closes the stream gracefully once it has stored everything, when the
partition unloads. A partition with no follower acks from memory as
before.

* mq: give a partition whose pair broke a new pair

Nothing reassigned a partition whose leader or follower was lost while
the other half lived on: the balancer only replaced brokers that had
left its broker set, and only on its own schedule. A broker of a
broken pair now reports the epoch with EndPartitionGeneration, and the
balancer assigns a new pair and the next epoch, preferring brokers
outside the old pair. A report for an epoch that already moved on is
ignored, so both halves can report, and reassignments are serialized.

* mq broker: a leader that loses its follower stores what it holds and ends the generation

When the follower stream broke, the leader kept serving alone, acking
from memory again. A broken pair now ends the generation on the leader:
it stops taking publishes, renews its fence so a new leader waits,
stores everything it holds under that fence, seals it, and reports the
epoch so the balancer assigns a new pair. A follower that cannot be
reached when the partition loads ends the generation the same way.

* mq broker: a follower takes over from a leader it lost

When the follow stream broke, the follower dropped what it held, so
entries the leader had acked but not stored were gone with it. The
follower now moves the fence from the lost leader to itself, unless
the leader sealed it first, reads what is already stored, stores the
entries above that, seals the fence and reports the generation ended.
The leader acks only what the follower holds, so every acked entry is
stored once, and a leader still writing is fenced out.

* mq broker: reload topic.conf when the balancer names this broker leader

A broker made leader by a reassignment could still hold the previous
topic.conf in its 30 second cache, so it either found no assignment
for itself or tried to take the fence with the old epoch, and refused
publishes until the cache expired. A publish that finds either now
drops the cached config and loads the partition again.

* mq broker: stop routing subscriptions through the follower

A subscription dialed the follower named in its init and advanced its
committed position only while that follower stream existed, so a
partition without a follower never saved a consumer position, and a
dead follower failed every subscription. The leader now tracks the
position itself and saves it when the subscriber leaves.

* mq broker: tell a partition's leader its follower when assigning it

The balancer created a topic's partitions on their leaders with only
the partition and epoch, so a partition made that way never knew its
follower and acked from memory. It now sends the whole assignment. Only
the named leader creates the partition; the follower learns of it from
the leader's follow stream, so the old forward of the leader's request
to the follower, which would have made the follower take the fence
too, is gone.

* mq broker: report an ended generation until a settled balancer takes it

A broker reported a broken pair once. When the lost broker was also
the balancer, the report failed and the partition stayed at a sealed
epoch nobody would serve. The report is now retried with backoff until
a balancer takes it, and a balancer takes reports only after its settle
window, so the new pair is picked from every live broker rather than
the few that reconnected first.

* mq: describe the replicated pair in the failover notes

* mq broker: break a pair whose follower stopped reading

The follower's silence was checked in the loop that sends to it, so
once a send blocked on a follower that stopped reading but kept its
connection, nothing checked again and publishers waited on acks that
never came. The check now runs on its own and cancels the stream.

* mq broker: a follower that cannot ack its leader takes over

An ack that failed to send ended the follow stream with an error and
dropped the follower's entries, though they may include messages the
leader had already acked to publishers. A failed ack now takes over
the partition, as a broken receive does.

* mq broker: retry a takeover through filer errors

A follower taking over gave up on the first failed fence or offset
read, dropping the entries its lost leader had not stored, which may
be the only copy left. It now retries until the fence has moved on or
the broker stops.

* mq broker: keep the fence renewed while a survivor persists

A leader that lost its follower renewed its fence once before
storing what it held, and a follower taking over not at all after
moving the fence, so a store that ran past 30 seconds let a new
leader take the unsealed fence, refusing the survivor's write and
dropping what it held. Both now renew every 10 seconds until they
seal.

* mq broker: leave the follower its copy when a retiring leader dropped a flush

A retiring leader closed its follow stream gracefully once its buffer
shut down, which tells the follower everything is stored, but a flush
that failed until shutdown is dropped. With the filer unavailable both
copies of acked messages went. The stream is now closed only when the
flushed offset reached the last one assigned; otherwise it is broken,
so the follower takes over and stores its copy.

* mq broker: order every topic.conf read-modify-write on the balancer

Only the generation handoff held a lock around its read and save of
topic.conf, so a concurrent ConfigureTopic or assignment refresh that
read the old assignments could save them back over the new pair,
after the reporter had been told the generation was taken. All of
them now take the same lock.

* mq broker: stamp a fence write when it lands, not when it was first tried

A fence write took its mtime before retrying, so a renewal that
landed after a long run of store errors was already older than the
seal wait, and a new leader could take the fence from a survivor
still persisting. Each attempt now stamps the time it is sent.

* mq broker: watch a leader's follower only once its partition is listed

The lost-follower watch started before the partition was registered,
so a pair that broke in that gap ended its generation while the
partition could not be removed, and the partition was then registered
and served after its fence was sealed. Both load paths now start the
watch after registering it.

* mq/kafka: answer a produce on an ended generation with NOT_LEADER_OR_FOLLOWER

A partition whose pair broke answers publishes with GenerationEnded
while the balancer hands it to a new pair, which the gateway mapped
to UNKNOWN_SERVER_ERROR: it kept the session and Kafka clients did not
refresh their metadata. It now maps to NOT_LEADER_OR_FOLLOWER, so the
gateway drops the session and clients look the leader up again.

* mq broker: take a stale fence only if its holder has not renewed it since

A new leader judged an earlier generation's unsealed fence stale by
its mtime, then wrote under the token alone. A renewal keeps the token
and moves only the mtime, so a holder that renewed in between, still
persisting what it held, lost the fence and the write that followed.
Taking a fence judged stale now requires the entry as it was read.

* mq broker: bound the seal when a leader cannot reach its follower

A leader whose replica failed to start sealed its fence and reported
the generation under the broker's access lock with no deadline, and a
fence write retries until it lands, so a filer that kept failing held
every partition operation on the broker. The seal now gives up after
the fence take timeout and the generation is reported regardless.

* mq broker: bound each report of an ended generation

A generation report called the balancer with no deadline, so a
balancer that accepted the call and stopped answering held the retry
loop and the partition stayed unassigned. Each attempt now gives up
after 30 seconds and is retried; a repeat after a save that landed
finds the epoch moved on and returns without writing.
2026-12-01 00:56:20 -08:00

230 lines
5.8 KiB
Go

package topic
import (
"context"
"errors"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"google.golang.org/grpc"
)
const (
replicaHeartbeat = time.Second
// replicaTimeout is how long a leader hears nothing from its follower before
// it takes the pair for broken.
replicaTimeout = 5 * time.Second
replicaQueue = 4096
)
var (
// ErrReplicaClosed is the error a replicator reports after a graceful close.
ErrReplicaClosed = errors.New("replica closed")
// ErrReplicaAbandoned is reported after Abandon, which leaves the follower to store its copy.
ErrReplicaAbandoned = errors.New("replica abandoned with unstored entries")
)
// Replicator streams a leader partition's entries to its follower, in offset
// order, and tracks the highest offset the follower holds.
type Replicator struct {
Follower string
conn *grpc.ClientConn
stream mq_pb.SeaweedMessaging_PublishFollowMeClient
cancel context.CancelFunc
sendCh chan *mq_pb.PublishFollowMeRequest
closing atomic.Bool
mu sync.Mutex
acked int64
err error
changed chan struct{} // closed and replaced whenever acked or err changes
broken chan struct{}
lastHeard atomic.Int64
}
func StartReplicator(follower string, dialOption grpc.DialOption, init *mq_pb.PublishFollowMeRequest_InitMessage) (*Replicator, error) {
ctx, cancel := context.WithCancel(context.Background())
conn, err := pb.GrpcDial(ctx, follower, false, dialOption)
if err != nil {
cancel()
return nil, fmt.Errorf("dial follower %s: %w", follower, err)
}
stream, err := mq_pb.NewSeaweedMessagingClient(conn).PublishFollowMe(ctx)
if err == nil {
err = stream.Send(&mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Init{Init: init}})
}
if err != nil {
cancel()
conn.Close()
return nil, fmt.Errorf("follow stream to %s: %w", follower, err)
}
r := &Replicator{
Follower: follower,
conn: conn,
stream: stream,
cancel: cancel,
sendCh: make(chan *mq_pb.PublishFollowMeRequest, replicaQueue),
acked: -1,
changed: make(chan struct{}),
broken: make(chan struct{}),
}
r.lastHeard.Store(time.Now().UnixNano())
go r.sendLoop()
go r.recvLoop()
go r.watchSilence()
return r, nil
}
// Send queues an entry for the follower. Callers queue entries in offset order.
func (r *Replicator) Send(entry *filer_pb.LogEntry) error {
select {
case r.sendCh <- &mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Entry{Entry: entry}}:
return nil
case <-r.broken:
return r.Err()
}
}
// Flushed tells the follower every entry up to offset is stored. It never blocks:
// a later notice covers a dropped one.
func (r *Replicator) Flushed(offset int64) {
select {
case r.sendCh <- &mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Flush{Flush: &mq_pb.PublishFollowMeRequest_FlushMessage{Offset: offset}}}:
default:
}
}
// WaitAcked returns once the follower holds offset, or the error that broke the pair.
func (r *Replicator) WaitAcked(offset int64) error {
for {
r.mu.Lock()
acked, err, changed := r.acked, r.err, r.changed
r.mu.Unlock()
if acked >= offset {
return nil
}
if err != nil {
return err
}
<-changed
}
}
// Broken is closed once the pair breaks or the replicator closes.
func (r *Replicator) Broken() <-chan struct{} {
return r.broken
}
func (r *Replicator) Err() error {
r.mu.Lock()
defer r.mu.Unlock()
return r.err
}
// Close ends the stream after every queued entry, telling the follower the
// leader stored everything it holds.
func (r *Replicator) Close() {
if r.closing.Swap(true) {
return
}
select {
case r.sendCh <- &mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Close{Close: &mq_pb.PublishFollowMeRequest_CloseMessage{}}}:
case <-r.broken:
}
select {
case <-r.broken:
case <-time.After(replicaTimeout):
r.fail(ErrReplicaClosed)
}
}
// Abandon breaks the stream without closing it, so the follower takes the
// partition over and stores what this leader could not.
func (r *Replicator) Abandon() {
r.fail(ErrReplicaAbandoned)
}
func (r *Replicator) sendLoop() {
ticker := time.NewTicker(replicaHeartbeat)
defer ticker.Stop()
heartbeat := &mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Heartbeat{Heartbeat: &mq_pb.PublishFollowMeRequest_HeartbeatMessage{}}}
for {
var req *mq_pb.PublishFollowMeRequest
select {
case <-r.broken:
return
case req = <-r.sendCh:
case <-ticker.C:
req = heartbeat
}
if err := r.stream.Send(req); err != nil {
r.fail(fmt.Errorf("send to follower %s: %w", r.Follower, err))
return
}
if req.GetClose() != nil {
r.stream.CloseSend()
}
}
}
// watchSilence runs apart from sendLoop, so a send blocked on a follower that
// stopped reading still breaks the pair.
func (r *Replicator) watchSilence() {
ticker := time.NewTicker(replicaHeartbeat)
defer ticker.Stop()
for {
select {
case <-r.broken:
return
case <-ticker.C:
if silent := time.Since(time.Unix(0, r.lastHeard.Load())); silent > replicaTimeout {
r.fail(fmt.Errorf("follower %s silent for %v", r.Follower, silent))
return
}
}
}
}
func (r *Replicator) recvLoop() {
for {
resp, err := r.stream.Recv()
if err != nil {
if r.closing.Load() && errors.Is(err, io.EOF) {
r.fail(ErrReplicaClosed)
} else {
r.fail(fmt.Errorf("follower %s: %w", r.Follower, err))
}
return
}
r.lastHeard.Store(time.Now().UnixNano())
r.mu.Lock()
if resp.AckOffset > r.acked {
r.acked = resp.AckOffset
close(r.changed)
r.changed = make(chan struct{})
}
r.mu.Unlock()
}
}
func (r *Replicator) fail(err error) {
r.mu.Lock()
if r.err == nil {
r.err = err
close(r.changed)
r.changed = make(chan struct{})
close(r.broken)
}
r.mu.Unlock()
r.cancel()
r.conn.Close()
}