package s3notification import ( "context" "errors" "fmt" "maps" "math" "reflect" "slices" "strings" "sync" "sync/atomic" "time" "github.com/seaweedfs/seaweedfs/weed/cluster" "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/mq/broker" "github.com/seaweedfs/seaweedfs/weed/mq/offset" "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/stats" "google.golang.org/grpc" "google.golang.org/protobuf/proto" ) const ( // ForwarderGroup is the consumer group forwarders store their offsets under. ForwarderGroup = "forwarder" // claimedPosition marks an offset a lead claimed but read nothing from yet claimedPosition = "claimed" // ForwarderLockPrefix and the target name make the lock that elects the // gateway forwarding a target. ForwarderLockPrefix = "s3.notify." forwardBatchMessages = 100 forwardBatchBytes = 1 << 20 forwardRPCTimeout = 30 * time.Second forwardLockCheckInterval = time.Second forwardIdleWait = time.Second forwardMinBackoff = time.Second forwardMaxBackoff = time.Minute forwardPartitionRefresh = 30 * time.Second forwardHoldLogInterval = time.Minute forwardStallWarnInterval = time.Minute // A lock still held this long after a refused save was renewed after the // refusal, so the generation that refused it no longer holds the lock. forwardReclaimWait = 2 * lock_manager.LiveLockTTL ) // errDeposed means a newer forwarder of the target stored a partition's offset. var errDeposed = errors.New("a newer forwarder holds the target") // forwarderLock is what a forwarder needs from cluster.LiveLock. type forwarderLock interface { IsLocked() bool Generation() int64 Stop() error } // positionStore is what a forwarder needs from offset.ConsumerGroupOffsetStorage. type positionStore interface { LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string) (*offset.ConsumerGroupPosition, error) SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string, position *offset.ConsumerGroupPosition) error ListConsumerGroupPositions(ctx context.Context, t topic.Topic, consumerGroup string, skip func(dir string) bool) (map[string]*offset.ConsumerGroupPosition, error) } // Forwarder delivers each target's topic to the target's destination. Every // gateway runs one, and a lock per target elects the gateway that forwards // it, so targets spread across gateways. A topic target has no forwarder. type Forwarder struct { brokers func() []string grpcDialOption grpc.DialOption positions positionStore owner string startLock func(key string) forwarderLock newDestination func(t *Target) destination lockCheckInterval time.Duration idleWait time.Duration minBackoff time.Duration maxBackoff time.Duration reclaimWait time.Duration partitionRefresh time.Duration // loopEnded, when set, runs as a forwarding loop ends, after it is marked ended loopEnded func(err error) mu sync.Mutex targets map[string]*targetForwarder // stopping are removed targets not done releasing their locks, which Close waits for stopping map[*targetForwarder]bool closed bool } // NewForwarder returns a forwarder that reads topics through the brokers listed // by brokers, stores offsets in positions, and elects itself per target through // lockClient as owner, which must be unique to this gateway process. func NewForwarder(brokers func() []string, grpcDialOption grpc.DialOption, positions positionStore, lockClient *cluster.LockClient, owner string) *Forwarder { return &Forwarder{ brokers: brokers, grpcDialOption: grpcDialOption, positions: positions, owner: owner, startLock: func(key string) forwarderLock { return lockClient.StartLongLivedLock(key, owner, func(newOwner string) { glog.V(1).Infof("notification forwarder lock %s is held by %s", key, newOwner) }, lock_manager.LiveLockTTL) }, newDestination: newDestination, lockCheckInterval: forwardLockCheckInterval, idleWait: forwardIdleWait, minBackoff: forwardMinBackoff, maxBackoff: forwardMaxBackoff, reclaimWait: forwardReclaimWait, partitionRefresh: forwardPartitionRefresh, targets: map[string]*targetForwarder{}, stopping: map[*targetForwarder]bool{}, } } // newDestination is the destination of a target type that has a forwarder, or nil. func newDestination(t *Target) destination { if t.Type == TargetTypeWebhook { return newWebhook(t) } return nil } // Sync runs a forwarder for every enabled target in reg that has a destination, // stops the others, and hands a changed target's settings to its forwarder. func (f *Forwarder) Sync(reg *Registry) { f.mu.Lock() defer f.mu.Unlock() if f.closed { return } want := map[string]*Target{} for _, name := range reg.Names() { if t, ok := reg.Lookup(name); ok && t.Enabled && t.Type != TargetTypeTopic { want[name] = t } } for name, tf := range f.targets { if t := want[name]; t == nil || t.Type != tf.settings().target.Type { tf.cancel() delete(f.targets, name) f.stopping[tf] = true go func() { <-tf.done f.mu.Lock() delete(f.stopping, tf) f.mu.Unlock() }() } } for name, t := range want { tf := f.targets[name] if tf != nil && reflect.DeepEqual(tf.settings().target, t) { continue } dest := f.newDestination(t) if dest == nil { glog.V(1).Infof("notification target %s: type %s has no forwarder yet", name, t.Type) continue } if tf != nil { tf.current.Store(&forwardSettings{target: t, dest: dest}) continue } f.targets[name] = f.start(t, dest) } } // Close stops every forwarder and waits for each to release its lock. func (f *Forwarder) Close() { f.mu.Lock() f.closed = true stopping := make([]*targetForwarder, 0, len(f.targets)) for name, tf := range f.targets { tf.cancel() stopping = append(stopping, tf) delete(f.targets, name) } for tf := range f.stopping { stopping = append(stopping, tf) } f.mu.Unlock() for _, tf := range stopping { <-tf.done } } type forwardSettings struct { target *Target dest destination } type targetForwarder struct { f *Forwarder name string topic topic.Topic current atomic.Pointer[forwardSettings] cancel context.CancelFunc done chan struct{} lagMu sync.Mutex lags map[topic.Partition]int64 } func (f *Forwarder) start(t *Target, dest destination) *targetForwarder { ctx, cancel := context.WithCancel(context.Background()) tf := &targetForwarder{ f: f, name: t.Name, topic: topic.NewTopic(TopicNamespace, t.TopicName()), cancel: cancel, done: make(chan struct{}), lags: map[topic.Partition]int64{}, } tf.current.Store(&forwardSettings{target: t, dest: dest}) go tf.run(ctx) return tf } func (tf *targetForwarder) settings() *forwardSettings { return tf.current.Load() } // run forwards the target while this gateway holds its lock. A forwarder whose // offset save was refused stops, and leads again only once it has held the // lock through reclaimWait. func (tf *targetForwarder) run(ctx context.Context) { defer close(tf.done) lock := tf.f.startLock(ForwarderLockPrefix + tf.name) defer func() { if err := lock.Stop(); err != nil { glog.V(1).Infof("notification target %s: release forwarder lock: %v", tf.name, err) } }() var ( stopLead context.CancelFunc ended chan error leadGeneration int64 holdOffUntil time.Time reclaim bool ) endLead := func() { if stopLead == nil { return } stopLead() if ended != nil { <-ended } stopLead, ended = nil, nil tf.clearLag() } defer endLead() ticker := time.NewTicker(tf.f.lockCheckInterval) defer ticker.Stop() for { held := lock.IsLocked() if stopLead != nil && (!held || lock.Generation() != leadGeneration) { glog.V(0).Infof("notification target %s: forwarder lock lost at generation %d", tf.name, leadGeneration) endLead() } if held && stopLead == nil && !time.Now().Before(holdOffUntil) { leadCtx, cancel := context.WithCancel(ctx) stopLead, ended, leadGeneration = cancel, make(chan error, 1), lock.Generation() glog.V(0).Infof("notification target %s: forwarding from this gateway at generation %d", tf.name, leadGeneration) go func(ended chan<- error, generation int64, reclaim bool) { ended <- tf.lead(leadCtx, lock, generation, reclaim) }(ended, leadGeneration, reclaim) reclaim = false } select { case <-ctx.Done(): return case err := <-ended: ended = nil endLead() if errors.Is(err, errDeposed) { glog.Warningf("notification target %s: stopped forwarding: %v", tf.name, err) holdOffUntil, reclaim = time.Now().Add(tf.f.reclaimWait), true } case <-ticker.C: } } } // forwardPartition is a partition of the target's topic and its leader, which // holds the partition's unflushed messages. type forwardPartition struct { partition topic.Partition leader string // retired is set for a sealed range of an earlier generation, read from its // files by any broker; its loop ends once it reaches highWaterMark retired atomic.Bool highWaterMark atomic.Int64 // removed is set once the topic lists the partition neither as assigned nor // as retired, as while a drained range is not sealed yet; its loop ends after // the batch in hand and starts again once the range is offered as retired removed atomic.Bool ended atomic.Bool } // lead forwards every partition until ctx ends or one finds itself deposed. A // reclaim lead may take over partitions whose stored generation is not older // than its own: the lock server's counter restarted or moved to another filer. // // A key's records in a retired range precede its records in the ranges that // replaced it, so retired ranges are forwarded first, one generation at a time, // oldest first, and the current ranges only once none is left. func (tf *targetForwarder) lead(ctx context.Context, lock forwarderLock, generation int64, reclaim bool) error { var current, retired []*forwardPartition b := tf.backoff() for { var err error if current, retired, err = tf.lookUp(ctx); err == nil { break } if b.failed() { glog.Warningf("notification target %s: look up topic %s: %v", tf.name, tf.topic, err) } if !b.wait(ctx) { return nil } } ctx, cancel := context.WithCancel(ctx) defer cancel() settled := map[string]bool{} var unsettled []string // a failed check says nothing about the old ranges, so it holds every range not yet running checked, checks := false, tf.backoff() var recheck <-chan time.Time check := func() { held, err := tf.unsettledRanges(ctx, current, retired, settled) if err != nil { if checks.failed() { glog.Warningf("notification target %s: holding its current partitions, list stored offsets: %v", tf.name, err) } checked, recheck = false, time.After(checks.delay()) return } unsettled, checked, recheck = held, true, nil checks.reset() } check() var heldLogged time.Time results := make(chan error) // keyed by directory: the topic lists a retired range at the resolution of // its generation's directory name, while its assignment carried nanoseconds loops := map[string]*forwardPartition{} dir := func(p *forwardPartition) string { return topic.PartitionDir(tf.topic, p.partition) } running := 0 start := func(p *forwardPartition) { loops[dir(p)] = p running++ go func() { err := tf.forward(ctx, lock, p, generation, reclaim) tf.setLag(p.partition, 0) if err != nil { // stopped before it is marked ended, so no adopt takes a failed range as delivered cancel() } p.ended.Store(true) if tf.f.loopEnded != nil { tf.f.loopEnded(err) } results <- err }() } adopt := func() { for key, p := range loops { // a removed loop is replaced only once it ended, so one range never has two if p.removed.Load() && p.ended.Load() { delete(loops, key) } } listed := map[string]bool{} for _, r := range retired { listed[dir(r)] = true if p := loops[dir(r)]; p != nil { // a range this lead forwarded as current, retired by a repartition since p.highWaterMark.Store(r.highWaterMark.Load()) p.retired.Store(true) } } // the oldest generation with a retired range not yet delivered oldest := int64(math.MaxInt64) for _, r := range retired { if p := loops[dir(r)]; p == nil || !p.ended.Load() { oldest = min(oldest, r.partition.UnixTimeNs) } } for _, p := range loops { if p.retired.Load() && !p.ended.Load() { oldest = min(oldest, p.partition.UnixTimeNs) } } // an unsealed range holds back the retired generations after its own too for _, d := range unsettled { if p, ok := partitionOfDir(d, 0); ok { oldest = min(oldest, p.UnixTimeNs) } } for _, r := range retired { if loops[dir(r)] == nil && checked && r.partition.UnixTimeNs == oldest { glog.V(0).Infof("notification target %s: forwarding retired partition %v up to offset %d", tf.name, r.partition, r.highWaterMark.Load()) start(r) } } if len(unsettled) > 0 && time.Since(heldLogged) >= forwardHoldLogInterval { heldLogged = time.Now() glog.Warningf("notification target %s: holding its new partitions until %v, drained but not sealed yet, are offered as retired", tf.name, unsettled) } for _, c := range current { listed[dir(c)] = true if loops[dir(c)] == nil && oldest == math.MaxInt64 && checked && len(unsettled) == 0 { start(c) } } for key, p := range loops { if listed[key] || p.removed.Load() { continue } if p.ended.Load() { delete(loops, key) continue } if tf.lagOf(p.partition) > 0 { glog.Warningf("notification target %s: topic %s lists partition %v neither as assigned nor as retired; pausing it until it is offered again", tf.name, tf.topic, p.partition) } p.removed.Store(true) } } // ranges held back have no loop to report their lag heldLag := func() { var held []*forwardPartition for _, p := range append(append([]*forwardPartition(nil), current...), retired...) { if loops[dir(p)] == nil { held = append(held, p) } } var live []topic.Partition for _, p := range loops { if !p.ended.Load() { live = append(live, p.partition) } } tf.recordHeldLag(ctx, held, live) } adopt() heldLag() ticker := time.NewTicker(tf.f.partitionRefresh) defer ticker.Stop() var deposed error done := ctx.Done() // held, the lead stays to look again even with no loop running for running > 0 || ((!checked || len(unsettled) > 0) && ctx.Err() == nil) { refreshed := false select { case err := <-results: running-- if err != nil && deposed == nil { deposed = err } case <-ticker.C: if found, gone, err := tf.lookUp(ctx); err == nil { current, retired = found, gone check() } refreshed = true case <-recheck: check() case <-done: // running loops end on their own and report done = nil } if ctx.Err() == nil { adopt() if refreshed { heldLag() } } } return deposed } // forward delivers one partition in offset order, one batch at a time, from // its stored offset, and stores the next offset after each delivered batch. It // returns errDeposed when a save is refused, and nil when ctx ends. func (tf *targetForwarder) forward(ctx context.Context, lock forwarderLock, p *forwardPartition, generation int64, reclaim bool) error { next, fence, stored, err := tf.claim(ctx, p.partition, generation, reclaim) if err != nil || ctx.Err() != nil { return err } b := tf.backoff() var stallWarned time.Time for ctx.Err() == nil && lock.IsLocked() && !p.removed.Load() { if p.retired.Load() && next >= p.highWaterMark.Load() { glog.V(0).Infof("notification target %s: retired partition %v delivered up to offset %d", tf.name, p.partition, next) return nil } resp, err := tf.fetch(ctx, p, next) if err == nil && resp.ErrorCode == broker.BrokerErrorOffsetOutOfRange && resp.LogStartOffset > next { if stored { stats.S3NotificationRetentionGapCounter.WithLabelValues(tf.name).Add(float64(resp.LogStartOffset - next)) glog.Warningf("notification target %s partition %v: retention removed offsets %d to %d before they were delivered", tf.name, p.partition, next, resp.LogStartOffset-1) } next, stored = resp.LogStartOffset, true if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { return err } continue } if err == nil && resp.ErrorCode != 0 { err = fmt.Errorf("broker error %d: %s", resp.ErrorCode, resp.Error) } if err != nil { if b.failed() { glog.Warningf("notification target %s partition %v: fetch at offset %d from %s: %v", tf.name, p.partition, next, p.leader, err) } if !b.wait(ctx) { return nil } tf.refreshLeader(ctx, p) continue } b.reset() if !stored { // read from now, so a later lead counts what retention removes past it if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { return err } stored = true } records, offsets, advance := tf.fetchedBatch(resp, next) tf.setLag(p.partition, resp.HighWaterMark-next) if len(records) == 0 { if advance > next { next = advance if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { return err } continue } if next < resp.HighWaterMark && time.Since(stallWarned) >= forwardStallWarnInterval { // the broker has records past next but returns none; waiting keeps them, skipping would lose them stallWarned = time.Now() glog.Warningf("notification target %s: topic %s partition %v returns no records at offset %d below its high-water mark %d", tf.name, tf.topic, p.partition, next, resp.HighWaterMark) } // caught up; a short fetch at a segment boundary still advances above select { case <-ctx.Done(): case <-time.After(tf.f.idleWait): } continue } if !tf.deliver(ctx, lock, records, offsets) { return nil } next = advance if _, _, err := tf.save(ctx, p.partition, next, fence, true); err != nil { return err } tf.setLag(p.partition, resp.HighWaterMark-next) } return nil } // fetchedBatch decodes the records of resp at or after next, in offset order, // with their offsets, and returns the offset after them. A message the log // could not place has no offset and is skipped; one that does not decode // could never be delivered. func (tf *targetForwarder) fetchedBatch(resp *mq_pb.FetchMessageResponse, next int64) (records []*schema_pb.RecordValue, offsets []int64, advance int64) { advance = max(resp.NextOffset, next) for i, m := range resp.Messages { at := next + int64(i) // brokers that predate DataMessage.Offset leave it unset if m.Offset != nil { at = *m.Offset } if at < next { continue } advance = max(advance, at+1) record := &schema_pb.RecordValue{} if err := proto.Unmarshal(m.Value, record); err != nil { tf.skip(at, "undecodable", err) continue } records = append(records, record) offsets = append(offsets, at) } return records, offsets, advance } // skip counts a record that can never be delivered; it is seen once, as the // offset moves past it. func (tf *targetForwarder) skip(at int64, reason string, err error) { stats.S3NotificationSkippedCounter.WithLabelValues(tf.name, reason).Inc() glog.Warningf("notification target %s: skipping %s record at offset %d: %v", tf.name, reason, at, err) } // claim reads the partition's stored offset and stores it back under this // forwarder's fence, the lock generation, so a forwarder of an older // generation can no longer store. A stored generation at or above ours, from // another forwarder, means this lock was lost unless this lead is a reclaim. func (tf *targetForwarder) claim(ctx context.Context, partition topic.Partition, generation int64, reclaim bool) (next, fence int64, stored bool, err error) { b := tf.backoff() for { loadCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) position, err := tf.f.positions.LoadConsumerGroupPosition(loadCtx, tf.topic, partition, ForwarderGroup) cancel() if err == nil || errors.Is(err, filer_pb.ErrNotFound) { next, fence, stored = 0, generation, err == nil && position.Metadata != claimedPosition if err == nil { next = position.Value if position.Generation > generation || (position.Generation == generation && position.Writer != tf.f.owner) { if !reclaim { return 0, 0, false, fmt.Errorf("partition %v stored at generation %d by %s, ours is %d: %w", partition, position.Generation, position.Writer, generation, errDeposed) } fence = position.Generation + 1 } } next, stored, err = tf.save(ctx, partition, next, fence, stored) if err == nil || ctx.Err() != nil { return next, fence, stored, err } if !reclaim { return 0, 0, false, err } // another reclaim got there first; read its generation and go above it continue } if b.failed() { glog.Warningf("notification target %s partition %v: load offset: %v", tf.name, partition, err) } if !b.wait(ctx) { return 0, 0, false, nil } } } // save stores next under fence, retrying until it is stored, refused, or ctx // ends. A position not established, as a claim's before anything was read // from it, is marked so, and counts no retention gap later. It returns the // offset stored and whether it is established: a save taking over from an // older fence keeps what that fence committed last. func (tf *targetForwarder) save(ctx context.Context, partition topic.Partition, next, fence int64, established bool) (int64, bool, error) { b := tf.backoff() for { saveCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) position := &offset.ConsumerGroupPosition{ Type: "offset", Value: next, OffsetType: schema_pb.OffsetType_EXACT_OFFSET.String(), CommittedAt: time.Now().UnixMilli(), Generation: fence, Writer: tf.f.owner, } if !established { position.Metadata = claimedPosition } err := tf.f.positions.SaveConsumerGroupPosition(saveCtx, tf.topic, partition, ForwarderGroup, position) cancel() if err == nil { return position.Value, position.Metadata != claimedPosition, nil } if errors.Is(err, offset.ErrStaleGeneration) { return next, established, fmt.Errorf("%v: %w", err, errDeposed) } // a takeover whose reply was lost may have stored what it kept; once the entry // is ours a retry keeps nothing, so it retries with that next, established = position.Value, position.Metadata != claimedPosition if b.failed() { glog.Warningf("notification target %s partition %v: store offset %d: %v", tf.name, partition, next, err) } if !b.wait(ctx) { return next, established, nil } } } // deliver sends records, found at offsets, until the destination takes them, // retrying every failed send, a refusal included: a 401 is an operator fix // away from succeeding. A record that cannot be rendered is skipped instead. // It reports false when ctx ends or the lock is lost first. func (tf *targetForwarder) deliver(ctx context.Context, lock forwarderLock, records []*schema_pb.RecordValue, offsets []int64) bool { b := tf.backoff() for len(records) > 0 { // the lock may have gone while the batch was fetched; losing it mid-send cancels ctx if !lock.IsLocked() { return false } err := tf.settings().dest.Send(ctx, records) var unrenderable *unrenderableError if errors.As(err, &unrenderable) { keptRecords, keptOffsets := records[:0:0], offsets[:0:0] for i := range records { if slices.Contains(unrenderable.indexes, i) { tf.skip(offsets[i], "unrenderable", unrenderable.err) continue } keptRecords, keptOffsets = append(keptRecords, records[i]), append(keptOffsets, offsets[i]) } records, offsets = keptRecords, keptOffsets continue } if err == nil { stats.S3NotificationDeliveredCounter.WithLabelValues(tf.name).Add(float64(len(records))) return true } if ctx.Err() != nil { return false } stats.S3NotificationSendRetriesCounter.WithLabelValues(tf.name).Inc() if b.failed() { glog.Warningf("notification target %s: send %d records: %v", tf.name, len(records), err) } if !b.wait(ctx) { return false } } return true } func (tf *targetForwarder) fetch(ctx context.Context, p *forwardPartition, next int64) (resp *mq_pb.FetchMessageResponse, err error) { addresses := []string{p.leader} if p.retired.Load() { // any broker reads a retired range from its files addresses = append(addresses, tf.f.brokers()...) } err = errors.New("partition has no leader") var refused *mq_pb.FetchMessageResponse tried := map[string]bool{} for _, address := range addresses { if address == "" || tried[address] { continue } tried[address] = true fetchCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) err = pb.WithBrokerGrpcClient(false, address, tf.f.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error { resp, err = client.FetchMessage(fetchCtx, &mq_pb.FetchMessageRequest{ Topic: tf.topic.ToPbTopic(), Partition: p.partition.ToPbPartition(), StartOffset: next, MaxMessages: forwardBatchMessages, MaxBytes: forwardBatchBytes, ConsumerGroup: ForwarderGroup, ConsumerId: tf.f.owner, }) return err }) cancel() if err == nil && p.retired.Load() && resp.ErrorCode != 0 && resp.ErrorCode != broker.BrokerErrorOffsetOutOfRange { // another broker may read the files this one cannot refused = resp continue } if err == nil { return resp, nil } } if refused != nil { return refused, nil } return nil, err } // lookUp asks the brokers for the topic's partitions and their leaders, and // for the retired ranges that still hold data. func (tf *targetForwarder) lookUp(ctx context.Context) (current, retired []*forwardPartition, err error) { brokers := tf.f.brokers() if len(brokers) == 0 { return nil, nil, errors.New("no message queue broker found") } var lastErr error for _, address := range brokers { var resp *mq_pb.LookupTopicBrokersResponse lastErr = pb.WithBrokerGrpcClient(false, address, tf.f.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) (err error) { lookupCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) defer cancel() resp, err = client.LookupTopicBrokers(lookupCtx, &mq_pb.LookupTopicBrokersRequest{Topic: tf.topic.ToPbTopic(), IncludeRetired: true}) return err }) if lastErr != nil { lastErr = fmt.Errorf("%s: %w", address, lastErr) continue } current = nil for _, assignment := range resp.BrokerPartitionAssignments { if assignment.Partition != nil { current = append(current, &forwardPartition{ partition: topic.FromPbPartition(assignment.Partition), leader: assignment.LeaderBroker, }) } } if len(current) == 0 { lastErr = fmt.Errorf("%s: topic has no partitions", address) continue } retired = nil for _, r := range resp.RetiredPartitions { if r.Partition != nil { p := &forwardPartition{partition: topic.FromPbPartition(r.Partition)} p.retired.Store(true) p.highWaterMark.Store(r.HighWaterMark) retired = append(retired, p) } } return current, retired, nil } return nil, nil, lastErr } // unsettledRanges lists the partition directories the topic offers neither as // assigned nor as retired that may still hold records past their stored offset, // or past 0 for one with none stored: a range a repartition drained but has not // sealed yet. Its records precede the new ranges' records of the same keys, so // while one is unsettled the new ranges wait. A range that answers a read with // nothing left past that offset, sealed and empty or already delivered, is settled. // A check that fails partway still keeps the ranges it found settled, so the // next one goes on from there. func (tf *targetForwarder) unsettledRanges(ctx context.Context, current, retired []*forwardPartition, settled map[string]bool) ([]string, error) { var ringSize int32 offered := map[string]bool{} for _, p := range append(append([]*forwardPartition(nil), current...), retired...) { offered[topic.PartitionDir(tf.topic, p.partition)] = true ringSize = p.partition.RingSize } listCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) defer cancel() // only the ranges not offered and not yet settled have their positions read stored, listErr := tf.f.positions.ListConsumerGroupPositions(listCtx, tf.topic, ForwarderGroup, func(dir string) bool { return offered[dir] || settled[dir] }) var unsettled []string for dir, position := range stored { partition, ok := partitionOfDir(dir, ringSize) if !ok { continue } var next int64 if position != nil { next = position.Value } probe := &forwardPartition{partition: partition} probe.retired.Store(true) resp, err := tf.fetch(ctx, probe, next) if err == nil && (resp.ErrorCode == 0 || resp.ErrorCode == broker.BrokerErrorOffsetOutOfRange) && resp.HighWaterMark <= max(next, resp.LogStartOffset) { // sealed, so it stays settled settled[dir] = true continue } unsettled = append(unsettled, dir) } if listErr != nil { // the ranges not read yet may be unsettled return nil, listErr } slices.Sort(unsettled) return unsettled, nil } // partitionOfDir is the partition a directory ...// names. func partitionOfDir(dir string, ringSize int32) (topic.Partition, bool) { parts := strings.Split(dir, "/") if len(parts) < 2 { return topic.Partition{}, false } version, err := topic.ParseTopicVersion(parts[len(parts)-2]) start, stop := topic.ParsePartitionBoundary(parts[len(parts)-1]) if err != nil || start == stop { return topic.Partition{}, false } return topic.Partition{RingSize: ringSize, RangeStart: start, RangeStop: stop, UnixTimeNs: version.UnixNano()}, true } // refreshLeader looks the partition's leader up again after a failed fetch. func (tf *targetForwarder) refreshLeader(ctx context.Context, p *forwardPartition) { partitions, _, err := tf.lookUp(ctx) if err != nil { return } for _, found := range partitions { if found.partition.Equals(p.partition) { p.leader = found.leader return } } } // setLag records how far a partition's committed offset trails its high-water // mark; the target's gauge is the sum over its partitions. func (tf *targetForwarder) setLag(partition topic.Partition, lag int64) { tf.lagMu.Lock() defer tf.lagMu.Unlock() tf.lags[partition] = max(lag, 0) tf.reportLagLocked() } func (tf *targetForwarder) reportLagLocked() { var total int64 for _, l := range tf.lags { total += l } stats.S3NotificationLagGauge.WithLabelValues(tf.name).Set(float64(total)) } // recordHeldLag sets the lag of the ranges held back behind an older // generation, from their stored offset to their high-water mark, and drops // that of ranges neither held nor running any more. func (tf *targetForwarder) recordHeldLag(ctx context.Context, held []*forwardPartition, running []topic.Partition) { lags := map[topic.Partition]int64{} keep := map[topic.Partition]bool{} for _, p := range running { keep[p] = true } for _, p := range held { keep[p.partition] = true loadCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) position, err := tf.f.positions.LoadConsumerGroupPosition(loadCtx, tf.topic, p.partition, ForwarderGroup) cancel() var next int64 if err == nil { next = position.Value } else if !errors.Is(err, filer_pb.ErrNotFound) { continue } hwm := p.highWaterMark.Load() if !p.retired.Load() { err = pb.WithBrokerGrpcClient(false, p.leader, tf.f.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error { infoCtx, cancel := context.WithTimeout(ctx, forwardRPCTimeout) defer cancel() resp, err := client.GetPartitionRangeInfo(infoCtx, &mq_pb.GetPartitionRangeInfoRequest{Topic: tf.topic.ToPbTopic(), Partition: p.partition.ToPbPartition()}) if err == nil && resp.Error != "" { err = errors.New(resp.Error) } hwm = resp.GetOffsetRange().GetHighWaterMark() return err }) if err != nil { continue } } lags[p.partition] = max(hwm-next, 0) } tf.lagMu.Lock() defer tf.lagMu.Unlock() for partition := range tf.lags { if !keep[partition] { delete(tf.lags, partition) } } maps.Copy(tf.lags, lags) tf.reportLagLocked() } func (tf *targetForwarder) lagOf(partition topic.Partition) int64 { tf.lagMu.Lock() defer tf.lagMu.Unlock() return tf.lags[partition] } // clearLag drops the gauge when this gateway stops forwarding the target, so // only the forwarding gateway reports it. func (tf *targetForwarder) clearLag() { tf.lagMu.Lock() defer tf.lagMu.Unlock() clear(tf.lags) stats.S3NotificationLagGauge.DeleteLabelValues(tf.name) } func (tf *targetForwarder) backoff() *backoff { return &backoff{min: tf.f.minBackoff, max: tf.f.maxBackoff} } // backoff doubles a wait from min up to max. type backoff struct { min, max, next time.Duration failures int } // failed counts a failure and reports whether it is worth logging: the first, // and each one once the wait is capped. func (b *backoff) failed() bool { b.failures++ return b.failures == 1 || b.next >= b.max } func (b *backoff) reset() { b.next, b.failures = 0, 0 } // delay doubles the wait and returns it. func (b *backoff) delay() time.Duration { b.next = min(max(2*b.next, b.min), b.max) return b.next } // wait sleeps the current wait and doubles it; false means ctx ended first. func (b *backoff) wait(ctx context.Context) bool { select { case <-ctx.Done(): return false case <-time.After(b.delay()): return true } }