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.
This commit is contained in:
Chris Lu authored and GitHub committed 2026-12-01 00:56:20 -08:00
1 parent 5c5e282787
commit d63c225d78
31 files changed
+2056 -764

No files matched your search

+5 -2
View File
@@ -57,8 +57,11 @@ A partition's files are written only by the broker holding the partition's fence
leadership cannot add to them. When that broker fails, the partition is assigned to another broker, which takes the
fence at a new epoch and continues from the files.
A follower keeps the messages it receives in memory and does not write them. Until followers can take over a failed
broker's partition, messages it acknowledged but had not flushed yet are lost when it fails.
Each partition has a leader and a follower on two brokers. The leader acknowledges a message once the follower holds
it, and the follower keeps what the leader has not flushed yet in memory. If either is lost, the survivor writes what
it holds, seals the fence and reports the generation ended; the balancer then assigns a new pair at the next epoch,
and publishers resend what was not acknowledged. A partition placed while only one broker is live has no follower,
and messages it acknowledged but had not flushed yet are lost when that broker fails.
## Auto Split or Merge
+6
View File
@@ -26,6 +26,8 @@ const (
BrokerErrorPublisherNotFound int32 = 100
BrokerErrorConnectionFailed int32 = 101
BrokerErrorFollowerConnectionFailed int32 = 102
// the partition's leader/follower pair broke; publishers look it up again and resend
BrokerErrorGenerationEnded int32 = 103
)
// BrokerErrorInfo contains metadata about a broker error
@@ -106,6 +108,10 @@ var BrokerErrors = map[int32]BrokerErrorInfo{
Code: BrokerErrorConnectionFailed, Name: "CONNECTION_FAILED",
Description: "Connection failed", KafkaCode: 13, // NETWORK_EXCEPTION
},
BrokerErrorGenerationEnded: {
Code: BrokerErrorGenerationEnded, Name: "GENERATION_ENDED",
Description: "Partition generation ended; look up its new leader", KafkaCode: 6,
},
BrokerErrorFollowerConnectionFailed: {
Code: BrokerErrorFollowerConnectionFailed, Name: "FOLLOWER_CONNECTION_FAILED",
Description: "Failed to connect to follower brokers", KafkaCode: 13, // NETWORK_EXCEPTION
+9 -26
View File
@@ -46,8 +46,10 @@ func (b *MessageQueueBroker) AssignTopicPartitions(c context.Context, request *m
b.accessLock.Unlock()
return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress())
}
if localPartition == nil {
localPartition, genErr := b.newLeaderPartition(t, partition, assignment.Epoch)
// a follower learns of its partition from the leader's follow stream
isLeader := assignment.LeaderBroker == "" || pb.ServerAddress(assignment.LeaderBroker).Equals(b.option.BrokerAddress())
if isLeader && localPartition == nil {
localPartition, genErr := b.newLeaderPartition(t, partition, assignment)
if genErr != nil {
b.accessLock.Unlock()
return nil, status.Errorf(codes.Unavailable, "%v", genErr)
@@ -57,26 +59,12 @@ func (b *MessageQueueBroker) AssignTopicPartitions(c context.Context, request *m
b.accessLock.Unlock()
return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress())
}
go b.watchReplica(t, partition, localPartition, assignment.Epoch)
}
}
b.accessLock.Unlock()
}
// if is leader, notify the followers to drain existing topic partition subscriptions
if request.IsLeader {
for _, brokerPartition := range request.BrokerPartitionAssignments {
if follower := brokerPartition.FollowerBroker; follower != "" {
err := pb.WithBrokerGrpcClient(false, follower, b.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error {
_, err := client.AssignTopicPartitions(context.Background(), request)
return err
})
if err != nil {
return ret, err
}
}
}
}
return ret, nil
}
@@ -91,15 +79,10 @@ func (b *MessageQueueBroker) assignTopicPartitionsToBrokers(ctx context.Context,
defer wg.Done()
if doCreateErr := b.withBrokerClient(false, pb.ServerAddress(bpa.LeaderBroker), func(client mq_pb.SeaweedMessagingClient) error {
_, doCreateErr := client.AssignTopicPartitions(ctx, &mq_pb.AssignTopicPartitionsRequest{
Topic: t,
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{
{
Partition: bpa.Partition,
Epoch: bpa.Epoch,
},
},
IsLeader: true,
IsDraining: !isAdd,
Topic: t,
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{bpa},
IsLeader: true,
IsDraining: !isAdd,
})
if doCreateErr != nil {
if !isAdd {
+2
View File
@@ -36,6 +36,8 @@ func (b *MessageQueueBroker) ConfigureTopic(ctx context.Context, request *mq_pb.
}
}
b.topicConfLock.Lock()
defer b.topicConfLock.Unlock()
t := topic.FromPbTopic(request.Topic)
var readErr, assignErr error
resp, readErr = b.fca.ReadTopicConfFromFiler(t)
+126
View File
@@ -0,0 +1,126 @@
package broker
import (
"context"
"errors"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// EndPartitionGeneration gives a partition whose leader/follower pair broke a new
// pair. A report for an epoch that already moved on is ignored, so both halves of
// a broken pair can report it.
func (b *MessageQueueBroker) EndPartitionGeneration(ctx context.Context, req *mq_pb.EndPartitionGenerationRequest) (resp *mq_pb.EndPartitionGenerationResponse, err error) {
if !b.isLockOwner() {
err = b.withBalancerClient(func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.EndPartitionGeneration(ctx, req)
return err
})
return resp, err
}
if !b.balancerSettled() {
// a new pair is picked from the brokers it has heard from, so wait until all have reconnected
return nil, status.Error(codes.Unavailable, "broker balancer is still settling")
}
b.topicConfLock.Lock()
defer b.topicConfLock.Unlock()
t := topic.FromPbTopic(req.Topic)
conf, err := b.fca.ReadTopicConfFromFiler(t)
if err != nil {
return nil, fmt.Errorf("read topic %s: %w", t, err)
}
for _, assignment := range conf.BrokerPartitionAssignments {
if !b.partitionsMatch(assignment.Partition, req.Partition) {
continue
}
if assignment.Epoch != req.Epoch {
return &mq_pb.EndPartitionGenerationResponse{}, nil
}
previousLeader, previousFollower := assignment.LeaderBroker, assignment.FollowerBroker
pub_balancer.ReassignPartition(b.PubBalancer.Brokers, assignment)
if err := b.fca.SaveTopicConfToFiler(t, conf); err != nil {
return nil, fmt.Errorf("save topic %s: %w", t, err)
}
b.invalidateTopicCache(t)
glog.V(0).Infof("topic %s partition %v epoch %d ended (reported by %s): %s/%s -> %s/%s at epoch %d", t, topic.FromPbPartition(req.Partition), req.Epoch, req.Broker,
previousLeader, previousFollower, assignment.LeaderBroker, assignment.FollowerBroker, assignment.Epoch)
return &mq_pb.EndPartitionGenerationResponse{}, nil
}
return nil, status.Errorf(codes.NotFound, "topic %s has no partition %v", t, topic.FromPbPartition(req.Partition))
}
// watchReplica ends this leader's generation when its follower is lost. It starts
// once lp is registered, so the generation never ends under an unlisted partition.
func (b *MessageQueueBroker) watchReplica(t topic.Topic, p topic.Partition, lp *topic.LocalPartition, epoch int64) {
if lp.Replica == nil {
return
}
<-lp.Replica.Broken()
if err := lp.Replica.Err(); errors.Is(err, topic.ErrReplicaClosed) || errors.Is(err, topic.ErrReplicaAbandoned) {
return
}
glog.Warningf("topic %s partition %v epoch %d lost follower %s: %v", t, p, epoch, lp.Follower, lp.Replica.Err())
b.endLeaderGeneration(t, lp, epoch)
}
// endLeaderGeneration stores what this leader holds, seals its fence and reports
// the generation ended. The fence is kept renewed meanwhile, so a new leader waits.
func (b *MessageQueueBroker) endLeaderGeneration(t topic.Topic, lp *topic.LocalPartition, epoch int64) {
ctx := context.Background()
p, fence := lp.Partition, lp.Fence
stopRenewing := b.keepFenceRenewed(fence)
b.localTopicManager.RemoveLocalPartition(t, lp)
b.localTopicManager.WaitRetired(ctx, t, p)
stopRenewing()
b.sealAndReportGeneration(ctx, t, p, fence, epoch)
}
func (b *MessageQueueBroker) sealAndReportGeneration(ctx context.Context, t topic.Topic, p topic.Partition, fence *topic.PartitionFence, epoch int64) {
if fence != nil && !fence.IsLost() {
if err := b.renewPartitionFence(ctx, fence, true); err != nil {
glog.Warningf("seal topic %s partition %v epoch %d: %v", t, p, epoch, err)
}
}
go b.reportGenerationEnded(t, p, epoch)
}
const generationReportTimeout = 30 * time.Second
// reportGenerationEnded retries until a balancer takes the report: the lost broker
// may have been the balancer, and the partition stays unserved until one does.
func (b *MessageQueueBroker) reportGenerationEnded(t topic.Topic, p topic.Partition, epoch int64) {
req := &mq_pb.EndPartitionGenerationRequest{
Topic: t.ToPbTopic(),
Partition: p.ToPbPartition(),
Epoch: epoch,
Broker: string(b.option.BrokerAddress()),
}
parent := context.Background()
if b.ctx != nil {
parent = b.ctx
}
for wait := time.Second; ; wait = min(2*wait, 10*time.Second) {
// a balancer that stops answering must not hold the retries; a repeat after a
// save that landed finds the epoch moved on and returns without writing
ctx, cancel := context.WithTimeout(parent, generationReportTimeout)
_, err := b.EndPartitionGeneration(ctx, req)
cancel()
if err == nil {
return
}
glog.Warningf("report topic %s partition %v epoch %d ended: %v", t, p, epoch, err)
select {
case <-parent.Done():
return
case <-time.After(wait):
}
}
}
+2
View File
@@ -289,6 +289,8 @@ func (b *MessageQueueBroker) GetTopicConfiguration(ctx context.Context, request
var conf *mq_pb.ConfigureTopicResponse
var createdAtNs, modifiedAtNs int64
b.topicConfLock.Lock()
defer b.topicConfLock.Unlock()
if conf, createdAtNs, modifiedAtNs, err = b.fca.ReadTopicConfFromFilerWithMetadata(t); err != nil {
glog.V(0).Infof("get topic configuration %s: %v", request.Topic, err)
return nil, fmt.Errorf("failed to read topic configuration: %w", err)
+21 -48
View File
@@ -7,8 +7,6 @@ import (
"io"
"math/rand/v2"
"net"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
@@ -72,10 +70,19 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
// get or generate a local partition
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
localTopicPartition, getOrGenErr := b.GetOrGenerateLocalPartition(t, p)
if localTopicPartition == nil && (getOrGenErr == nil || errors.Is(getOrGenErr, errFenceLost)) {
// the balancer named this broker from a newer topic.conf than the cached one
b.invalidateTopicCache(t)
localTopicPartition, getOrGenErr = b.GetOrGenerateLocalPartition(t, p)
}
if errors.Is(getOrGenErr, errFenceLost) {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, getOrGenErr.Error())
return stream.Send(response)
}
if errors.Is(getOrGenErr, errGenerationEnded) {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, getOrGenErr.Error())
return stream.Send(response)
}
if getOrGenErr != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorTopicNotFound, fmt.Sprintf("topic %v not found: %v", t, getOrGenErr))
glog.Errorf("topic %v not found: %v", t, getOrGenErr)
@@ -90,11 +97,8 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is fenced by another broker", t, p))
return stream.Send(response)
}
// connect to follower brokers
if followerErr := localTopicPartition.MaybeConnectToFollowers(initMessage, b.grpcDialOption); followerErr != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorFollowerConnectionFailed, followerErr.Error())
glog.Errorf("MaybeConnectToFollowers: %v", followerErr)
if replica := localTopicPartition.Replica; replica != nil && replica.Err() != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, fmt.Sprintf("topic %v partition %v: %v", t, p, replica.Err()))
return stream.Send(response)
}
@@ -103,43 +107,6 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
publisher := topic.NewLocalPublisher()
localTopicPartition.Publishers.AddPublisher(clientName, publisher)
// DISABLED: Periodic ack goroutine not needed with immediate per-message acks
// Immediate acks provide correct offset information for Kafka Gateway
var receivedSequence, acknowledgedSequence int64
var isClosed bool
if false {
ackInterval := int64(1)
if initMessage.AckInterval > 0 {
ackInterval = int64(initMessage.AckInterval)
}
go func() {
defer func() {
// println("stop sending ack to publisher", initMessage.PublisherName)
}()
lastAckTime := time.Now()
for !isClosed {
receivedSequence = atomic.LoadInt64(&localTopicPartition.AckTsNs)
if acknowledgedSequence < receivedSequence && (receivedSequence-acknowledgedSequence >= ackInterval || time.Since(lastAckTime) > 100*time.Millisecond) {
acknowledgedSequence = receivedSequence
response := &mq_pb.PublishMessageResponse{
AckTsNs: acknowledgedSequence,
}
if err := stream.Send(response); err != nil {
glog.Errorf("Error sending response %v: %v", response, err)
}
// Update acknowledged offset for this publisher
publisher.UpdateAckedOffset(acknowledgedSequence)
// println("sent ack", acknowledgedSequence, "=>", initMessage.PublisherName)
lastAckTime = time.Now()
} else {
time.Sleep(10 * time.Millisecond) // Reduced from 1s to 10ms for faster acknowledgments
}
}
}()
}
defer func() {
// remove the publisher
localTopicPartition.Publishers.RemovePublisher(clientName)
@@ -153,10 +120,6 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
// send a hello message
stream.Send(&mq_pb.PublishMessageResponse{})
defer func() {
isClosed = true
}()
// process each published messages
for {
// receive a message
@@ -199,6 +162,16 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
}
assignedOffset, err := localTopicPartition.PublishWithOffset(dataMessage)
if replica := localTopicPartition.Replica; replica != nil {
// acked only once the follower holds it too
if err == nil {
err = replica.WaitAcked(assignedOffset)
}
if replicaErr := replica.Err(); replicaErr != nil {
response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorGenerationEnded, fmt.Sprintf("topic %v partition %v: %v", t, p, replicaErr))
return stream.Send(response)
}
}
if err != nil {
return fmt.Errorf("topic %v partition %v publish error: %w", initMessage.Topic, initMessage.Partition, err)
}
+86 -121
View File
@@ -2,150 +2,115 @@ package broker
import (
"context"
"encoding/binary"
"fmt"
"io"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util/buffered_queue"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
type memBuffer struct {
buf []byte
startTime time.Time
stopTime time.Time
}
func (b *MessageQueueBroker) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) (err error) {
var req *mq_pb.PublishFollowMeRequest
req, err = stream.Recv()
// PublishFollowMe holds a leader's entries that are not stored yet, acking each,
// until the leader closes the stream after storing everything.
func (b *MessageQueueBroker) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) error {
req, err := stream.Recv()
if err != nil {
return err
}
initMessage := req.GetInit()
if initMessage == nil {
init := req.GetInit()
if init == nil {
return fmt.Errorf("missing init message")
}
t, p := topic.FromPbTopic(init.Topic), topic.FromPbPartition(init.Partition)
// create an in-memory queue of buffered messages
inMemoryBuffers := buffered_queue.NewBufferedQueue[memBuffer](4)
logBuffer := b.buildFollowerLogBuffer(inMemoryBuffers)
lastFlushTsNs := time.Now().UnixNano()
// follow each published messages
var held []*filer_pb.LogEntry
acked := int64(-1)
for {
// receive a message
req, err = stream.Recv()
req, err := stream.Recv()
if err != nil {
if err == io.EOF {
err = nil
break
}
glog.V(0).Infof("topic %v partition %v publish stream error: %v", initMessage.Topic, initMessage.Partition, err)
break
// the leader went without closing the stream, so it may not have stored these
glog.Warningf("follow stream of %v %v from %s at epoch %d broke with %d unstored entries: %v", t, p, init.Leader, init.Epoch, len(held), err)
b.takeOverPartition(t, p, init, held)
return nil
}
// Process the received message
if dataMessage := req.GetData(); dataMessage != nil {
// TODO: change this to DataMessage
// log the message
if addErr := logBuffer.AddToBuffer(dataMessage); addErr != nil {
err = fmt.Errorf("failed to add message to log buffer: %w", addErr)
glog.Errorf("Failed to add message to log buffer: %v", addErr)
break
}
// send back the ack
if err := stream.Send(&mq_pb.PublishFollowMeResponse{
AckTsNs: dataMessage.TsNs,
}); err != nil {
glog.Errorf("Error sending response %v: %v", dataMessage, err)
}
// println("ack", string(dataMessage.Key), dataMessage.TsNs)
} else if closeMessage := req.GetClose(); closeMessage != nil {
glog.V(0).Infof("topic %v partition %v publish stream closed: %v", initMessage.Topic, initMessage.Partition, closeMessage)
break
} else if flushMessage := req.GetFlush(); flushMessage != nil {
glog.V(0).Infof("topic %v partition %v publish stream flushed: %v", initMessage.Topic, initMessage.Partition, flushMessage)
lastFlushTsNs = flushMessage.TsNs
// drop already flushed messages
for mem, found := inMemoryBuffers.PeekHead(); found; mem, found = inMemoryBuffers.PeekHead() {
if mem.stopTime.UnixNano() <= flushMessage.TsNs {
inMemoryBuffers.Dequeue()
// println("dropping flushed messages: ", mem.startTime.UnixNano(), mem.stopTime.UnixNano(), len(mem.buf))
} else {
break
}
}
} else {
glog.Errorf("unknown message: %v", req)
}
}
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
logBuffer.ShutdownLogBuffer()
// wait until all messages are sent to inMemoryBuffers
for !logBuffer.IsAllFlushed() {
time.Sleep(113 * time.Millisecond)
}
partitionDir := topic.PartitionDir(t, p)
// flush the remaining messages
inMemoryBuffers.CloseInput()
for mem, found := inMemoryBuffers.Dequeue(); found; mem, found = inMemoryBuffers.Dequeue() {
if len(mem.buf) == 0 {
switch m := req.Message.(type) {
case *mq_pb.PublishFollowMeRequest_Entry:
held = append(held, m.Entry)
acked = m.Entry.Offset
case *mq_pb.PublishFollowMeRequest_Heartbeat:
case *mq_pb.PublishFollowMeRequest_Flush:
held = dropStored(held, m.Flush.Offset)
continue
case *mq_pb.PublishFollowMeRequest_Close:
return nil
default:
continue
}
startTime, stopTime := mem.startTime.UTC(), mem.stopTime.UTC()
if stopTime.UnixNano() <= lastFlushTsNs {
glog.V(0).Infof("dropping remaining data at %v %v", t, p)
continue
if err := stream.Send(&mq_pb.PublishFollowMeResponse{AckOffset: acked}); err != nil {
glog.Warningf("follow stream of %v %v from %s at epoch %d failed to ack with %d unstored entries: %v", t, p, init.Leader, init.Epoch, len(held), err)
b.takeOverPartition(t, p, init, held)
return nil
}
// TODO trim data earlier than lastFlushTsNs
targetFile := fmt.Sprintf("%s/%s", partitionDir, topic.LogFileName(startTime, 0))
// A follower holds no fence, so the fenced writer refuses its copy.
if err := b.writeLogFile(context.Background(), nil, targetFile, mem.buf); err != nil {
glog.Warningf("dropping remaining data at %v %v size %d: %v", t, p, len(mem.buf), err)
continue
}
glog.V(0).Infof("flushed remaining data at %v to %s size %d", mem.stopTime.UnixNano(), targetFile, len(mem.buf))
}
glog.V(0).Infof("shut down follower for %v %v", t, p)
return err
}
func (b *MessageQueueBroker) buildFollowerLogBuffer(inMemoryBuffers *buffered_queue.BufferedQueue[memBuffer]) *log_buffer.LogBuffer {
lb := log_buffer.NewLogBuffer("follower",
5*time.Second, func(logBuffer *log_buffer.LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) {
if len(buf) == 0 {
// dropStored keeps the entries above offset; held is in offset order.
func dropStored(held []*filer_pb.LogEntry, offset int64) []*filer_pb.LogEntry {
i := sort.Search(len(held), func(i int) bool { return held[i].Offset > offset })
return append([]*filer_pb.LogEntry(nil), held[i:]...)
}
// takeOverPartition moves the fence from a lost leader to this follower, stores the
// entries the leader had not, and ends the generation. Every acked entry is here,
// since the leader acks only what this follower holds.
func (b *MessageQueueBroker) takeOverPartition(t topic.Topic, p topic.Partition, init *mq_pb.PublishFollowMeRequest_InitMessage, held []*filer_pb.LogEntry) {
ctx := context.Background()
if b.ctx != nil {
ctx = b.ctx
}
// these entries may be the only copy left, so a filer error is retried until the fence moves on
var fence *topic.PartitionFence
if err := retryLogWrite(ctx, topic.PartitionFencePath(t, p), func() (err error) {
fence, err = b.takeOverPartitionFence(ctx, t, p, init.Epoch, init.Leader)
return err
}); err != nil {
glog.V(0).Infof("not taking over %v %v epoch %d: %v", t, p, init.Epoch, err)
return
}
stopRenewing := b.keepFenceRenewed(fence)
defer stopRenewing()
// with the fence moved, nothing else adds to what is stored
var highWaterMark int64
if err := retryLogWrite(ctx, topic.PartitionDir(t, p), func() (err error) {
_, highWaterMark, err = b.getOffsetRangeFromChunkMetadata(t, p)
return err
}); err != nil {
glog.Errorf("take over %v %v epoch %d: %v", t, p, init.Epoch, err)
return
}
held = dropStored(held, highWaterMark-1)
if len(held) > 0 {
var data []byte
for _, entry := range held {
encoded, err := entry.MarshalVT()
if err != nil {
glog.Errorf("take over %v %v epoch %d: %v", t, p, init.Epoch, err)
return
}
inMemoryBuffers.Enqueue(memBuffer{
// The flush callback borrows buf only until it returns.
buf: append([]byte(nil), buf...),
startTime: startTime,
stopTime: stopTime,
})
glog.V(0).Infof("queue up %d~%d size %d", startTime.UnixNano(), stopTime.UnixNano(), len(buf))
}, nil, func() {
})
return lb
data = binary.BigEndian.AppendUint32(data, uint32(len(encoded)))
data = append(data, encoded...)
}
first, last := held[0], held[len(held)-1]
targetFile := topic.PartitionDir(t, p) + "/" + topic.LogFileName(time.Unix(0, first.TsNs), first.Offset)
if err := b.writeLogFile(ctx, fence, targetFile, data, first.Offset, last.Offset); err != nil {
glog.Errorf("take over %v %v epoch %d: store offsets %d-%d: %v", t, p, init.Epoch, first.Offset, last.Offset, err)
return
}
}
glog.V(0).Infof("took over %v %v epoch %d from %s, stored %d entries", t, p, init.Epoch, init.Leader, len(held))
stopRenewing()
b.sealAndReportGeneration(ctx, t, p, fence, init.Epoch)
}
@@ -1,54 +0,0 @@
package broker
import (
"bytes"
"encoding/binary"
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util/buffered_queue"
)
// Keep the first flushed batch queued while subsequent flushes can reuse the
// log buffer's pooled storage.
func TestFollowerQueuedBufferRetainsBytes(t *testing.T) {
queue := buffered_queue.NewBufferedQueue[memBuffer](4)
broker := &MessageQueueBroker{}
lb := broker.buildFollowerLogBuffer(queue)
defer func() { lb.ShutdownLogBuffer(); lb.WaitForShutdown(); queue.CloseInput() }()
if err := lb.InitializeOffsetFromExistingData(func() (int64, error) { return 99, nil }); err != nil {
t.Fatal(err)
}
want := bytes.Repeat([]byte{'A'}, 64)
var original []byte
for i := 0; i < 8; i++ {
data := bytes.Repeat([]byte{byte('A' + i)}, 64)
if err := lb.AddDataToBuffer([]byte("key"), data, 1_000_000_000+int64(i)*100_000_000); err != nil {
t.Fatal(err)
}
lb.ForceFlush()
first, ok := queue.PeekHead()
if !ok {
t.Fatal("completed flush did not queue follower data")
}
if i == 0 {
original = bytes.Clone(first.buf)
}
if !bytes.Equal(first.buf, original) {
var entry filer_pb.LogEntry
var decodeErr error
if len(first.buf) < 4 {
decodeErr = fmt.Errorf("short header")
} else {
size := int(binary.BigEndian.Uint32(first.buf[:4]))
if size+4 > len(first.buf) {
decodeErr = fmt.Errorf("truncated frame: announced=%d slice=%d", size, len(first.buf))
} else {
decodeErr = entry.UnmarshalVT(first.buf[4 : 4+size])
}
}
t.Fatalf("queued first buffer changed after later flush %d: want_data=%q actual_data=%q decode_error=%v first_offset=%d", i, want, entry.Data, decodeErr, entry.Offset)
}
}
}
+1 -59
View File
@@ -9,7 +9,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/sub_coordinator"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
@@ -72,41 +71,6 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
}
}()
// connect to the follower
var subscribeFollowMeStream mq_pb.SeaweedMessaging_SubscribeFollowMeClient
glog.V(0).Infof("follower broker: %v", req.GetInit().FollowerBroker)
if req.GetInit().FollowerBroker != "" {
follower := req.GetInit().FollowerBroker
if followerGrpcConnection, err := pb.GrpcDial(ctx, follower, true, b.grpcDialOption); err != nil {
return fmt.Errorf("fail to dial %s: %v", follower, err)
} else {
defer func() {
println("closing SubscribeFollowMe connection", follower)
if subscribeFollowMeStream != nil {
subscribeFollowMeStream.CloseSend()
}
// followerGrpcConnection.Close()
}()
followerClient := mq_pb.NewSeaweedMessagingClient(followerGrpcConnection)
if subscribeFollowMeStream, err = followerClient.SubscribeFollowMe(ctx); err != nil {
return fmt.Errorf("fail to subscribe to %s: %v", follower, err)
} else {
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
Message: &mq_pb.SubscribeFollowMeRequest_Init{
Init: &mq_pb.SubscribeFollowMeRequest_InitMessage{
Topic: req.GetInit().Topic,
Partition: req.GetInit().GetPartitionOffset().Partition,
ConsumerGroup: req.GetInit().ConsumerGroup,
},
},
}); err != nil {
return fmt.Errorf("fail to send init to %s: %v", follower, err)
}
}
}
glog.V(0).Infof("follower %s connected", follower)
}
// Channel to handle seek requests - signals Subscribe loop to restart from new offset
seekChan := make(chan *mq_pb.SubscribeMessageRequest_SeekMessage, 1)
@@ -162,19 +126,8 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
// Update acknowledged offset and last seen time for this subscriber when it sends an ack
subscriber.UpdateAckedOffset(currentLastOffset)
// fmt.Printf("%+v recv (%s,%d), oldest %d\n", partition, string(ack.GetAck().Key), ack.GetAck().TsNs, currentLastOffset)
if subscribeFollowMeStream != nil && currentLastOffset > lastOffset {
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
Message: &mq_pb.SubscribeFollowMeRequest_Ack{
Ack: &mq_pb.SubscribeFollowMeRequest_AckMessage{
TsNs: currentLastOffset,
},
},
}); err != nil {
glog.Errorf("Error sending ack to follower: %v", err)
break
}
if currentLastOffset > lastOffset {
lastOffset = currentLastOffset
// fmt.Printf("%+v forwarding ack %d\n", partition, lastOffset)
}
}
if lastOffset > 0 {
@@ -183,17 +136,6 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs
glog.Errorf("saveConsumerGroupOffset partition %v lastOffset %d: %v", partition, lastOffset, err)
}
}
if subscribeFollowMeStream != nil {
if err := subscribeFollowMeStream.Send(&mq_pb.SubscribeFollowMeRequest{
Message: &mq_pb.SubscribeFollowMeRequest_Close{
Close: &mq_pb.SubscribeFollowMeRequest_CloseMessage{},
},
}); err != nil {
if err != io.EOF {
glog.Errorf("Error sending close to follower: %v", err)
}
}
}
}()
// Create a goroutine to handle context cancellation and wake up the condition variable
+169 -28
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"strconv"
"sync"
"time"
"github.com/google/uuid"
@@ -13,13 +14,16 @@ import (
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/logstore"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util"
)
var (
errFenceLost = errors.New("partition fence is held by another broker")
errFenceLost = errors.New("partition fence is held by another broker")
errGenerationEnded = errors.New("partition generation ended")
// the filer recorded this failure under the request id, so a retry of that id replays it
errTransactionFailed = errors.New("transaction failed")
)
@@ -27,9 +31,11 @@ var (
// fenceTakeTimeout bounds the filer calls a fence take makes while holding accessLock.
var fenceTakeTimeout = 10 * time.Second
// newLeaderPartition takes the partition's fence for epoch before anything reads
// the partition's files, so a previous leader can no longer add to them.
func (b *MessageQueueBroker) newLeaderPartition(t topic.Topic, partition topic.Partition, epoch int64) (*topic.LocalPartition, error) {
// newLeaderPartition takes the partition's fence for the assignment's epoch before
// anything reads the partition's files, so a previous leader can no longer add to
// them, then starts replicating to the assigned follower.
func (b *MessageQueueBroker) newLeaderPartition(t topic.Topic, partition topic.Partition, assignment *mq_pb.BrokerPartitionAssignment) (*topic.LocalPartition, error) {
epoch := assignment.Epoch
ctx, cancel := context.WithTimeout(context.Background(), fenceTakeTimeout)
defer cancel()
fence, err := b.takePartitionFence(ctx, t, partition, epoch)
@@ -42,6 +48,23 @@ func (b *MessageQueueBroker) newLeaderPartition(t topic.Topic, partition topic.P
localPartition.Shutdown()
return nil, err
}
if follower := assignment.FollowerBroker; follower != "" && !pb.ServerAddress(follower).Equals(b.option.BrokerAddress()) {
replica, err := topic.StartReplicator(follower, b.grpcDialOption, &mq_pb.PublishFollowMeRequest_InitMessage{
Topic: t.ToPbTopic(),
Partition: assignment.Partition,
Epoch: epoch,
Leader: string(b.option.BrokerAddress()),
})
if err != nil {
localPartition.Shutdown()
// callers hold accessLock, so the seal gives up and the report goes out regardless
sealCtx, cancelSeal := context.WithTimeout(context.Background(), fenceTakeTimeout)
b.sealAndReportGeneration(sealCtx, t, partition, fence, epoch)
cancelSeal()
return nil, fmt.Errorf("%v: %w", err, errGenerationEnded)
}
localPartition.Replica, localPartition.Follower = replica, follower
}
return localPartition, nil
}
@@ -53,12 +76,15 @@ func fenceEpoch(entry *filer_pb.Entry) (int64, error) {
return strconv.ParseInt(string(value), 10, 64)
}
// fenceSealWait is how long a new leader leaves an unsealed fence of an earlier
// generation to its holder, which may still be persisting what it holds.
const fenceSealWait = 30 * time.Second
func (b *MessageQueueBroker) takePartitionFence(ctx context.Context, t topic.Topic, partition topic.Partition, epoch int64) (*topic.PartitionFence, error) {
fencePath := util.FullPath(topic.PartitionFencePath(t, partition))
dir, name := fencePath.DirAndName()
fencePath := topic.PartitionFencePath(t, partition)
self := string(b.option.BrokerAddress())
current, _, _, err := filer_pb.GetEntry(ctx, b, fencePath)
current, _, _, err := filer_pb.GetEntry(ctx, b, util.FullPath(fencePath))
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return nil, err
}
@@ -68,23 +94,119 @@ func (b *MessageQueueBroker) takePartitionFence(ctx context.Context, t topic.Top
if parseErr != nil {
return nil, fmt.Errorf("fence %s epoch: %w", fencePath, parseErr)
}
if storedEpoch > epoch {
return nil, fmt.Errorf("fence %s is at epoch %d held by %s: %w", fencePath, storedEpoch, current.Extended[mq.ExtendedAttrFenceWriter], errFenceLost)
writer, sealed := string(current.Extended[mq.ExtendedAttrFenceWriter]), fenceSealed(current)
switch {
case storedEpoch > epoch:
return nil, fmt.Errorf("fence %s is at epoch %d held by %s: %w", fencePath, storedEpoch, writer, errFenceLost)
case storedEpoch == epoch && (sealed || writer != self):
// this generation ended, or its follower took it over
return nil, fmt.Errorf("fence %s epoch %d held by %s sealed %v: %w", fencePath, epoch, writer, sealed, errFenceLost)
case storedEpoch < epoch && !sealed && time.Since(time.Unix(current.GetAttributes().GetMtime(), 0)) < fenceSealWait:
return nil, fmt.Errorf("fence %s: epoch %d held by %s is still being sealed: %w", fencePath, storedEpoch, writer, errFenceLost)
}
if string(current.Extended[mq.ExtendedAttrFenceSealed]) == "true" {
return nil, fmt.Errorf("fence %s is sealed", fencePath)
}
condition = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: current}
if token := current.Extended[s3_constants.ExtETagKey]; len(token) > 0 {
condition = fenceTokenCondition(string(token))
condition = currentFenceCondition(current)
if storedEpoch < epoch && !sealed {
// judged stale by its mtime, which a renewal changes but the token does not
condition = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: current}
}
}
fence, err := b.writePartitionFence(ctx, fencePath, condition, epoch, false)
if err != nil {
return nil, err
}
glog.V(0).Infof("broker %s took fence %s at epoch %d", self, fencePath, epoch)
return fence, nil
}
// The token is the fence entry's etag, so writes can require it without reading
// the entry back through a filer that may not have caught up with the owner.
// takeOverPartitionFence moves the fence from a lost leader to this follower within
// the same generation, unless the leader sealed it or someone else moved it first.
func (b *MessageQueueBroker) takeOverPartitionFence(ctx context.Context, t topic.Topic, partition topic.Partition, epoch int64, leader string) (*topic.PartitionFence, error) {
fencePath := topic.PartitionFencePath(t, partition)
current, _, _, err := filer_pb.GetEntry(ctx, b, util.FullPath(fencePath))
if err != nil {
return nil, err
}
storedEpoch, _ := fenceEpoch(current)
if writer := string(current.Extended[mq.ExtendedAttrFenceWriter]); writer != leader || storedEpoch != epoch || fenceSealed(current) {
return nil, fmt.Errorf("fence %s is held by %s at epoch %d sealed %v: %w", fencePath, writer, storedEpoch, fenceSealed(current), errFenceLost)
}
return b.writePartitionFence(ctx, fencePath, currentFenceCondition(current), epoch, false)
}
// currentFenceCondition holds while the fence is still current; a fence written
// before tokens is matched as a whole entry.
func currentFenceCondition(current *filer_pb.Entry) *filer_pb.WriteCondition_Clause {
if token := current.Extended[s3_constants.ExtETagKey]; len(token) > 0 {
return fenceTokenCondition(string(token))
}
return &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: current}
}
// writePartitionFence stores the fence for this broker under a fresh token. The
// token is the entry's etag, so writes can require it without reading the entry
// back through a filer that may not have caught up with the owner.
func (b *MessageQueueBroker) writePartitionFence(ctx context.Context, fencePath string, condition *filer_pb.WriteCondition_Clause, epoch int64, sealed bool) (*topic.PartitionFence, error) {
token := uuid.NewString()
if err := b.putFence(ctx, fencePath, condition, epoch, token, sealed); err != nil {
return nil, err
}
return topic.NewPartitionFence(fencePath, epoch, token), nil
}
// renewPartitionFence refreshes the held fence's mtime, which tells a new leader
// this holder is still persisting. Sealing also replaces the token, so a follower
// that read the fence unsealed cannot take it over afterwards.
func (b *MessageQueueBroker) renewPartitionFence(ctx context.Context, fence *topic.PartitionFence, seal bool) error {
held, token := fence.Token(), fence.Token()
if seal {
token = uuid.NewString()
}
err := b.putFence(ctx, fence.Path, fenceTokenCondition(held), fence.Epoch, token, seal)
if errors.Is(err, errFenceLost) {
fence.MarkLost()
}
if err != nil {
return err
}
fence.Hold(token)
return nil
}
// fenceRenewInterval keeps a persisting holder's fence well inside fenceSealWait.
var fenceRenewInterval = fenceSealWait / 3
// keepFenceRenewed renews fence now and then periodically until stop, so a new
// leader keeps waiting while this broker persists what it holds.
func (b *MessageQueueBroker) keepFenceRenewed(fence *topic.PartitionFence) (stop func()) {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
for {
if err := b.renewPartitionFence(ctx, fence, false); errors.Is(err, errFenceLost) {
glog.Warningf("fence %s moved on while persisting: %v", fence.Path, err)
return
}
select {
case <-ctx.Done():
return
case <-time.After(fenceRenewInterval):
}
}
}()
var once sync.Once
return func() {
once.Do(func() {
cancel()
<-done
})
}
}
func (b *MessageQueueBroker) putFence(ctx context.Context, fencePath string, condition *filer_pb.WriteCondition_Clause, epoch int64, token string, sealed bool) error {
dir, name := util.FullPath(fencePath).DirAndName()
now := time.Now().Unix()
fenceEntry := &filer_pb.Entry{
entry := &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{
Crtime: now,
@@ -92,20 +214,30 @@ func (b *MessageQueueBroker) takePartitionFence(ctx context.Context, t topic.Top
FileMode: uint32(os.FileMode(0644)),
},
Extended: map[string][]byte{
mq.ExtendedAttrFenceWriter: []byte(self),
mq.ExtendedAttrFenceWriter: []byte(b.option.BrokerAddress()),
mq.ExtendedAttrFenceEpoch: []byte(strconv.FormatInt(epoch, 10)),
s3_constants.ExtETagKey: []byte(token),
},
}
if err := b.fencedTransaction(ctx, string(fencePath), condition, uuid.NewString(), &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_PUT,
Directory: dir,
Entry: fenceEntry,
}); err != nil {
return nil, err
if sealed {
entry.Extended[mq.ExtendedAttrFenceSealed] = []byte("true")
}
glog.V(0).Infof("broker %s took fence %s at epoch %d", self, fencePath, epoch)
return &topic.PartitionFence{Path: string(fencePath), Epoch: epoch, Token: token}, nil
mutation := &filer_pb.ObjectMutation{Type: filer_pb.ObjectMutation_PUT, Directory: dir, Entry: entry}
requestId := uuid.NewString()
return retryLogWrite(ctx, fencePath, func() error {
// stamped per attempt, so a renewal that lands late is not already stale;
// a replayed request id answers with the outcome the filer recorded
entry.Attributes.Mtime = time.Now().Unix()
err := b.fencedTransaction(ctx, fencePath, condition, requestId, mutation)
if errors.Is(err, errTransactionFailed) {
requestId = uuid.NewString()
}
return err
})
}
func fenceSealed(entry *filer_pb.Entry) bool {
return string(entry.Extended[mq.ExtendedAttrFenceSealed]) == "true"
}
// retireStaleLeader retires p if it lost its fence or holds it for an older
@@ -123,7 +255,16 @@ func (b *MessageQueueBroker) retireStaleLeader(t topic.Topic, p *topic.LocalPart
p.LogBuffer.WaitForShutdown()
b.accessLock.Lock()
// once the broker is stopping, its Shutdown retires p instead
return b.localTopicManager.RemoveLocalPartition(t, p) || b.localTopicManager.GetLocalPartition(t, p.Partition) != p
removed := b.localTopicManager.RemoveLocalPartition(t, p)
if removed && !p.Fence.IsLost() {
// its last flush landed, so the next leader need not wait out fenceSealWait
ctx, cancel := context.WithTimeout(context.Background(), fenceTakeTimeout)
if err := b.renewPartitionFence(ctx, p.Fence, true); err != nil {
glog.V(0).Infof("seal stale fence %s: %v", p.Fence.Path, err)
}
cancel()
}
return removed || b.localTopicManager.GetLocalPartition(t, p.Partition) != p
}
// fenceTokenCondition holds while the fence entry is still the one written with token.
+233 -14
View File
@@ -46,6 +46,8 @@ type fencingFiler struct {
lagging map[string]*filer_pb.Entry
// lookups wait for their caller to give up, as a stalled filer does
stalled bool
// listings fail this many times, as a filer that is briefly unavailable does
failLists int
// runs under the lock before a transaction applies, to interleave another writer
beforeApply func()
volume *httptest.Server
@@ -56,6 +58,11 @@ type fencingFiler struct {
func (f *fencingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
f.mu.Lock()
if f.failLists > 0 {
f.failLists--
f.mu.Unlock()
return status.Error(codes.Unavailable, "filer unavailable")
}
var names []string
children := map[string]*filer_pb.Entry{}
for path, entry := range f.entries {
@@ -241,8 +248,8 @@ func TestTakeAbsentFenceRequiresItStillAbsent(t *testing.T) {
t.Errorf("fence carries %s", key)
}
}
if fence.Path != path || fence.Token == "" || string(f.entry(path).Extended[s3_constants.ExtETagKey]) != fence.Token {
t.Errorf("held fence token %q is not the stored %v", fence.Token, f.entry(path))
if fence.Path != path || fence.Token() == "" || string(f.entry(path).Extended[s3_constants.ExtETagKey]) != fence.Token() {
t.Errorf("held fence token %q is not the stored %v", fence.Token(), f.entry(path))
}
}
@@ -264,8 +271,8 @@ func TestTakePresentFenceRequiresTheEntryAsRead(t *testing.T) {
if len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ENTRY_EQUAL || !proto.Equal(clauses[0].ExpectedEntry, previous) {
t.Errorf("condition %v, want IF_ENTRY_EQUAL on %v", clauses, previous)
}
if stored := f.entry(path); string(stored.Extended[mq.ExtendedAttrFenceEpoch]) != "3" || string(stored.Extended[s3_constants.ExtETagKey]) != fence.Token {
t.Errorf("stored fence %v, held token %q", stored, fence.Token)
if stored := f.entry(path); string(stored.Extended[mq.ExtendedAttrFenceEpoch]) != "3" || string(stored.Extended[s3_constants.ExtETagKey]) != fence.Token() {
t.Errorf("stored fence %v, held token %q", stored, fence.Token())
}
// the same epoch can be taken again, as a restarted leader does, requiring the token as read
@@ -273,10 +280,10 @@ func TestTakePresentFenceRequiresTheEntryAsRead(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if clauses := f.transactions()[1].Condition.GetClauses(); len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || !slices.Equal(clauses[0].Etags, []string{fence.Token}) {
t.Errorf("retake condition %v, want the token %q", clauses, fence.Token)
if clauses := f.transactions()[1].Condition.GetClauses(); len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || !slices.Equal(clauses[0].Etags, []string{fence.Token()}) {
t.Errorf("retake condition %v, want the token %q", clauses, fence.Token())
}
if again.Token == fence.Token {
if again.Token() == fence.Token() {
t.Error("a retaken fence kept its token")
}
}
@@ -329,7 +336,7 @@ func TestTakeFenceGivesUpOnAStalledFiler(t *testing.T) {
done := make(chan error, 1)
go func() {
_, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, 1)
_, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 1})
done <- err
}()
select {
@@ -358,6 +365,8 @@ func TestReassignedLeaderReplacesItsFencedPartition(t *testing.T) {
}
assign(1)
old := b.localTopicManager.GetLocalPartition(fenceTestTopic, fenceTestPartition)
// another broker led epoch 2 and sealed it
f.put(topic.PartitionFencePath(fenceTestTopic, fenceTestPartition), fenceAt("127.0.0.1:18888", "2", 1, true))
old.Fence.MarkLost()
assign(3)
@@ -376,7 +385,7 @@ func TestReassignedLeaderReplacesItsFencedPartition(t *testing.T) {
func TestReassignmentReloadsAnOlderEpoch(t *testing.T) {
f, b := newFencingFiler(t)
old, _ := newFencedPartition(t, b)
if err := old.Publish(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
if _, err := old.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
assign := func(epoch int64) *topic.LocalPartition {
@@ -399,8 +408,8 @@ func TestReassignmentReloadsAnOlderEpoch(t *testing.T) {
t.Fatalf("serving fence %+v after an assignment at epoch 2", reloaded.Fence)
}
txns := f.transactions()
if len(txns) != 3 || !strings.HasPrefix(txns[1].Mutations[0].Entry.Name, "20") || txns[2].Mutations[0].Entry.Name != topic.PartitionFenceName {
t.Errorf("%d transactions, want the old copy's last window before the new fence", len(txns))
if len(txns) != 4 || !strings.HasPrefix(txns[1].Mutations[0].Entry.Name, "20") || !fenceSealed(txns[2].Mutations[0].Entry) || txns[3].Mutations[0].Entry.Name != topic.PartitionFenceName {
t.Errorf("%d transactions, want the old copy's last window and seal before the new fence", len(txns))
}
}
@@ -425,7 +434,7 @@ func TestLookupReloadsAnOlderEpoch(t *testing.T) {
func TestConcurrentReloadsWaitForTheLastFlush(t *testing.T) {
f, b := newFencingFiler(t)
old, _ := newFencedPartition(t, b)
if err := old.Publish(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
if _, err := old.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
f.uploadGate = make(chan struct{})
@@ -465,8 +474,9 @@ func TestConcurrentReloadsWaitForTheLastFlush(t *testing.T) {
for _, txn := range f.transactions() {
names = append(names, txn.Mutations[0].Entry.Name)
}
if len(names) != 3 || names[0] != topic.PartitionFenceName || !strings.HasPrefix(names[1], "20") || names[2] != topic.PartitionFenceName {
t.Errorf("transactions %v, want the old copy's last window before one new fence", names)
txns := f.transactions()
if len(names) != 4 || names[0] != topic.PartitionFenceName || !strings.HasPrefix(names[1], "20") || !fenceSealed(txns[2].Mutations[0].Entry) || names[3] != topic.PartitionFenceName {
t.Errorf("transactions %v, want the old copy's last window and one seal before one new fence", names)
}
for _, txn := range f.transactions() {
if f.outcome[txn.RequestId].GetErrorCode() == filer_pb.FilerError_PRECONDITION_FAILED {
@@ -474,3 +484,212 @@ func TestConcurrentReloadsWaitForTheLastFlush(t *testing.T) {
}
}
}
func fenceAt(writer string, epoch string, mtime int64, sealed bool) *filer_pb.Entry {
e := &filer_pb.Entry{
Name: topic.PartitionFenceName,
Attributes: &filer_pb.FuseAttributes{Mtime: mtime},
Extended: map[string][]byte{
mq.ExtendedAttrFenceWriter: []byte(writer),
mq.ExtendedAttrFenceEpoch: []byte(epoch),
s3_constants.ExtETagKey: []byte(writer + "/" + epoch),
},
}
if sealed {
e.Extended[mq.ExtendedAttrFenceSealed] = []byte("true")
}
return e
}
// A new leader leaves an unsealed fence of an earlier generation to its holder for
// a while, since the holder may still be persisting what it holds.
func TestTakeFenceWaitsForAnEarlierGenerationToSeal(t *testing.T) {
f, b := newFencingFiler(t)
path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
f.put(path, fenceAt("127.0.0.1:18888", "2", time.Now().Unix(), false))
if _, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3); !errors.Is(err, errFenceLost) {
t.Fatalf("took a fence its holder just renewed: %v", err)
}
f.put(path, fenceAt("127.0.0.1:18888", "2", time.Now().Unix(), true))
if _, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3); err != nil {
t.Fatalf("could not take a sealed fence: %v", err)
}
}
func TestTakeFenceRefusesItsGenerationHeldElsewhere(t *testing.T) {
f, b := newFencingFiler(t)
path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
f.put(path, fenceAt("127.0.0.1:18888", "3", 1, false))
if _, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3); !errors.Is(err, errFenceLost) {
t.Fatalf("took back a generation its follower took over: %v", err)
}
f.put(path, fenceAt("127.0.0.1:17777", "3", 1, true))
if _, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3); !errors.Is(err, errFenceLost) {
t.Fatalf("reopened a sealed generation: %v", err)
}
}
func TestFollowerTakesOverItsLeadersFence(t *testing.T) {
f, b := newFencingFiler(t)
path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
leader := "127.0.0.1:18888"
f.put(path, fenceAt(leader, "3", 1, true))
if _, err := b.takeOverPartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3, leader); !errors.Is(err, errFenceLost) {
t.Fatalf("took over a fence the leader sealed: %v", err)
}
f.put(path, fenceAt("127.0.0.1:19999", "3", 1, false))
if _, err := b.takeOverPartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3, leader); !errors.Is(err, errFenceLost) {
t.Fatalf("took over a fence another broker holds: %v", err)
}
f.put(path, fenceAt(leader, "3", 1, false))
fence, err := b.takeOverPartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3, leader)
if err != nil {
t.Fatal(err)
}
stored := f.entry(path)
if string(stored.Extended[mq.ExtendedAttrFenceWriter]) != "127.0.0.1:17777" || string(stored.Extended[s3_constants.ExtETagKey]) != fence.Token() {
t.Fatalf("stored %v, held token %q", stored, fence.Token())
}
}
// A seal replaces the token, so a follower that read the fence before the seal
// cannot take it over after.
func TestSealingReplacesTheToken(t *testing.T) {
f, b := newFencingFiler(t)
path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
fence, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 1)
if err != nil {
t.Fatal(err)
}
before := fence.Token()
if err := b.renewPartitionFence(context.Background(), fence, false); err != nil {
t.Fatal(err)
}
if fence.Token() != before {
t.Fatal("a renewal replaced the token, failing flushes already under way")
}
if err := b.renewPartitionFence(context.Background(), fence, true); err != nil {
t.Fatal(err)
}
stored := f.entry(path)
if !fenceSealed(stored) || fence.Token() == before || string(stored.Extended[s3_constants.ExtETagKey]) != fence.Token() {
t.Fatalf("stored %v, held token %q", stored, fence.Token())
}
if err := b.fencedTransaction(context.Background(), path, fenceTokenCondition(before), "late-takeover", &filer_pb.ObjectMutation{Type: filer_pb.ObjectMutation_PUT, Directory: topic.PartitionDir(fenceTestTopic, fenceTestPartition), Entry: fenceAt("127.0.0.1:18888", "1", 1, false)}); !errors.Is(err, errFenceLost) {
t.Fatalf("a write holding the pre-seal token went through: %v", err)
}
// a holder whose fence moved on is told so, and marks it lost
f.put(path, fenceAt("127.0.0.1:18888", "2", 1, false))
if err := b.renewPartitionFence(context.Background(), fence, true); !errors.Is(err, errFenceLost) || !fence.IsLost() {
t.Fatalf("renewed a fence another broker holds: %v", err)
}
}
// A holder persisting what it holds keeps its fence fresh, so a new leader keeps
// waiting however long that takes, and takes the fence once the holder stops.
func TestPersistingHolderKeepsItsFenceRenewed(t *testing.T) {
f, b := newFencingFiler(t)
defer func(interval time.Duration) { fenceRenewInterval = interval }(fenceRenewInterval)
fenceRenewInterval = 20 * time.Millisecond
path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
fence, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 1)
if err != nil {
t.Fatal(err)
}
// taken long ago, as a leader's fence is when its generation ends
stale := proto.Clone(f.entry(path)).(*filer_pb.Entry)
stale.Attributes.Mtime = time.Now().Add(-time.Hour).Unix()
f.put(path, stale)
stop := b.keepFenceRenewed(fence)
for deadline := time.Now().Add(5 * time.Second); f.entry(path).Attributes.Mtime < time.Now().Add(-fenceSealWait).Unix(); time.Sleep(5 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("fence not renewed")
}
}
_, other := newFencingFiler(t)
other.currentFiler, other.option = b.currentFiler, &MessageQueueBrokerOption{Ip: "127.0.0.1", Port: 18888}
if _, err := other.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 2); !errors.Is(err, errFenceLost) {
t.Fatalf("a new leader took a fence its holder is renewing: %v", err)
}
stop()
stop()
if string(f.entry(path).Extended[s3_constants.ExtETagKey]) != fence.Token() || fence.IsLost() {
t.Fatal("renewals changed the token")
}
}
// A renewal that lands only after its retries carries the time it landed.
func TestLateRenewalIsStampedWhenItLands(t *testing.T) {
f, b := newFencingFiler(t)
path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
fence, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 1)
if err != nil {
t.Fatal(err)
}
f.mu.Lock()
f.failMutations = 3
f.mu.Unlock()
start := time.Now().Unix()
if err := b.renewPartitionFence(context.Background(), fence, false); err != nil {
t.Fatal(err)
}
landed := f.entry(path).Attributes.Mtime
if elapsed := time.Now().Unix() - start; elapsed < 2 {
t.Fatalf("retries took %ds, too short to tell the stamps apart", elapsed)
}
if landed <= start {
t.Fatalf("renewal stamped %d, before it landed (started %d)", landed, start)
}
}
// A holder that renews between a new leader's staleness check and its write keeps
// the fence: the renewal changes only the mtime, so the token alone would not tell.
func TestTakeFenceLosesToARenewalAfterItsCheck(t *testing.T) {
f, b := newFencingFiler(t)
path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
f.put(path, fenceAt("127.0.0.1:18888", "2", time.Now().Add(-time.Hour).Unix(), false))
f.beforeApply = func() {
renewed := proto.Clone(f.entries[path]).(*filer_pb.Entry)
renewed.Attributes.Mtime = time.Now().Unix()
f.entries[path] = renewed
}
if _, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3); !errors.Is(err, errFenceLost) {
t.Fatalf("took a fence its holder renewed after the check: %v", err)
}
if writer := string(f.entry(path).Extended[mq.ExtendedAttrFenceWriter]); writer != "127.0.0.1:18888" {
t.Fatalf("fence moved to %s", writer)
}
}
// A leader whose follower cannot be reached seals and reports under the access
// lock, so a filer that keeps failing must not hold the load forever.
func TestFailedReplicaStartDoesNotWaitOnAFailingFiler(t *testing.T) {
f, b := newFencingFiler(t)
defer func(timeout time.Duration) { fenceTakeTimeout = timeout }(fenceTakeTimeout)
fenceTakeTimeout = 500 * time.Millisecond
took := false
f.beforeApply = func() {
if took {
f.failMutations = 1 << 30
}
took = true
}
done := make(chan error, 1)
go func() {
_, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{
Partition: fenceTestPartition.ToPbPartition(), Epoch: 1, FollowerBroker: "127.0.0.1:1",
})
done <- err
}()
select {
case err := <-done:
if !errors.Is(err, errGenerationEnded) {
t.Fatalf("load with an unreachable follower returned %v", err)
}
case <-time.After(15 * time.Second):
t.Fatal("seal after a failed replica start never gave up")
}
}
+478
View File
@@ -0,0 +1,478 @@
package broker
import (
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"sort"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func startFollower(t *testing.T, srv mq_pb.SeaweedMessagingServer) (string, *grpc.Server) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
mq_pb.RegisterSeaweedMessagingServer(server, srv)
go server.Serve(listener)
t.Cleanup(server.Stop)
return listener.Addr().String(), server
}
func startReplica(t *testing.T, follower string) *topic.Replicator {
replica, err := topic.StartReplicator(follower, grpc.WithTransportCredentials(insecure.NewCredentials()), &mq_pb.PublishFollowMeRequest_InitMessage{
Topic: &schema_pb.Topic{Namespace: "test", Name: "t"},
Partition: &schema_pb.Partition{RingSize: 2520, RangeStop: 2520, UnixTimeNs: 1},
Epoch: 1,
Leader: "127.0.0.1:17777",
})
if err != nil {
t.Fatal(err)
}
return replica
}
func TestReplicaAcksWhatTheFollowerHolds(t *testing.T) {
follower, _ := startFollower(t, &MessageQueueBroker{})
replica := startReplica(t, follower)
for offset := int64(0); offset < 100; offset++ {
if err := replica.Send(&filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Key: []byte("k"), Offset: offset}); err != nil {
t.Fatal(err)
}
}
if err := replica.WaitAcked(99); err != nil {
t.Fatal(err)
}
replica.Flushed(99)
replica.Close()
if err := replica.Err(); !errors.Is(err, topic.ErrReplicaClosed) {
t.Fatalf("closed replica reports %v", err)
}
}
func TestReplicaBreaksWhenTheFollowerGoes(t *testing.T) {
follower, server := startFollower(t, &MessageQueueBroker{})
replica := startReplica(t, follower)
if err := replica.Send(&filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Offset: 0}); err != nil {
t.Fatal(err)
}
if err := replica.WaitAcked(0); err != nil {
t.Fatal(err)
}
server.Stop()
select {
case <-replica.Broken():
case <-time.After(10 * time.Second):
t.Fatal("pair not broken after the follower stopped")
}
if err := replica.WaitAcked(1); err == nil {
t.Fatal("an offset the follower never held was acked")
}
}
// silentFollower takes the stream and never answers, as a hung broker would.
type silentFollower struct {
mq_pb.UnimplementedSeaweedMessagingServer
}
func (silentFollower) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) error {
for {
if _, err := stream.Recv(); err != nil {
return err
}
}
}
func TestReplicaBreaksWhenTheFollowerFallsSilent(t *testing.T) {
follower, _ := startFollower(t, silentFollower{})
replica := startReplica(t, follower)
select {
case <-replica.Broken():
case <-time.After(15 * time.Second):
t.Fatal("pair not broken after the follower fell silent")
}
}
// A leader that loses its follower stores what it holds under its fence and seals it.
// stuckFollower takes the stream and stops reading, so the leader's sends block.
type stuckFollower struct {
mq_pb.UnimplementedSeaweedMessagingServer
}
func (stuckFollower) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) error {
<-stream.Context().Done()
return nil
}
func TestReplicaBreaksWhenASendBlocks(t *testing.T) {
follower, _ := startFollower(t, stuckFollower{})
replica := startReplica(t, follower)
value := make([]byte, 64*1024)
go func() {
for offset := int64(0); ; offset++ {
if replica.Send(&filer_pb.LogEntry{Offset: offset, Data: value}) != nil {
return
}
}
}()
select {
case <-replica.Broken():
case <-time.After(15 * time.Second):
t.Fatal("pair not broken while sends to the follower were blocked")
}
}
func TestLeaderStoresAndSealsWhenItLosesItsFollower(t *testing.T) {
f, leader := newFencingFiler(t)
leader.localTopicManager = topic.NewLocalTopicManager()
leader.fca = &filer_client.FilerClientAccessor{
GetGrpcDialOption: leader.GetGrpcDialOption,
GetFilers: func() []pb.ServerAddress { return []pb.ServerAddress{leader.GetFiler()} },
}
followerAddr, followerServer := startFollower(t, &MessageQueueBroker{})
lp, err := leader.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{
Partition: fenceTestPartition.ToPbPartition(),
LeaderBroker: "127.0.0.1:17777",
FollowerBroker: followerAddr,
Epoch: 1,
})
if err != nil {
t.Fatal(err)
}
leader.localTopicManager.AddLocalPartition(fenceTestTopic, lp)
go leader.watchReplica(fenceTestTopic, fenceTestPartition, lp, 1)
for i := 0; i < 10; i++ {
offset, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()})
if err != nil {
t.Fatal(err)
}
if err := lp.Replica.WaitAcked(offset); err != nil {
t.Fatal(err)
}
}
followerServer.Stop()
fencePath := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
deadline := time.Now().Add(20 * time.Second)
for !fenceSealed(f.entry(fencePath)) {
if time.Now().After(deadline) {
t.Fatal("fence not sealed after the follower was lost")
}
time.Sleep(50 * time.Millisecond)
}
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("late"), TsNs: time.Now().UnixNano()}); err == nil {
t.Fatal("a broken pair accepted a publish")
}
var stored mq.OffsetRange
dir := topic.PartitionDir(fenceTestTopic, fenceTestPartition)
f.mu.Lock()
for path, entry := range f.entries {
if d, name := util.FullPath(path).DirAndName(); d == dir && name != topic.PartitionFenceName {
stored.Add(entry.Extended)
}
}
f.mu.Unlock()
if earliest, hwm := stored.Bounds(); earliest != 0 || hwm != 10 {
t.Fatalf("stored offsets %d..%d, want 0..9", earliest, hwm-1)
}
}
// A follower whose leader vanishes takes the fence and stores what the leader had
// not, exactly once.
func TestFollowerTakesOverALostLeader(t *testing.T) {
f, follower := newFencingFiler(t)
follower.fca = &filer_client.FilerClientAccessor{
GetGrpcDialOption: follower.GetGrpcDialOption,
GetFilers: func() []pb.ServerAddress { return []pb.ServerAddress{follower.GetFiler()} },
}
followerAddr, _ := startFollower(t, follower)
leaderAddr := "127.0.0.1:18888"
fencePath := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
dir := topic.PartitionDir(fenceTestTopic, fenceTestPartition)
f.put(fencePath, fenceAt(leaderAddr, "1", time.Now().Unix(), false))
// the leader had stored offsets 0..4 before it went
f.put(dir+"/"+topic.LogFileName(time.Now(), 0), &filer_pb.Entry{Name: topic.LogFileName(time.Now(), 0), Attributes: &filer_pb.FuseAttributes{}, Extended: rangeExtended(0, 4)})
conn, err := grpc.NewClient(followerAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, vanish := context.WithCancel(context.Background())
stream, err := mq_pb.NewSeaweedMessagingClient(conn).PublishFollowMe(ctx)
if err != nil {
t.Fatal(err)
}
if err := stream.Send(&mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Init{Init: &mq_pb.PublishFollowMeRequest_InitMessage{
Topic: fenceTestTopic.ToPbTopic(), Partition: fenceTestPartition.ToPbPartition(), Epoch: 1, Leader: leaderAddr,
}}}); err != nil {
t.Fatal(err)
}
for offset := int64(0); offset < 10; offset++ {
if err := stream.Send(&mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Entry{Entry: &filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Key: []byte("k"), Data: []byte("v"), Offset: offset}}}); err != nil {
t.Fatal(err)
}
if ack, err := stream.Recv(); err != nil || ack.AckOffset != offset {
t.Fatalf("ack %v, %v; want offset %d", ack, err, offset)
}
}
vanish()
deadline := time.Now().Add(20 * time.Second)
for !fenceSealed(f.entry(fencePath)) {
if time.Now().After(deadline) {
t.Fatal("follower did not take over and seal")
}
time.Sleep(50 * time.Millisecond)
}
if writer := string(f.entry(fencePath).Extended[mq.ExtendedAttrFenceWriter]); writer != follower.option.BrokerAddress().String() {
t.Fatalf("fence held by %s", writer)
}
if stored, want := storedRanges(f, dir), []string{"0-4", "5-9"}; fmt.Sprint(stored) != fmt.Sprint(want) {
t.Fatalf("stored ranges %v, want %v", stored, want)
}
}
// storedRanges lists the offset ranges of the log files in dir.
func storedRanges(f *fencingFiler, dir string) (stored []string) {
f.mu.Lock()
defer f.mu.Unlock()
for path, entry := range f.entries {
if d, name := util.FullPath(path).DirAndName(); d == dir && name != topic.PartitionFenceName {
var r mq.OffsetRange
r.Add(entry.Extended)
earliest, hwm := r.Bounds()
stored = append(stored, fmt.Sprintf("%d-%d", earliest, hwm-1))
}
}
sort.Strings(stored)
return stored
}
// ackFailingStream delivers the leader's messages but fails the follower's ack
// at failAt, as a connection that broke while the follower answered.
type ackFailingStream struct {
grpc.ServerStream
ctx context.Context
reqs []*mq_pb.PublishFollowMeRequest
acks int
failAt int
}
func (s *ackFailingStream) Context() context.Context { return s.ctx }
func (s *ackFailingStream) Recv() (*mq_pb.PublishFollowMeRequest, error) {
if len(s.reqs) == 0 {
<-s.ctx.Done()
return nil, s.ctx.Err()
}
req := s.reqs[0]
s.reqs = s.reqs[1:]
return req, nil
}
func (s *ackFailingStream) Send(*mq_pb.PublishFollowMeResponse) error {
if s.acks++; s.acks == s.failAt {
return io.ErrClosedPipe
}
return nil
}
func TestFollowerTakesOverWhenItCannotAck(t *testing.T) {
f, follower := newFencingFiler(t)
leaderAddr := "127.0.0.1:18888"
fencePath := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
f.put(fencePath, fenceAt(leaderAddr, "1", time.Now().Unix(), false))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stream := &ackFailingStream{ctx: ctx, failAt: 5}
stream.reqs = append(stream.reqs, &mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Init{Init: &mq_pb.PublishFollowMeRequest_InitMessage{
Topic: fenceTestTopic.ToPbTopic(), Partition: fenceTestPartition.ToPbPartition(), Epoch: 1, Leader: leaderAddr,
}}})
for offset := int64(0); offset < 5; offset++ {
stream.reqs = append(stream.reqs, &mq_pb.PublishFollowMeRequest{Message: &mq_pb.PublishFollowMeRequest_Entry{Entry: &filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Key: []byte("k"), Data: []byte("v"), Offset: offset}}})
}
done := make(chan error, 1)
go func() { done <- follower.PublishFollowMe(stream) }()
select {
case <-done:
case <-time.After(20 * time.Second):
t.Fatal("follower kept waiting after its ack failed")
}
if !fenceSealed(f.entry(fencePath)) {
t.Fatal("follower did not take over and seal")
}
if stored, want := storedRanges(f, topic.PartitionDir(fenceTestTopic, fenceTestPartition)), []string{"0-4"}; fmt.Sprint(stored) != fmt.Sprint(want) {
t.Fatalf("stored ranges %v, want %v", stored, want)
}
}
func rangeExtended(min, max int64) map[string][]byte {
return map[string][]byte{
mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(min)),
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(max)),
}
}
// A follower whose filer briefly fails keeps the only copy of what the leader had
// not stored and retries, rather than give up the takeover.
func TestFollowerTakeoverRetriesAFilerError(t *testing.T) {
f, follower := newFencingFiler(t)
leaderAddr := "127.0.0.1:18888"
fencePath := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
dir := topic.PartitionDir(fenceTestTopic, fenceTestPartition)
f.put(fencePath, fenceAt(leaderAddr, "1", time.Now().Unix(), false))
f.put(dir+"/"+topic.LogFileName(time.Now(), 0), &filer_pb.Entry{Name: topic.LogFileName(time.Now(), 0), Attributes: &filer_pb.FuseAttributes{}, Extended: rangeExtended(0, 4)})
f.mu.Lock()
f.failLists = 2
f.mu.Unlock()
var held []*filer_pb.LogEntry
for offset := int64(0); offset < 10; offset++ {
held = append(held, &filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Key: []byte("k"), Data: []byte("v"), Offset: offset})
}
follower.takeOverPartition(fenceTestTopic, fenceTestPartition, &mq_pb.PublishFollowMeRequest_InitMessage{Epoch: 1, Leader: leaderAddr}, held)
if !fenceSealed(f.entry(fencePath)) {
t.Fatal("follower gave up the takeover")
}
if stored, want := storedRanges(f, dir), []string{"0-4", "5-9"}; fmt.Sprint(stored) != fmt.Sprint(want) {
t.Fatalf("stored ranges %v, want %v", stored, want)
}
}
// endingFollower acks every entry and reports how its stream ended.
type endingFollower struct {
mq_pb.UnimplementedSeaweedMessagingServer
ended chan string
}
func (f endingFollower) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) error {
for {
req, err := stream.Recv()
if err != nil {
f.ended <- "broken"
return nil
}
if req.GetClose() != nil {
f.ended <- "closed"
return nil
}
if entry := req.GetEntry(); entry != nil {
if err := stream.Send(&mq_pb.PublishFollowMeResponse{AckOffset: entry.Offset}); err != nil {
f.ended <- "broken"
return nil
}
}
}
}
// A leader whose last flush was dropped leaves the follower to store its copy
// instead of telling it everything is stored.
func TestRetiredLeaderClosesItsFollowerOnlyWhenAllIsStored(t *testing.T) {
for _, tc := range []struct {
dropFlush bool
want string
}{{false, "closed"}, {true, "broken"}} {
follower := endingFollower{ended: make(chan string, 1)}
addr, _ := startFollower(t, follower)
flush := func(logBuffer *log_buffer.LogBuffer, _, _ time.Time, buf []byte, _, _ int64) {
if tc.dropFlush {
logBuffer.NoteFlushDropped(len(buf))
}
}
manager := topic.NewLocalTopicManager()
lp := topic.NewLocalPartition(fenceTestPartition, 3600, flush, nil)
lp.Replica = startReplica(t, addr)
manager.AddLocalPartition(fenceTestTopic, lp)
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
manager.RemoveLocalPartition(fenceTestTopic, lp)
if err := manager.WaitRetired(context.Background(), fenceTestTopic, fenceTestPartition); err != nil {
t.Fatal(err)
}
select {
case got := <-follower.ended:
if got != tc.want {
t.Errorf("dropped flush %v: follow stream %s, want %s", tc.dropFlush, got, tc.want)
}
case <-time.After(10 * time.Second):
t.Fatalf("dropped flush %v: follow stream never ended", tc.dropFlush)
}
}
}
// refusingFollower takes the init and then drops the stream.
type refusingFollower struct {
mq_pb.UnimplementedSeaweedMessagingServer
}
func (refusingFollower) PublishFollowMe(stream mq_pb.SeaweedMessaging_PublishFollowMeServer) error {
if _, err := stream.Recv(); err != nil {
return err
}
return io.ErrUnexpectedEOF
}
// A pair that breaks before its partition is registered ends the generation
// only once it is, so the generation never ends under a partition still to be served.
func TestPairBrokenBeforeRegistrationEndsOnceRegistered(t *testing.T) {
f, leader := newFencingFiler(t)
leader.localTopicManager = topic.NewLocalTopicManager()
followerAddr, _ := startFollower(t, refusingFollower{})
lp, err := leader.newLeaderPartition(fenceTestTopic, fenceTestPartition, &mq_pb.BrokerPartitionAssignment{
Partition: fenceTestPartition.ToPbPartition(),
LeaderBroker: "127.0.0.1:17777",
FollowerBroker: followerAddr,
Epoch: 1,
})
if err != nil {
t.Fatal(err)
}
select {
case <-lp.Replica.Broken():
case <-time.After(10 * time.Second):
t.Fatal("pair did not break")
}
fencePath := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
time.Sleep(200 * time.Millisecond)
if fenceSealed(f.entry(fencePath)) {
t.Fatal("generation ended before its partition was registered")
}
leader.localTopicManager.AddLocalPartition(fenceTestTopic, lp)
go leader.watchReplica(fenceTestTopic, fenceTestPartition, lp, 1)
for deadline := time.Now().Add(10 * time.Second); !fenceSealed(f.entry(fencePath)); time.Sleep(20 * time.Millisecond) {
if time.Now().After(deadline) {
t.Fatal("generation not ended once registered")
}
}
if leader.localTopicManager.GetLocalPartition(fenceTestTopic, fenceTestPartition) == lp {
t.Fatal("ended generation still registered")
}
}
+3 -1
View File
@@ -70,7 +70,9 @@ type MessageQueueBroker struct {
SubCoordinator *sub_coordinator.SubCoordinator
// Removed gatewayRegistry - no longer needed
accessLock sync.Mutex
fca *filer_client.FilerClientAccessor
// orders read-modify-writes of topic.conf, all of which run on the balancer
topicConfLock sync.Mutex
fca *filer_client.FilerClientAccessor
// Unified topic cache for both existence and configuration
// Caches topic config (positive: conf != nil) and non-existence (negative: conf == nil)
// Eliminates 60% CPU overhead from repeated filer reads and JSON unmarshaling
@@ -71,6 +71,8 @@ func (b *MessageQueueBroker) getTopicConfFromCache(t topic.Topic) (*mq_pb.Config
// Cache miss or expired - read from filer
glog.V(4).Infof("Topic cache MISS for %s, reading from filer", topicKey)
b.topicConfLock.Lock()
defer b.topicConfLock.Unlock()
conf, readConfErr := b.fca.ReadTopicConfFromFiler(t)
if readConfErr != nil {
@@ -183,7 +185,7 @@ func (b *MessageQueueBroker) genLocalPartitionFromFiler(t topic.Topic, partition
if pb.ServerAddress(assignment.LeaderBroker).Equals(self) && partition.LogicalEquals(assignmentPartition) {
partition = assignmentPartition
glog.V(4).Infof("Creating local partition for %s %s", t, partition)
if localPartition, err = b.newLeaderPartition(t, partition, assignment.Epoch); err != nil {
if localPartition, err = b.newLeaderPartition(t, partition, assignment); err != nil {
return nil, false, err
}
@@ -191,6 +193,7 @@ func (b *MessageQueueBroker) genLocalPartitionFromFiler(t topic.Topic, partition
localPartition.Shutdown()
return nil, false, fmt.Errorf("broker is stopping")
}
go b.watchReplica(t, partition, localPartition, assignment.Epoch)
isGenerated = true
glog.V(4).Infof("Successfully added local partition %s %s to localTopicManager", t, partition)
break
@@ -55,7 +55,7 @@ func (b *MessageQueueBroker) genLogFlushFunc(t topic.Topic, p topic.Partition, f
b.accessLock.Lock()
defer b.accessLock.Unlock()
if localPartition := b.localTopicManager.GetLocalPartition(t, p); localPartition != nil {
localPartition.NotifyLogFlushed(logBuffer.GetLastFlushTsNs())
localPartition.NotifyLogFlushed(maxOffset)
}
glog.V(0).Infof("flushing at %d to %s size %d from buffer %s (offsets %d-%d)", logBuffer.GetLastFlushTsNs(), targetFile, len(buf), logBuffer.GetName(), minOffset, maxOffset)
+1 -1
View File
@@ -74,7 +74,7 @@ func (b *MessageQueueBroker) writeLogFile(ctx context.Context, fence *topic.Part
}
}
condition := fenceTokenCondition(fence.Token)
condition := fenceTokenCondition(fence.Token())
mutation := &filer_pb.ObjectMutation{Type: filer_pb.ObjectMutation_PUT, Directory: dir, Entry: entry}
requestId := uuid.NewString()
err := retryLogWrite(ctx, targetFile, func() error {
+2 -2
View File
@@ -72,7 +72,7 @@ func TestStoppingBrokerAbandonsAFailingFlush(t *testing.T) {
currentFiler: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port),
flushCtx: flushCtx,
}
fence := &topic.PartitionFence{Path: topic.PartitionFencePath(fenceTestTopic, fenceTestPartition), Token: "token"}
fence := topic.NewPartitionFence(topic.PartitionFencePath(fenceTestTopic, fenceTestPartition), 0, "token")
flush := b.genLogFlushFunc(fenceTestTopic, fenceTestPartition, fence)
logBuffer := log_buffer.NewLogBuffer("test", time.Hour, flush, nil, nil)
defer logBuffer.ShutdownLogBuffer()
@@ -136,7 +136,7 @@ func TestFlushWritesOneFencedFilePerWindow(t *testing.T) {
if txn.LockKey != fence.Path || txn.ConditionKey != fence.Path || txn.RouteKey != s3_constants.ObjectWriteRouteKeyPrefix+fence.Path {
t.Errorf("transaction keys lock=%q condition=%q route=%q", txn.LockKey, txn.ConditionKey, txn.RouteKey)
}
if clauses := txn.Condition.GetClauses(); len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || len(clauses[0].Etags) != 1 || clauses[0].Etags[0] != fence.Token {
if clauses := txn.Condition.GetClauses(); len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || len(clauses[0].Etags) != 1 || clauses[0].Etags[0] != fence.Token() {
t.Errorf("condition %v, want the held fence's token", txn.Condition)
}
@@ -72,6 +72,8 @@ func MapBrokerErrorToKafka(brokerErrorCode int32) int16 {
return kafkaErrorCodeNetworkException
case 102: // BrokerErrorFollowerConnectionFailed
return kafkaErrorCodeNetworkException
case 103: // BrokerErrorGenerationEnded: the partition moves to a new pair
return kafkaErrorCodeNotLeaderOrFollower
default:
// Unknown broker error code, default to unknown server error
return kafkaErrorCodeUnknownServerError
@@ -30,6 +30,7 @@ func TestMapBrokerErrorToKafka(t *testing.T) {
{"Publisher not found", 100, kafkaErrorCodeUnknownServerError},
{"Connection failed", 101, kafkaErrorCodeNetworkException},
{"Follower connection failed", 102, kafkaErrorCodeNetworkException},
{"Generation ended", 103, kafkaErrorCodeNotLeaderOrFollower},
{"Unknown error code", 999, kafkaErrorCodeUnknownServerError},
}
+28
View File
@@ -1,7 +1,9 @@
package pub_balancer
import (
"cmp"
"math/rand/v2"
"slices"
"time"
cmap "github.com/orcaman/concurrent-map/v2"
@@ -149,3 +151,29 @@ func EnsureAssignmentsToActiveBrokers(activeBrokers cmap.ConcurrentMap[string, *
glog.V(4).Infof("EnsureAssignmentsToActiveBrokers: activeBrokers: %v, followerCount: %d, assignments: %v hasChanges: %v", activeBrokers.Count(), followerCount, assignments, hasChanges)
return
}
// ReassignPartition gives a partition whose pair broke a new pair and the next epoch,
// preferring brokers outside the old pair, which may hold the broken half.
func ReassignPartition(activeBrokers cmap.ConcurrentMap[string, *BrokerStats], assignment *mq_pb.BrokerPartitionAssignment) {
candidates := make([]string, 0, activeBrokers.Count())
for brokerStatsItem := range activeBrokers.IterBuffered() {
candidates = append(candidates, brokerStatsItem.Key)
}
pick := func(excluded ...string) string {
var pool []string
for _, c := range candidates {
if !slices.ContainsFunc(excluded, func(e string) bool { return e != "" && pb.ServerAddress(c).Equals(pb.ServerAddress(e)) }) {
pool = append(pool, c)
}
}
if picked := pickBrokersExcluded(pool, 1, "", ""); len(picked) > 0 {
return picked[0]
}
return ""
}
oldLeader, oldFollower := assignment.LeaderBroker, assignment.FollowerBroker
leader := cmp.Or(pick(oldLeader, oldFollower), pick(oldLeader), pick(), oldLeader)
follower := cmp.Or(pick(leader, oldLeader, oldFollower), pick(leader, oldLeader), pick(leader))
assignment.LeaderBroker, assignment.FollowerBroker = leader, follower
assignment.Epoch++
}
+21
View File
@@ -277,3 +277,24 @@ func TestEnsureAssignmentsBumpsEpochOnlyWithTheLeader(t *testing.T) {
assert.True(t, EnsureAssignmentsToActiveBrokers(brokerSet("localhost:1"), 1, []*mq_pb.BrokerPartitionAssignment{unassigned}))
assert.Equal(t, int64(1), unassigned.Epoch)
}
func TestReassignPartitionPrefersBrokersOutsideTheOldPair(t *testing.T) {
assignment := &mq_pb.BrokerPartitionAssignment{LeaderBroker: "localhost:1", FollowerBroker: "localhost:2", Epoch: 4}
ReassignPartition(brokerSet("localhost:1", "localhost:2", "localhost:3", "localhost:4"), assignment)
assert.Equal(t, int64(5), assignment.Epoch)
assert.NotContains(t, []string{"localhost:1", "localhost:2"}, assignment.LeaderBroker)
assert.NotContains(t, []string{"localhost:1", "localhost:2", assignment.LeaderBroker}, assignment.FollowerBroker)
// with only the survivor and one more broker, the pair is rebuilt from them
assignment = &mq_pb.BrokerPartitionAssignment{LeaderBroker: "localhost:1", FollowerBroker: "localhost:2", Epoch: 4}
ReassignPartition(brokerSet("localhost:2", "localhost:3"), assignment)
assert.Equal(t, "localhost:3", assignment.LeaderBroker)
assert.Equal(t, "localhost:2", assignment.FollowerBroker)
assert.Equal(t, int64(5), assignment.Epoch)
// a lone survivor leads without a follower
assignment = &mq_pb.BrokerPartitionAssignment{LeaderBroker: "localhost:1", FollowerBroker: "localhost:2", Epoch: 4}
ReassignPartition(brokerSet("localhost:2"), assignment)
assert.Equal(t, "localhost:2", assignment.LeaderBroker)
assert.Equal(t, "", assignment.FollowerBroker)
}
+1
View File
@@ -151,6 +151,7 @@ func (manager *LocalTopicManager) markRetiring(t Topic, p *LocalPartition) {
manager.retiring[p] = r
go func() {
p.LogBuffer.WaitForShutdown()
p.closeReplica()
manager.retiringMu.Lock()
delete(manager.retiring, p)
manager.retiringMu.Unlock()
+23 -112
View File
@@ -1,7 +1,6 @@
package topic
import (
"context"
"fmt"
"strings"
"sync"
@@ -9,13 +8,8 @@ import (
"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/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type LocalPartition struct {
@@ -34,9 +28,10 @@ type LocalPartition struct {
// held while this broker leads the partition; nil on a follower
Fence *PartitionFence
publishFolloweMeStream mq_pb.SeaweedMessaging_PublishFollowMeClient
followerGrpcConnection *grpc.ClientConn
Follower string
// replicates to the follower while this broker leads a replicated partition
Replica *Replicator
Follower string
publishMu sync.Mutex // keeps the follower's entries in offset order
// Track last activity for idle cleanup
lastActivityTime atomic.Int64 // Unix nano timestamp
@@ -75,29 +70,6 @@ func (p *LocalPartition) IsFenced() bool {
return p.Fence != nil && p.Fence.IsLost()
}
func (p *LocalPartition) Publish(message *mq_pb.DataMessage) error {
if err := p.LogBuffer.AddToBuffer(message); err != nil {
return fmt.Errorf("failed to add message to log buffer: %w", err)
}
p.UpdateActivity() // Track publish activity for idle cleanup
// maybe send to the follower
if p.publishFolloweMeStream != nil {
// println("recv", string(message.Key), message.TsNs)
if followErr := p.publishFolloweMeStream.Send(&mq_pb.PublishFollowMeRequest{
Message: &mq_pb.PublishFollowMeRequest_Data{
Data: message,
},
}); followErr != nil {
return fmt.Errorf("send to follower %s: %v", p.Follower, followErr)
}
} else {
atomic.StoreInt64(&p.AckTsNs, message.TsNs)
}
return nil
}
func (p *LocalPartition) Subscribe(clientName string, startPosition log_buffer.MessagePosition,
onNoMessageFn func() bool, eachMessageFn log_buffer.EachLogEntryFuncType) error {
var processedPosition log_buffer.MessagePosition
@@ -258,60 +230,6 @@ func (p *LocalPartition) WaitUntilNoPublishers() {
}
}
func (p *LocalPartition) MaybeConnectToFollowers(initMessage *mq_pb.PublishMessageRequest_InitMessage, grpcDialOption grpc.DialOption) (err error) {
if p.publishFolloweMeStream != nil {
return nil
}
if initMessage.FollowerBroker == "" {
return nil
}
p.Follower = initMessage.FollowerBroker
ctx := context.Background()
p.followerGrpcConnection, err = pb.GrpcDial(ctx, p.Follower, true, grpcDialOption)
if err != nil {
return fmt.Errorf("fail to dial %s: %v", p.Follower, err)
}
followerClient := mq_pb.NewSeaweedMessagingClient(p.followerGrpcConnection)
p.publishFolloweMeStream, err = followerClient.PublishFollowMe(ctx)
if err != nil {
return fmt.Errorf("fail to create publish client: %w", err)
}
if err = p.publishFolloweMeStream.Send(&mq_pb.PublishFollowMeRequest{
Message: &mq_pb.PublishFollowMeRequest_Init{
Init: &mq_pb.PublishFollowMeRequest_InitMessage{
Topic: initMessage.Topic,
Partition: initMessage.Partition,
},
},
}); err != nil {
return err
}
// start receiving ack from follower
go func() {
defer func() {
// println("stop receiving ack from follower")
}()
for {
ack, err := p.publishFolloweMeStream.Recv()
if err != nil {
e, _ := status.FromError(err)
if e.Code() == codes.Canceled {
glog.V(0).Infof("local partition %v follower %v stopped", p.Partition, p.Follower)
return
}
glog.Errorf("Receiving local partition %v follower %s ack: %v", p.Partition, p.Follower, err)
return
}
atomic.StoreInt64(&p.AckTsNs, ack.AckTsNs)
// println("recv ack", ack.AckTsNs)
}
}()
return nil
}
func (p *LocalPartition) MaybeShutdownLocalPartition() (hasShutdown bool) {
if p.Publishers.Size() == 0 && p.Subscribers.Size() == 0 {
@@ -319,20 +237,7 @@ func (p *LocalPartition) MaybeShutdownLocalPartition() (hasShutdown bool) {
for !p.LogBuffer.IsAllFlushed() {
time.Sleep(113 * time.Millisecond)
}
if p.publishFolloweMeStream != nil {
// send close to the follower
if followErr := p.publishFolloweMeStream.Send(&mq_pb.PublishFollowMeRequest{
Message: &mq_pb.PublishFollowMeRequest_Close{
Close: &mq_pb.PublishFollowMeRequest_CloseMessage{},
},
}); followErr != nil {
glog.Errorf("Error closing follower stream: %v", followErr)
}
glog.V(4).Infof("closing grpcConnection to follower")
p.followerGrpcConnection.Close()
p.publishFolloweMeStream = nil
p.Follower = ""
}
p.closeReplica()
hasShutdown = true
}
@@ -379,18 +284,24 @@ func (p *LocalPartition) Shutdown() {
glog.V(0).Infof("local partition %v shutting down", p.Partition)
}
func (p *LocalPartition) NotifyLogFlushed(flushTsNs int64) {
if p.publishFolloweMeStream != nil {
if followErr := p.publishFolloweMeStream.Send(&mq_pb.PublishFollowMeRequest{
Message: &mq_pb.PublishFollowMeRequest_Flush{
Flush: &mq_pb.PublishFollowMeRequest_FlushMessage{
TsNs: flushTsNs,
},
},
}); followErr != nil {
glog.Errorf("send follower %s flush message: %v", p.Follower, followErr)
}
// println("notifying", p.Follower, "flushed at", flushTsNs)
// closeReplica tells the follower everything is stored, or, when a flush was
// dropped, breaks the stream so the follower stores its copy instead.
func (p *LocalPartition) closeReplica() {
if p.Replica == nil {
return
}
// a dropped window drops every later one, so the watermark stops below the end
if p.LogBuffer.GetLastFlushedOffset() >= p.LogBuffer.GetOffset()-1 {
p.Replica.Close()
} else {
p.Replica.Abandon()
}
}
// NotifyLogFlushed tells the follower every entry up to offset is stored.
func (p *LocalPartition) NotifyLogFlushed(offset int64) {
if p.Replica != nil {
p.Replica.Flushed(offset)
}
}
+17 -23
View File
@@ -2,7 +2,6 @@ package topic
import (
"fmt"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -11,34 +10,29 @@ import (
)
// PublishWithOffset appends the message and returns the offset the buffer gave it.
// On a replicated partition the entry is queued for the follower in offset order.
func (p *LocalPartition) PublishWithOffset(message *mq_pb.DataMessage) (int64, error) {
offset, err := p.addToBuffer(message)
p.publishMu.Lock()
if p.Replica != nil && p.Replica.Err() != nil {
// a broken pair stores nothing new; the publisher resends to the next pair
p.publishMu.Unlock()
return 0, p.Replica.Err()
}
entry, err := p.addToBuffer(message)
if err == nil && p.Replica != nil {
err = p.Replica.Send(entry)
}
p.publishMu.Unlock()
if err != nil {
return 0, fmt.Errorf("failed to add message to buffer: %w", err)
return 0, err
}
// Track publish activity for idle cleanup (consistent with Publish method)
p.UpdateActivity()
// Send to follower if needed (same logic as original Publish)
if p.publishFolloweMeStream != nil {
if followErr := p.publishFolloweMeStream.Send(&mq_pb.PublishFollowMeRequest{
Message: &mq_pb.PublishFollowMeRequest_Data{
Data: message,
},
}); followErr != nil {
return 0, fmt.Errorf("send to follower %s: %v", p.Follower, followErr)
}
} else {
atomic.StoreInt64(&p.AckTsNs, message.TsNs)
}
return offset, nil
return entry.Offset, nil
}
// addToBuffer has the buffer assign the offset under its own lock, so offsets
// stay in append order across publishers.
func (p *LocalPartition) addToBuffer(message *mq_pb.DataMessage) (int64, error) {
func (p *LocalPartition) addToBuffer(message *mq_pb.DataMessage) (*filer_pb.LogEntry, error) {
processingTsNs := message.TsNs
if processingTsNs == 0 {
processingTsNs = time.Now().UnixNano()
@@ -51,9 +45,9 @@ func (p *LocalPartition) addToBuffer(message *mq_pb.DataMessage) (int64, error)
Offset: -1,
}
if err := p.LogBuffer.AddLogEntryToBuffer(logEntry); err != nil {
return 0, fmt.Errorf("failed to add log entry to buffer: %w", err)
return nil, fmt.Errorf("failed to add log entry to buffer: %w", err)
}
return logEntry.Offset, nil
return logEntry, nil
}
// GetOffsetInfo returns offset information for this partition
+22 -2
View File
@@ -1,24 +1,44 @@
package topic
import (
"sync"
"sync/atomic"
)
// PartitionFenceName is the partition directory entry naming the one broker allowed to write it.
const PartitionFenceName = ".fence"
// PartitionFence is the fence this broker stored; every write requires its token unchanged.
// PartitionFence is the fence this broker stored; every write requires its current token.
type PartitionFence struct {
Path string
Epoch int64
Token string
mu sync.Mutex
token string
lost atomic.Bool
}
func NewPartitionFence(path string, epoch int64, token string) *PartitionFence {
return &PartitionFence{Path: path, Epoch: epoch, token: token}
}
func PartitionFencePath(t Topic, p Partition) string {
return PartitionDir(t, p) + "/" + PartitionFenceName
}
// Token is the etag of the fence entry as this broker last wrote it.
func (f *PartitionFence) Token() string {
f.mu.Lock()
defer f.mu.Unlock()
return f.token
}
// Hold replaces the token after this broker rewrote the fence.
func (f *PartitionFence) Hold(token string) {
f.mu.Lock()
defer f.mu.Unlock()
f.token = token
}
// MarkLost records that another broker has taken the fence.
func (f *PartitionFence) MarkLost() {
f.lost.Store(true)
+229
View File
@@ -0,0 +1,229 @@
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()
}
+19
View File
@@ -61,6 +61,9 @@ service SeaweedMessaging {
}
rpc SubscribeFollowMe (stream SubscribeFollowMeRequest) returns (SubscribeFollowMeResponse) {
}
// A broker of a partition's pair reports that the pair broke; the balancer assigns a new pair
rpc EndPartitionGeneration (EndPartitionGenerationRequest) returns (EndPartitionGenerationResponse) {
}
// Stateless fetch API (Kafka-style) - request/response pattern
// This is the recommended API for Kafka gateway and other stateless clients
@@ -304,21 +307,37 @@ message PublishFollowMeRequest {
message InitMessage {
schema_pb.Topic topic = 1;
schema_pb.Partition partition = 2;
int64 epoch = 3;
string leader = 4;
}
message FlushMessage {
int64 ts_ns = 1;
int64 offset = 2; // every entry up to this offset is stored
}
message CloseMessage {
}
message HeartbeatMessage {
}
oneof message {
InitMessage init = 1;
DataMessage data = 2;
FlushMessage flush = 3;
CloseMessage close = 4;
filer_pb.LogEntry entry = 5;
HeartbeatMessage heartbeat = 6;
}
}
message PublishFollowMeResponse {
int64 ack_ts_ns = 1;
int64 ack_offset = 2; // the follower holds every entry up to this offset
}
message EndPartitionGenerationRequest {
schema_pb.Topic topic = 1;
schema_pb.Partition partition = 2;
int64 epoch = 3;
string broker = 4;
}
message EndPartitionGenerationResponse {
}
message SubscribeMessageRequest {
message InitMessage {
File diff suppressed because it is too large. Load diff
+41 -1
View File
@@ -37,6 +37,7 @@ const (
SeaweedMessaging_SubscribeMessage_FullMethodName = "/messaging_pb.SeaweedMessaging/SubscribeMessage"
SeaweedMessaging_PublishFollowMe_FullMethodName = "/messaging_pb.SeaweedMessaging/PublishFollowMe"
SeaweedMessaging_SubscribeFollowMe_FullMethodName = "/messaging_pb.SeaweedMessaging/SubscribeFollowMe"
SeaweedMessaging_EndPartitionGeneration_FullMethodName = "/messaging_pb.SeaweedMessaging/EndPartitionGeneration"
SeaweedMessaging_FetchMessage_FullMethodName = "/messaging_pb.SeaweedMessaging/FetchMessage"
SeaweedMessaging_GetUnflushedMessages_FullMethodName = "/messaging_pb.SeaweedMessaging/GetUnflushedMessages"
SeaweedMessaging_GetPartitionRangeInfo_FullMethodName = "/messaging_pb.SeaweedMessaging/GetPartitionRangeInfo"
@@ -71,6 +72,8 @@ type SeaweedMessagingClient interface {
// The lead broker asks a follower broker to follow itself
PublishFollowMe(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PublishFollowMeRequest, PublishFollowMeResponse], error)
SubscribeFollowMe(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[SubscribeFollowMeRequest, SubscribeFollowMeResponse], error)
// A broker of a partition's pair reports that the pair broke; the balancer assigns a new pair
EndPartitionGeneration(ctx context.Context, in *EndPartitionGenerationRequest, opts ...grpc.CallOption) (*EndPartitionGenerationResponse, error)
// Stateless fetch API (Kafka-style) - request/response pattern
// This is the recommended API for Kafka gateway and other stateless clients
// No streaming, no session state - each request is completely independent
@@ -287,6 +290,16 @@ func (c *seaweedMessagingClient) SubscribeFollowMe(ctx context.Context, opts ...
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type SeaweedMessaging_SubscribeFollowMeClient = grpc.ClientStreamingClient[SubscribeFollowMeRequest, SubscribeFollowMeResponse]
func (c *seaweedMessagingClient) EndPartitionGeneration(ctx context.Context, in *EndPartitionGenerationRequest, opts ...grpc.CallOption) (*EndPartitionGenerationResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(EndPartitionGenerationResponse)
err := c.cc.Invoke(ctx, SeaweedMessaging_EndPartitionGeneration_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *seaweedMessagingClient) FetchMessage(ctx context.Context, in *FetchMessageRequest, opts ...grpc.CallOption) (*FetchMessageResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(FetchMessageResponse)
@@ -355,6 +368,8 @@ type SeaweedMessagingServer interface {
// The lead broker asks a follower broker to follow itself
PublishFollowMe(grpc.BidiStreamingServer[PublishFollowMeRequest, PublishFollowMeResponse]) error
SubscribeFollowMe(grpc.ClientStreamingServer[SubscribeFollowMeRequest, SubscribeFollowMeResponse]) error
// A broker of a partition's pair reports that the pair broke; the balancer assigns a new pair
EndPartitionGeneration(context.Context, *EndPartitionGenerationRequest) (*EndPartitionGenerationResponse, error)
// Stateless fetch API (Kafka-style) - request/response pattern
// This is the recommended API for Kafka gateway and other stateless clients
// No streaming, no session state - each request is completely independent
@@ -427,6 +442,9 @@ func (UnimplementedSeaweedMessagingServer) PublishFollowMe(grpc.BidiStreamingSer
func (UnimplementedSeaweedMessagingServer) SubscribeFollowMe(grpc.ClientStreamingServer[SubscribeFollowMeRequest, SubscribeFollowMeResponse]) error {
return status.Errorf(codes.Unimplemented, "method SubscribeFollowMe not implemented")
}
func (UnimplementedSeaweedMessagingServer) EndPartitionGeneration(context.Context, *EndPartitionGenerationRequest) (*EndPartitionGenerationResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method EndPartitionGeneration not implemented")
}
func (UnimplementedSeaweedMessagingServer) FetchMessage(context.Context, *FetchMessageRequest) (*FetchMessageResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method FetchMessage not implemented")
}
@@ -447,7 +465,7 @@ type UnsafeSeaweedMessagingServer interface {
}
func RegisterSeaweedMessagingServer(s grpc.ServiceRegistrar, srv SeaweedMessagingServer) {
// If the following call pancis, it indicates UnimplementedSeaweedMessagingServer was
// If the following call panics, it indicates UnimplementedSeaweedMessagingServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
@@ -715,6 +733,24 @@ func _SeaweedMessaging_SubscribeFollowMe_Handler(srv interface{}, stream grpc.Se
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type SeaweedMessaging_SubscribeFollowMeServer = grpc.ClientStreamingServer[SubscribeFollowMeRequest, SubscribeFollowMeResponse]
func _SeaweedMessaging_EndPartitionGeneration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EndPartitionGenerationRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SeaweedMessagingServer).EndPartitionGeneration(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: SeaweedMessaging_EndPartitionGeneration_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SeaweedMessagingServer).EndPartitionGeneration(ctx, req.(*EndPartitionGenerationRequest))
}
return interceptor(ctx, in, info, handler)
}
func _SeaweedMessaging_FetchMessage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FetchMessageRequest)
if err := dec(in); err != nil {
@@ -817,6 +853,10 @@ var SeaweedMessaging_ServiceDesc = grpc.ServiceDesc{
MethodName: "CloseSubscribers",
Handler: _SeaweedMessaging_CloseSubscribers_Handler,
},
{
MethodName: "EndPartitionGeneration",
Handler: _SeaweedMessaging_EndPartitionGeneration_Handler,
},
{
MethodName: "FetchMessage",
Handler: _SeaweedMessaging_FetchMessage_Handler,
+5
View File
@@ -793,6 +793,11 @@ func (logBuffer *LogBuffer) NoteFlushDropped(n int) {
logBuffer.flushDroppedBytes.Add(int64(n))
}
// GetLastFlushedOffset returns the highest offset a landed flush stored, or -1.
func (logBuffer *LogBuffer) GetLastFlushedOffset() int64 {
return logBuffer.lastFlushedOffset.Load()
}
// IsAllFlushed returns true if all data in the buffer has been flushed, after calling ShutdownLogBuffer().
func (logBuffer *LogBuffer) IsAllFlushed() bool {
return logBuffer.isAllFlushed