Files
seaweedfs/weed/s3api/s3notification/forwarder.go
T
Chris LuandClaude Opus 5.5 284d491587 s3: forward notification topics to webhook targets (#13245)
* util: move the guarded dialer out of the volume server

The deny list and the dialer that re-checks every resolved address at
connect time move into weed/util/netguard, with the allow-private knob as a
policy, so other outbound clients can dial through the same guard.

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

* mq: fence consumer group position saves by generation

A position saved with a generation is written only while the stored one
carries no newer generation, or the same generation from another writer:
the save reads the stored position and writes on the condition that it is
unchanged, routed to the entry's owner filer, and re-reads when another
writer got there first. A single consumer that elects itself can then store
its offsets without a deposed predecessor overwriting them. Saves without a
generation keep overwriting as before.

Loading a missing position now reports ErrNotFound instead of trying every
filer and marking each one failed.

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

* s3: post bucket event batches to a webhook target

A webhook destination renders a batch of records as one
{"Records":[...]} body, posts it with the target's bearer token, and takes
any 2xx as delivered. The renderer is a function the destination holds, a
stand-in that refuses until the record renderer lands. It dials through the
guarded dialer under a new Local policy, which refuses metadata-service,
link-local and unspecified addresses at connect time but lets an operator
point a target at a private host or a sidecar on loopback. Redirects are
followed only to the endpoint's own host and never down from https.

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

* s3: forward each target's topic to its destination

A Forwarder runs beside the Publisher on every gateway. Each enabled target
with a destination gets a lock, s3.notify.<target>, held through
LockClient.StartLongLivedLock, so one gateway forwards a target and targets
spread across gateways; a topic target has none.

The holder runs one loop per partition of the target's topic: fetch from the
stored offset at the partition's leader, decode the records, deliver them as
one batch, store the next offset. A fetch that stops short at a segment
boundary just continues from its next offset. A failed send, a rejected one
included, blocks the partition and is retried with capped backoff, and the
offset is stored only after the destination took the batch. An offset that
retention removed skips to the earliest one and counts the gap.

Offsets go to the consumer group offset storage under group forwarder,
fenced by the lock generation. On taking the lock a forwarder stores each
partition's offset back under its generation, so an older holder's saves are
refused and it stops. A stored generation at or above its own means the
lock was lost, unless the forwarder has since held the lock through a full
renewal, which happens only when the lock server's counter restarted; it
then fences above the stored generation.

Metrics per target: records delivered, send retries, retention gaps, and
lag from the forwarding gateway.

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

* s3api: run notification forwarders beside the publisher

Every gateway with filers starts a Forwarder with the publisher. It elects
itself per target through the gateway's object-write lock client, stores
offsets in the filer, reads through the same brokers the publisher uses,
follows the target registry as the publisher does, and releases its locks
on shutdown.

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

* s3: post a test event to a webhook on its own

The renderer refuses an s3:TestEvent that shares a body with other records,
so a webhook splits a batch around each one and posts them in order, the
test event as its own body. The test is a stand-in until the renderer's
lands.

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

* s3: skip a bucket event record that can never be delivered

A record that does not decode, or that the renderer refuses, used to be
retried like a failed send and would block its partition for good. The
webhook now renders a whole batch before posting any of it and names the
records that cannot render; the forwarder drops those, counts them per
target and reason in notification_skipped_records_total, logs each offset
once, and sends the rest. Only transport and HTTP failures are retried.

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

* mq: read a fenced position save at the filer that applies it

The fenced save read the stored position from whichever filer answered and
then sent its conditional write to the key's owner, so with filers that keep
their own stores the condition could be checked against an entry other than
the one read, failing until replication caught up or judging a stale copy.
The storage now takes the ring's owner lookup, the one route-by-key writes
already use, and sends both the read and the write to that filer. The
gateway hands its object-write lock client's PrimaryForKey to the forwarder
offsets.

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

* s3: follow a repartitioned notification topic

A forwarder listed its topic's partitions once, when it took the lock, so a
repartition left the new partitions unforwarded until the lock moved. It now
lists them again every 30 seconds, starts a loop for each new partition, and
marks the loops of partitions no longer listed as replaced; such a loop keeps
delivering what its partition holds and ends once it has caught up. A
failed fetch now looks up the leader of that exact partition, not of any
partition with the same range.

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

* s3: let the first forwarder take the lock before the second asks

The election test synced both gateways at once, and each forwarder asks for
its lock from its own goroutine, so the second could ask first and store the
offsets the test expected from the first.

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

* s3: warn when a partition returns nothing below its high-water mark

A fetch that returned no records and kept its next offset below the
high-water mark looked like an idle partition, so the forwarder waited
without a word while its lag stayed up. It still waits, since skipping would
lose the records, but now warns at most once a minute with the topic,
partition, offset and high-water mark, so the lag has an explanation.

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

* s3: render webhook bodies with the bucket event renderer

The webhook now renders through Render and posts each s3:TestEvent alone by
IsTestEvent, replacing the stand-ins it held until the renderer landed.
The tests send real records and read the object keys and test request ids
back out of the bodies.

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

* netguard: refuse the IPv6 and Alibaba metadata service addresses

AWS's IPv6 metadata address fd00:ec2::254 is unique-local and Alibaba's
100.100.100.200 sits in the CGNAT range, so the Private and Local
policies let a webhook or remote endpoint reach them. Refuse both under
every policy, like 169.254.169.254.

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

* grafana: chart the notification forwarder metrics

Add an S3 Notifications row with delivered records, lag, send retries,
and records skipped or lost to retention per target.

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

* s3: follow only webhook redirects that keep the POST

On a 301, 302 or 303 Go resends the request as a GET without a body, so an
endpoint that redirected and then answered 2xx counted as delivered while
it received no records. Only 307 and 308, which keep the method and resend
the body, are followed now; any other redirect fails the send and is
retried.

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

* s3: keep webhook endpoint secrets out of errors and logs

The guarded dialer names its endpoint in every refusal, and the forwarder
logs that error, so a webhook endpoint carrying credentials in its userinfo
or a token in its query had them written to the log. The dialer now gets
the endpoint as scheme, host and path only, and the parse and request
errors no longer echo the URL.

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

* mq: load a consumer group position from its owner filer

A forwarder taking over read its start offset from whichever filer answered,
while its fenced saves read and write at the key's owner. With filers that
keep their own stores, a replica still holding an older offset handed the
new holder that offset, which it then stored under its higher generation at
the owner, replaying everything delivered since. Loads now go to the owner
too when the storage knows it.

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

* mq: bound consumer group position loads and saves by the caller

LoadConsumerGroupPosition and SaveConsumerGroupPosition ran their filer
calls under context.Background(), so a filer whose store stalled held a
forwarder's save forever: ending the lead waited on it, the lock was never
released, and Close hung while the lock kept renewing. Both now take the
caller's context; the forwarder gives each call its RPC deadline under the
lead's context, so stopping returns and the lock is released. The offset
wrappers the broker uses keep their signatures.

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

* mq: list a consumer group's positions across partition generations

ListConsumerGroupPositions walks every generation and range directory of a
topic and returns the group's stored position in each, keyed by partition
directory, so a consumer can tell which ranges it holds offsets for that
the topic no longer lists.

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

* s3: stop forwarding ranges a repartition removed

A repartition drops the old assignments, and the broker serves only
assigned ranges, so the loop draining a removed range retried a refused
fetch forever, and after a restart nothing looked at it at all. Reading a
removed range's flushed data would need a read-only path in the broker.
Until then a removed range's loop delivers the batch it holds and ends,
and the forwarder logs an error naming each range it stops and, when it
takes the lock, each partition directory holding a stored offset the topic
no longer lists. The fake broker now refuses unassigned ranges as the real
one does.

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

* s3: deliver what a repartition left in the retired ranges

The lookup now offers the sealed ranges a repartition retired, and any
broker serves them from their files, so the forwarder no longer drops
them. On taking the lock and on each re-list it asks for the retired
ranges too and runs a loop for each, from its stored offset up to its
high-water mark, after which the loop ends; a range it was forwarding as
current and that is now retired gets the same end. A read below a retired
range's log start counts as a retention gap, as for a live one.

A key's records in a retired range precede its records in the ranges that
replaced it, and loops running side by side would not keep that order. So
the retired ranges go first, one generation at a time, oldest first, and
the current ranges start only once none is left. A range listed neither as
assigned nor as retired, as while a drained range is not sealed yet, pauses
until it is offered again.

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

* s3: match a retired range to its forwarding loop by directory

The broker lists a retired range at the second its generation directory
is named for, while the assignment the forwarder started its loop from
carried nanoseconds. After a repartition the retired entry missed the
running loop, so a second loop started on the same stored offset and
delivered the batch the first was still retrying. Key the loops by
partition directory; the fake broker now lists retired ranges and the
fake positions store offsets at that resolution, like the real ones.

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

* s3: replace a paused forwarding loop only once it ended

A range drained but not sealed yet is listed neither as assigned nor as
retired, so its loop is paused and dropped from the lead's loops while
it may still be retrying a batch. Once the range was offered as retired
a new loop started at the stored offset and sent that batch again. Keep
a paused loop until it ends, and start the range again only then.

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

* s3: hold the new ranges while a drained one is not sealed yet

A repartition saves the new ranges before it drains and seals the old ones,
so for a while an old range is offered neither as assigned nor as retired,
and the forwarder started the new ranges at once: a key's new records could
go out before its records still waiting in the old range. On each look at
the topic the forwarder now lists the directories holding a stored offset
that the topic does not offer, and probes each at its offset; one that may
still hold records past it, refused because it is not sealed, holds the new
ranges until it is offered as retired and drained. One that answers with
nothing past the stored offset is settled, sealed and empty or already
delivered, and stays so for the lead. While holding, the forwarder logs at
most once a minute and keeps looking even with no loop running.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: have the fake broker serve only the generation a fetch names

The broker now refuses a fetch naming a generation other than the one it
assigns for the range, unless that generation is sealed and read as
retired. The forwarder tests' fake broker matched an assigned range by its
range alone, so it served the live generation to a fetch for an older,
unsealed one; it now matches the generation too, as the broker does.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold the current ranges until the stored offsets can be listed

A lead whose first look at the stored offsets failed took that as no old
range left unsettled and started the current ranges, delivering a key's
newer records ahead of the ones still in a drained range that is not sealed
yet. A failed look now holds the current ranges as an unsettled range does,
and is retried with backoff and on each partition refresh; the current
ranges start only after a look succeeds. Retired ranges and loops already
running carry on meanwhile.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3api: leave forwarding off on an unusable broker TLS config

The forwarder loaded the grpc.msg_broker client TLS config with
LoadClientTLS, which exits the process on a bad one, and every gateway with
filers builds a forwarder whether or not it has webhook targets. It now
loads it as the publisher does: an unusable config is logged and leaves
forwarding off while the gateway keeps serving.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold the new ranges for an unsealed old range with no stored offset

The check for old ranges still unsealed looked only at ranges holding a
forwarder offset. A forwarder starting for the first time while a drained
range was not sealed yet had stored none in it, so it started the new
ranges and delivered a key's newer records ahead of its older ones. The
consumer group listing now names every partition directory of the topic,
with no position where the group stored none, and such a range is probed
from offset 0. A range with nothing left past that offset, including one
whose records retention already removed, is settled.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: check the load in the fenced save race test

The test read the stored position back ignoring the load's error, so a
failed load panicked on a nil position instead of reporting the error.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: take a partition over at the offset its last holder committed

A new forwarder generation claimed a partition by writing the offset it
had loaded. When the old generation committed again in between, the claim
rewound the stored offset and the new lead replayed what had been
delivered since. A fenced save that takes over from an older generation
now keeps the offset that generation committed last, rereading it on a
conditional write miss, and hands it back in the position, and the
forwarder starts from it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: wait for a position's owner filer instead of asking another

A position store routed by owner fell back to any filer while the owner
of a key was not known yet, as before the lock ring is learned. That
filer's not-found ended the load there, though it may only not have
caught up, and a claim on it would start the partition over. Loads and
fenced saves now fail until the owner is known, and the forwarder
retries them; a store without an owner routing still uses any filer.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: wait for the last checkpoint before a forwarder handoff in tests

The resume, repartition and election tests stopped the first forwarder
once its records were delivered but possibly before their offsets were
stored, so they could pass on a replay rather than on a committed
handoff. They now wait for the final offsets first.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: have Close wait for removed targets to release their locks

A target removed from the registry had its forwarder cancelled and
dropped from the targets, so a Close soon after did not wait for it and
returned with that target's lock possibly still held. Removed forwarders
are now kept until they are done, and Close waits for them as well.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold newer retired generations behind an unsealed older one

A range of an old generation still unsealed held back only the current
ranges. A generation retired after it was offered and delivered right
away, ahead of the older generation's records of the same keys. The
unsealed range's generation now counts as the oldest one left, so only
that generation's own sealed ranges are forwarded until it is sealed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: check the forwarder lock right before each send

A lead checked its lock at the top of each fetch and after a failed send's
backoff, so a lead that lost the lock while it fetched a batch still sent
it, and the next holder sent it again. The lock is now checked right
before each send. Delivery stays at-least-once: a lock lost during a send
cancels that send once the lead notices, which may be after the endpoint
took the batch.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: read a retired range past a broker that answers with an error

Any broker serves a retired range from its files, but a fetch took the
first broker's answer even when it was a storage error, and each retry
asked that broker first again, so one broker that could not read the
files held the range up for good. A retired fetch answered with an error
other than an offset out of range now goes on to the next broker, and
returns the error only when none could read it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count ranges held back behind an older generation in the lag

The lag gauge summed what each running loop reported, so the current
ranges held back while an older generation was still unsealed, and the
retired generations waiting their turn, showed no lag however much piled
up in them. On each partition refresh the lead now reports their lag
from the stored offset to the high-water mark, read from the range's
leader or the retired listing, and drops the lag of ranges it no longer
has.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold retired generations too while stored offsets cannot be listed

A lead whose look at the stored offsets failed held only the current
ranges and went on forwarding retired generations, though an older
generation it could not see might still be unsealed and hold earlier
records of the same keys. A failed look now holds every range not yet
running until a look succeeds; loops already running carry on.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: read stored offsets only of the ranges a lead does not know yet

The check for unsettled ranges listed every partition directory and read
every stored offset in it one by one under one deadline, before dropping
the ranges the topic offers and those already found settled. A topic
with many past generations could take longer than the deadline on every
refresh and hold a new lead for good. The listing now takes the
directories to skip and reads only the remaining offsets, a few at a
time, and the lead skips the offered ranges and those it found settled.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: test the failed-listing hold with no unsealed range

The failed-listing test also had an older generation unsealed, which
holds the newer ranges on its own once a listing succeeds, so it did not
show the listing guard by itself. A second case has no unsealed range:
nothing goes out while the listing fails, and both the retired and the
current range do once it succeeds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: stop the lead before marking a failed loop ended

A forwarding loop that failed, as on being deposed, was marked ended
before it cancelled its lead. A partition refresh in between saw a
retired range's loop ended, took the range as delivered, and started the
next generation's ranges on the lead that was about to stop. The lead is
now cancelled first, so no refresh acts on the failed loop.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count no retention gap below an offset only claimed

A lead claiming a partition with no stored offset wrote offset 0 to fence
it before reading anything. A lead that stopped there left 0 behind, and
the next one, finding the log start past it, counted those offsets as
lost though no forwarder had ever been at them. A claim made before any
read is now marked as such, a takeover keeps the marker of the entry it
replaces, and only an offset a lead read from counts a gap.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: retry a takeover save at the offset it kept

A claim's save that took a partition over from an older generation kept
that generation's last offset, but when its reply was lost the retry
went out with the offset the claim had loaded. The stored entry was by
then the claim's own, so the retry kept nothing and rewound the
partition, replaying what had been delivered since. A failed save now
retries with the offset and marker the attempt settled on.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: store an offset as read from once the first fetch succeeds

A claimed offset lost its claimed marker only when a later save moved it,
so a lead that read an empty partition and stopped left it marked as
never read. Records published and then removed by retention while no
gateway forwarded the target were skipped without a gap counted or
logged. The first successful fetch now stores the offset as read from,
once per claim, even when it has not moved.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: wait for the stalled topic's publisher before reading it in a test

The worker sets the topic publisher up on its own goroutine, which on a
loaded host can start after Publish has stopped waiting.

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

* s3: keep what a timed-out offset check settled for the next one

A check for unsettled ranges that could not read every stored offset
within its deadline returned nothing, so each retry read the same ranges
again and a long enough history kept the new ranges held for good. The
listing now returns the positions it read along with the error and goes
on past one that fails, and the check probes those and keeps the ranges
it finds settled before reporting the failure, so the next check reads
only the rest. The ranges stay held until a check covers them all.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: say which records the notification lag counts

The lag gauge's help, and the dashboard panel with none, read as every
undelivered record, but the records of an old range still being sealed
after a repartition cannot be read and are not counted. Both now say the
gauge covers the current ranges, the ranges held back behind an older
generation, and the sealed retired ranges.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:45:41 -08:00

1022 lines
33 KiB
Go

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 .../<generation>/<range> 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
}
}