mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* mq: report the caller's deadline when a broker sees it first doConfigureTopic checked ctx.Err() to tell the caller's deadline from a broker failure. A broker's DeadlineExceeded status (or its RST_STREAM, which gRPC maps to DeadlineExceeded once the deadline has passed) can arrive before the context's own timer has run, so ctx.Err() was still nil and NewTopicPublisher returned the wrapped gRPC error instead of context.DeadlineExceeded. Once the deadline is behind us, wait for the context's timer before reading ctx.Err(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: let the configure call start before its deadline passes in the test The deadline the test reported had already passed when NewTopicPublisher started, so the check before the first broker caught it and the check after the call was never exercised. The fake broker now moves the deadline behind us only once it has the call, and answers with its own DeadlineExceeded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
489 lines
13 KiB
Go
489 lines
13 KiB
Go
package pub_client
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
|
)
|
|
|
|
const (
|
|
maxBufferedMessages = 1024 // per partition, queued plus sent but not yet acked
|
|
lookupMinBackoff = 100 * time.Millisecond
|
|
lookupMaxBackoff = 5 * time.Second
|
|
lookupTimeout = 10 * time.Second // per broker, so a stalled one does not hold up the next
|
|
)
|
|
|
|
// EachPartitionPublishJob owns one partition's queue and unacked messages across
|
|
// the publish streams opened to whichever broker leads the partition.
|
|
type EachPartitionPublishJob struct {
|
|
*mq_pb.BrokerPartitionAssignment
|
|
inputQueue chan *mq_pb.DataMessage
|
|
slots chan struct{}
|
|
enqueueLock sync.Mutex
|
|
accepted atomic.Int64 // data messages enqueued and not yet acked
|
|
|
|
inflightLock sync.Mutex
|
|
inflight []*mq_pb.DataMessage // sent but not acked, in send order
|
|
waiters map[int64]chan struct{} // by TsNs, closed on ack
|
|
inputDrained bool
|
|
|
|
// guarded by TopicPublisher.Mutex
|
|
running bool
|
|
done bool
|
|
cancel context.CancelFunc
|
|
wg sync.WaitGroup
|
|
}
|
|
|
|
func (p *TopicPublisher) startSchedulerThread(ready chan struct{}) {
|
|
defer close(p.schedulerDone)
|
|
|
|
glog.V(0).Infof("start scheduler thread for topic %s", p.config.Topic)
|
|
|
|
lookupCtx, cancelLookups := context.WithCancel(context.Background())
|
|
defer cancelLookups()
|
|
go func() {
|
|
select {
|
|
case <-p.stopped:
|
|
cancelLookups()
|
|
case <-lookupCtx.Done():
|
|
}
|
|
}()
|
|
|
|
isReady := false
|
|
var backoff time.Duration
|
|
for {
|
|
if backoff > 0 {
|
|
select {
|
|
case <-time.After(backoff):
|
|
case <-p.stopped:
|
|
p.stopJobs()
|
|
return
|
|
}
|
|
}
|
|
backoff = min(max(2*backoff, lookupMinBackoff), lookupMaxBackoff)
|
|
|
|
assignments, err := p.doLookupTopicPartitions(lookupCtx)
|
|
if err != nil {
|
|
glog.Errorf("lookup topic %s: %v", p.config.Topic, err)
|
|
continue
|
|
}
|
|
p.onEachAssignments(assignments)
|
|
if !isReady {
|
|
isReady = true
|
|
close(ready)
|
|
}
|
|
|
|
// wait until a partition needs a new leader
|
|
healthySince := time.Now()
|
|
for !p.hasIdleJob() {
|
|
if p.allJobsDone() {
|
|
return
|
|
}
|
|
select {
|
|
case <-p.jobEnded:
|
|
case <-p.stopped:
|
|
p.stopJobs()
|
|
return
|
|
}
|
|
}
|
|
if time.Since(healthySince) > lookupMaxBackoff {
|
|
backoff = lookupMinBackoff
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *TopicPublisher) onEachAssignments(assignments []*mq_pb.BrokerPartitionAssignment) {
|
|
sort.Slice(assignments, func(i, j int) bool {
|
|
return assignments[i].Partition.RangeStart < assignments[j].Partition.RangeStart
|
|
})
|
|
p.inputLock.RLock()
|
|
defer p.inputLock.RUnlock()
|
|
for _, assignment := range assignments {
|
|
if assignment.Partition == nil {
|
|
continue
|
|
}
|
|
p.Lock()
|
|
job, found := p.partition2Buffer.Find(assignment.Partition.RangeStart, assignment.Partition.RangeStop)
|
|
if !found {
|
|
job = &EachPartitionPublishJob{
|
|
inputQueue: make(chan *mq_pb.DataMessage, maxBufferedMessages+1),
|
|
slots: make(chan struct{}, maxBufferedMessages),
|
|
}
|
|
if p.inputClosed {
|
|
close(job.inputQueue)
|
|
}
|
|
p.jobs = append(p.jobs, job)
|
|
p.partition2Buffer.Insert(assignment.Partition.RangeStart, assignment.Partition.RangeStop, job)
|
|
}
|
|
if job.done {
|
|
p.Unlock()
|
|
continue
|
|
}
|
|
if job.running {
|
|
if pb.ServerAddress(job.LeaderBroker).Equals(pb.ServerAddress(assignment.LeaderBroker)) {
|
|
p.Unlock()
|
|
continue
|
|
}
|
|
cancel := job.cancel
|
|
p.Unlock()
|
|
cancel()
|
|
job.wg.Wait()
|
|
p.Lock()
|
|
if job.done {
|
|
p.Unlock()
|
|
continue
|
|
}
|
|
}
|
|
job.BrokerPartitionAssignment = assignment
|
|
if assignment.LeaderBroker != "" {
|
|
p.startJob(job)
|
|
}
|
|
p.Unlock()
|
|
}
|
|
}
|
|
|
|
// startJob runs one publish stream for the job; the caller holds p.Mutex.
|
|
func (p *TopicPublisher) startJob(job *EachPartitionPublishJob) {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
job.running = true
|
|
job.cancel = cancel
|
|
job.wg.Add(1)
|
|
assignment := job.BrokerPartitionAssignment
|
|
go func() {
|
|
defer job.wg.Done()
|
|
err := p.doPublishToPartition(ctx, job, assignment)
|
|
cancel()
|
|
if err != nil {
|
|
glog.Warningf("publish to %s partition %v on %s: %v", p.config.Topic, assignment.Partition, assignment.LeaderBroker, err)
|
|
}
|
|
p.Lock()
|
|
job.running = false
|
|
job.done = err == nil
|
|
p.Unlock()
|
|
select {
|
|
case p.jobEnded <- struct{}{}:
|
|
default:
|
|
}
|
|
}()
|
|
}
|
|
|
|
func (p *TopicPublisher) hasIdleJob() bool {
|
|
p.Lock()
|
|
defer p.Unlock()
|
|
for _, job := range p.jobs {
|
|
if !job.running && !job.done {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (p *TopicPublisher) allJobsDone() bool {
|
|
p.Lock()
|
|
defer p.Unlock()
|
|
for _, job := range p.jobs {
|
|
if !job.done {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (p *TopicPublisher) stopJobs() {
|
|
p.Lock()
|
|
jobs := p.jobs
|
|
for _, job := range jobs {
|
|
if job.running {
|
|
job.cancel()
|
|
}
|
|
}
|
|
p.Unlock()
|
|
for _, job := range jobs {
|
|
job.wg.Wait()
|
|
}
|
|
}
|
|
|
|
// doPublishToPartition resends the job's unacked messages, then publishes its queue,
|
|
// until the queue is closed and everything is acked or the stream fails.
|
|
func (p *TopicPublisher) doPublishToPartition(ctx context.Context, job *EachPartitionPublishJob, assignment *mq_pb.BrokerPartitionAssignment) error {
|
|
glog.V(1).Infof("connecting to %v for topic %s partition %v", assignment.LeaderBroker, p.config.Topic, assignment.Partition)
|
|
|
|
return pb.WithBrokerGrpcClient(true, assignment.LeaderBroker, p.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error {
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
stream, err := client.PublishMessage(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("create publish client: %w", err)
|
|
}
|
|
if err = stream.Send(&mq_pb.PublishMessageRequest{
|
|
Message: &mq_pb.PublishMessageRequest_Init{
|
|
Init: &mq_pb.PublishMessageRequest_InitMessage{
|
|
Topic: p.config.Topic.ToPbTopic(),
|
|
Partition: assignment.Partition,
|
|
AckInterval: 128,
|
|
FollowerBroker: assignment.FollowerBroker,
|
|
PublisherName: p.config.PublisherName,
|
|
},
|
|
},
|
|
}); err != nil {
|
|
return fmt.Errorf("send init message: %w", err)
|
|
}
|
|
resp, err := stream.Recv()
|
|
if err != nil {
|
|
return fmt.Errorf("recv init response: %w", err)
|
|
}
|
|
if err = responseError(resp); err != nil {
|
|
return fmt.Errorf("init: %w", err)
|
|
}
|
|
|
|
finished := make(chan struct{})
|
|
var finishOnce sync.Once
|
|
finish := func() { finishOnce.Do(func() { close(finished) }) }
|
|
|
|
ackErr := make(chan error, 1)
|
|
var acks sync.WaitGroup
|
|
acks.Add(1)
|
|
go func() {
|
|
defer acks.Done()
|
|
err := job.receiveAcks(stream, finish)
|
|
if err != nil {
|
|
// unblock a Send stuck on flow control
|
|
cancel()
|
|
}
|
|
ackErr <- err
|
|
}()
|
|
defer acks.Wait()
|
|
defer cancel()
|
|
|
|
send := func(data *mq_pb.DataMessage) error {
|
|
if err := stream.Send(&mq_pb.PublishMessageRequest{
|
|
Message: &mq_pb.PublishMessageRequest_Data{
|
|
Data: data,
|
|
},
|
|
}); err != nil {
|
|
return fmt.Errorf("send publish data: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
for _, data := range job.unacked() {
|
|
if err := send(data); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
queue := job.inputQueue
|
|
for {
|
|
select {
|
|
case data, ok := <-queue:
|
|
if !ok {
|
|
queue = nil
|
|
if job.markDrained() {
|
|
finish()
|
|
}
|
|
continue
|
|
}
|
|
job.addInflight(data)
|
|
if err := send(data); err != nil {
|
|
return err
|
|
}
|
|
case <-finished:
|
|
// the broker answers the close with EOF, which receiveAcks takes as success
|
|
finished = nil
|
|
if err := stream.CloseSend(); err != nil {
|
|
return fmt.Errorf("close send: %w", err)
|
|
}
|
|
case err := <-ackErr:
|
|
return err
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
func responseError(resp *mq_pb.PublishMessageResponse) error {
|
|
if resp.Error != "" || resp.ErrorCode != 0 {
|
|
return fmt.Errorf("broker error %d: %s", resp.ErrorCode, resp.Error)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// receiveAcks calls finish once the input is drained and every message is acked,
|
|
// and returns nil when the broker then ends the stream.
|
|
func (job *EachPartitionPublishJob) receiveAcks(stream mq_pb.SeaweedMessaging_PublishMessageClient, finish func()) error {
|
|
for {
|
|
resp, err := stream.Recv()
|
|
if err == io.EOF && job.isFinished() {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("receive ack: %w", err)
|
|
}
|
|
if err = responseError(resp); err != nil {
|
|
return err
|
|
}
|
|
if resp.AckTsNs > 0 && job.ack(resp.AckTsNs) {
|
|
finish()
|
|
}
|
|
}
|
|
}
|
|
|
|
func (job *EachPartitionPublishJob) addInflight(data *mq_pb.DataMessage) {
|
|
job.inflightLock.Lock()
|
|
job.inflight = append(job.inflight, data)
|
|
job.inflightLock.Unlock()
|
|
}
|
|
|
|
func (job *EachPartitionPublishJob) addWaiter(tsNs int64, acked chan struct{}) {
|
|
job.inflightLock.Lock()
|
|
if job.waiters == nil {
|
|
job.waiters = make(map[int64]chan struct{})
|
|
}
|
|
job.waiters[tsNs] = acked
|
|
job.inflightLock.Unlock()
|
|
}
|
|
|
|
func (job *EachPartitionPublishJob) unacked() []*mq_pb.DataMessage {
|
|
job.inflightLock.Lock()
|
|
defer job.inflightLock.Unlock()
|
|
return append([]*mq_pb.DataMessage(nil), job.inflight...)
|
|
}
|
|
|
|
// ack drops every in-flight message up to tsNs and reports whether the job is finished.
|
|
func (job *EachPartitionPublishJob) ack(tsNs int64) bool {
|
|
job.inflightLock.Lock()
|
|
defer job.inflightLock.Unlock()
|
|
n := 0
|
|
for n < len(job.inflight) && job.inflight[n].TsNs <= tsNs {
|
|
if job.inflight[n].Ctrl == nil {
|
|
<-job.slots
|
|
job.accepted.Add(-1)
|
|
if waiter, ok := job.waiters[job.inflight[n].TsNs]; ok {
|
|
close(waiter)
|
|
delete(job.waiters, job.inflight[n].TsNs)
|
|
}
|
|
}
|
|
job.inflight[n] = nil
|
|
n++
|
|
}
|
|
job.inflight = job.inflight[n:]
|
|
return job.inputDrained && len(job.inflight) == 0
|
|
}
|
|
|
|
// markDrained records that the closed input is empty and reports whether nothing is left to ack.
|
|
func (job *EachPartitionPublishJob) markDrained() bool {
|
|
job.inflightLock.Lock()
|
|
defer job.inflightLock.Unlock()
|
|
job.inputDrained = true
|
|
return len(job.inflight) == 0
|
|
}
|
|
|
|
func (job *EachPartitionPublishJob) isFinished() bool {
|
|
job.inflightLock.Lock()
|
|
defer job.inflightLock.Unlock()
|
|
return job.inputDrained && len(job.inflight) == 0
|
|
}
|
|
|
|
// unackedCount counts accepted data messages not yet acked, not a Publish still waiting to enqueue.
|
|
func (job *EachPartitionPublishJob) unackedCount() int {
|
|
return int(job.accepted.Load())
|
|
}
|
|
|
|
func (p *TopicPublisher) doConfigureTopic(ctx context.Context) (err error) {
|
|
if len(p.config.Brokers) == 0 {
|
|
return fmt.Errorf("topic configuring found no bootstrap brokers")
|
|
}
|
|
var lastErr error
|
|
for _, brokerAddress := range p.config.Brokers {
|
|
if err := callerContextErr(ctx); err != nil {
|
|
return err
|
|
}
|
|
// The configured dial option belongs to this publisher. A process-wide
|
|
// address cache can reuse a connection opened with different credentials.
|
|
err = pb.WithBrokerGrpcClient(true,
|
|
brokerAddress,
|
|
p.grpcDialOption,
|
|
func(client mq_pb.SeaweedMessagingClient) error {
|
|
callCtx, cancel := context.WithTimeout(ctx, configureTopicTimeout)
|
|
defer cancel()
|
|
_, err := client.ConfigureTopic(callCtx, &mq_pb.ConfigureTopicRequest{
|
|
Topic: p.config.Topic.ToPbTopic(),
|
|
PartitionCount: p.config.PartitionCount,
|
|
MessageRecordType: p.config.RecordType, // Flat schema
|
|
})
|
|
return err
|
|
})
|
|
if err == nil {
|
|
lastErr = nil
|
|
return nil
|
|
} else {
|
|
lastErr = fmt.Errorf("%s: %w", brokerAddress, err)
|
|
}
|
|
}
|
|
|
|
if err := callerContextErr(ctx); err != nil {
|
|
return err
|
|
}
|
|
if lastErr != nil {
|
|
return fmt.Errorf("doConfigureTopic %s: %w", p.config.Topic, lastErr)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// callerContextErr is ctx.Err(), except that once ctx's deadline is behind us it
|
|
// waits for ctx's own timer: a broker can report the deadline a tick before
|
|
// ctx.Err() becomes visible.
|
|
func callerContextErr(ctx context.Context) error {
|
|
if deadline, ok := ctx.Deadline(); ok && !deadline.After(time.Now()) {
|
|
<-ctx.Done()
|
|
}
|
|
return ctx.Err()
|
|
}
|
|
|
|
func (p *TopicPublisher) doLookupTopicPartitions(ctx context.Context) (assignments []*mq_pb.BrokerPartitionAssignment, err error) {
|
|
if len(p.config.Brokers) == 0 {
|
|
return nil, fmt.Errorf("lookup found no bootstrap brokers")
|
|
}
|
|
var lastErr error
|
|
for _, brokerAddress := range p.config.Brokers {
|
|
err := pb.WithBrokerGrpcClient(true,
|
|
brokerAddress,
|
|
p.grpcDialOption,
|
|
func(client mq_pb.SeaweedMessagingClient) error {
|
|
ctx, cancel := context.WithTimeout(ctx, lookupTimeout)
|
|
defer cancel()
|
|
lookupResp, err := client.LookupTopicBrokers(ctx,
|
|
&mq_pb.LookupTopicBrokersRequest{
|
|
Topic: p.config.Topic.ToPbTopic(),
|
|
})
|
|
glog.V(0).Infof("lookup topic %s: %v", p.config.Topic, lookupResp)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(lookupResp.BrokerPartitionAssignments) == 0 {
|
|
return fmt.Errorf("no broker partition assignments")
|
|
}
|
|
|
|
assignments = lookupResp.BrokerPartitionAssignments
|
|
|
|
return nil
|
|
})
|
|
if err == nil {
|
|
return assignments, nil
|
|
} else {
|
|
lastErr = err
|
|
}
|
|
}
|
|
|
|
return nil, fmt.Errorf("lookup topic %s: %v", p.config.Topic, lastErr)
|
|
|
|
}
|