mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* 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>
1362 lines
48 KiB
Go
1362 lines
48 KiB
Go
package s3notification
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/testutil"
|
|
"github.com/seaweedfs/seaweedfs/weed/filer_client"
|
|
"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/stats"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
// fakeLog is one partition's messages; offsets below start were removed by retention.
|
|
type fakeLog struct {
|
|
start int64
|
|
values [][]byte
|
|
}
|
|
|
|
// fakeLogKey is a partition by its generation and range start.
|
|
type fakeLogKey struct {
|
|
version int64
|
|
rangeStart int32
|
|
}
|
|
|
|
// atSecond is a generation at the resolution of its directory name, at which
|
|
// the broker lists retired ranges and the filer keys stored positions.
|
|
func atSecond(version int64) int64 {
|
|
return version - version%int64(time.Second)
|
|
}
|
|
|
|
func (b *fakeBroker) appendLocked(key fakeLogKey, value []byte) {
|
|
if b.logs == nil {
|
|
b.logs = map[fakeLogKey]*fakeLog{}
|
|
}
|
|
log := b.logs[key]
|
|
if log == nil {
|
|
log = &fakeLog{}
|
|
b.logs[key] = log
|
|
}
|
|
log.values = append(log.values, value)
|
|
}
|
|
|
|
// appendRecords adds one record per name to the first partition of the current generation.
|
|
func (b *fakeBroker) appendRecords(names ...string) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
for _, name := range names {
|
|
value, err := proto.Marshal(namedRecord(name))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
b.appendLocked(fakeLogKey{b.version, 0}, value)
|
|
}
|
|
}
|
|
|
|
func (b *fakeBroker) purgeBefore(rangeStart int32, start int64) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
b.logs[fakeLogKey{b.version, rangeStart}].start = start
|
|
}
|
|
|
|
// repartition replaces the current generation, which is retired and sealed,
|
|
// after adding last records to its first partition in the same step.
|
|
func (b *fakeBroker) repartition(version int64, count int32, last ...string) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
for _, name := range last {
|
|
value, err := proto.Marshal(namedRecord(name))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
b.appendLocked(fakeLogKey{b.version, 0}, value)
|
|
}
|
|
if b.retired == nil {
|
|
b.retired = map[int64]int32{}
|
|
}
|
|
b.retired[b.version] = int32(TopicPartitionCount)
|
|
if b.partitionCount > 0 {
|
|
b.retired[b.version] = b.partitionCount
|
|
}
|
|
b.version, b.partitionCount = version, count
|
|
}
|
|
|
|
func (b *fakeBroker) setSealed(version int64, sealed bool) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.unsealed == nil {
|
|
b.unsealed = map[int64]bool{}
|
|
}
|
|
b.unsealed[version] = !sealed
|
|
}
|
|
|
|
// appendTo adds one record per name to the partition at key.
|
|
func (b *fakeBroker) appendTo(key fakeLogKey, names ...string) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
for _, name := range names {
|
|
value, err := proto.Marshal(namedRecord(name))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
b.appendLocked(key, value)
|
|
}
|
|
}
|
|
|
|
func (b *fakeBroker) fetchCount(key fakeLogKey) int {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.fetches[key]
|
|
}
|
|
|
|
// GetPartitionRangeInfo answers for the current generation's ranges, as their leader does.
|
|
func (b *fakeBroker) GetPartitionRangeInfo(ctx context.Context, req *mq_pb.GetPartitionRangeInfoRequest) (*mq_pb.GetPartitionRangeInfoResponse, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
for _, p := range b.assignedLocked() {
|
|
if atSecond(p.UnixTimeNs) == atSecond(req.Partition.UnixTimeNs) && p.RangeStart == req.Partition.RangeStart && p.RangeStop == req.Partition.RangeStop {
|
|
log := b.logs[fakeLogKey{p.UnixTimeNs, p.RangeStart}]
|
|
if log == nil {
|
|
log = &fakeLog{}
|
|
}
|
|
return &mq_pb.GetPartitionRangeInfoResponse{OffsetRange: &mq_pb.OffsetRangeInfo{EarliestOffset: log.start, HighWaterMark: int64(len(log.values))}}, nil
|
|
}
|
|
}
|
|
return &mq_pb.GetPartitionRangeInfoResponse{Error: "partition not found"}, nil
|
|
}
|
|
|
|
func (b *fakeBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchMessageRequest) (*mq_pb.FetchMessageResponse, error) {
|
|
b.mu.Lock()
|
|
hook := b.onFetch
|
|
b.mu.Unlock()
|
|
if hook != nil {
|
|
hook()
|
|
}
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if b.failFetches > 0 {
|
|
b.failFetches--
|
|
return nil, status.Error(codes.Unavailable, "broker restarting")
|
|
}
|
|
if b.fetchErrorCode != 0 {
|
|
return &mq_pb.FetchMessageResponse{Error: "storage unavailable", ErrorCode: b.fetchErrorCode, NextOffset: req.StartOffset}, nil
|
|
}
|
|
key := fakeLogKey{req.Partition.UnixTimeNs, req.Partition.RangeStart}
|
|
if b.fetches == nil {
|
|
b.fetches = map[fakeLogKey]int{}
|
|
}
|
|
b.fetches[key]++
|
|
// like the real broker, serve a retired range of an earlier generation from
|
|
// its files, and otherwise only an assigned range of the generation named
|
|
assigned := false
|
|
for version, count := range b.retired {
|
|
if b.unsealed[version] || atSecond(version) != atSecond(req.Partition.UnixTimeNs) || atSecond(req.Partition.UnixTimeNs) == atSecond(b.version) {
|
|
continue
|
|
}
|
|
for _, p := range generationPartitions(version, count) {
|
|
if p.RangeStart == req.Partition.RangeStart && p.RangeStop == req.Partition.RangeStop {
|
|
assigned, key = true, fakeLogKey{version, p.RangeStart}
|
|
}
|
|
}
|
|
}
|
|
for _, p := range b.assignedLocked() {
|
|
sameGeneration := req.Partition.UnixTimeNs == 0 || atSecond(p.UnixTimeNs) == atSecond(req.Partition.UnixTimeNs)
|
|
if !assigned && sameGeneration && p.RangeStart == req.Partition.RangeStart && p.RangeStop == req.Partition.RangeStop {
|
|
assigned, key = true, fakeLogKey{p.UnixTimeNs, p.RangeStart}
|
|
}
|
|
}
|
|
if !assigned {
|
|
return &mq_pb.FetchMessageResponse{Error: "partition not found", ErrorCode: 1, NextOffset: req.StartOffset}, nil
|
|
}
|
|
log := b.logs[key]
|
|
if log == nil {
|
|
log = &fakeLog{}
|
|
}
|
|
hwm := int64(len(log.values))
|
|
if req.StartOffset < log.start {
|
|
return &mq_pb.FetchMessageResponse{
|
|
HighWaterMark: hwm,
|
|
LogStartOffset: log.start,
|
|
NextOffset: req.StartOffset,
|
|
Error: "offset out of range",
|
|
ErrorCode: broker.BrokerErrorOffsetOutOfRange,
|
|
}, nil
|
|
}
|
|
end := min(hwm, req.StartOffset+int64(req.MaxMessages))
|
|
if b.holding && req.StartOffset == b.holdAt {
|
|
end = req.StartOffset
|
|
}
|
|
if b.segment > 0 {
|
|
end = min(end, (req.StartOffset/b.segment+1)*b.segment)
|
|
}
|
|
resp := &mq_pb.FetchMessageResponse{HighWaterMark: hwm, LogStartOffset: log.start, NextOffset: max(end, req.StartOffset)}
|
|
for at := req.StartOffset; at < end; at++ {
|
|
resp.Messages = append(resp.Messages, &mq_pb.DataMessage{Value: log.values[at], Offset: proto.Int64(at)})
|
|
}
|
|
resp.EndOfPartition = resp.NextOffset >= hwm
|
|
return resp, nil
|
|
}
|
|
|
|
// memoryPositions stores positions with the same fencing rule as the filer storage.
|
|
type memoryPositions struct {
|
|
mu sync.Mutex
|
|
positions map[fakeLogKey]offset.ConsumerGroupPosition
|
|
partitions map[fakeLogKey]topic.Partition
|
|
refused int
|
|
listed []string
|
|
// failLists is how many more listings fail
|
|
failLists int
|
|
// afterLoad runs once a load returns, as another writer landing before the next save
|
|
afterLoad func()
|
|
// lostSaves is how many more saves are applied but answered with an error, as a lost reply
|
|
lostSaves int
|
|
// loadLimit, when set, is how many positions a listing reads before it runs out of time
|
|
loadLimit int
|
|
}
|
|
|
|
func newMemoryPositions() *memoryPositions {
|
|
return &memoryPositions{positions: map[fakeLogKey]offset.ConsumerGroupPosition{}, partitions: map[fakeLogKey]topic.Partition{}}
|
|
}
|
|
|
|
func (m *memoryPositions) LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, group string) (*offset.ConsumerGroupPosition, error) {
|
|
m.mu.Lock()
|
|
hook := m.afterLoad
|
|
m.mu.Unlock()
|
|
if hook != nil {
|
|
defer hook()
|
|
}
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
position, ok := m.positions[fakeLogKey{atSecond(p.UnixTimeNs), p.RangeStart}]
|
|
if !ok {
|
|
return nil, filer_pb.ErrNotFound
|
|
}
|
|
return &position, nil
|
|
}
|
|
|
|
func (m *memoryPositions) SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, group string, position *offset.ConsumerGroupPosition) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if group != ForwarderGroup || t.Namespace != TopicNamespace {
|
|
return fmt.Errorf("saved %s under %s", group, t)
|
|
}
|
|
key := fakeLogKey{atSecond(p.UnixTimeNs), p.RangeStart}
|
|
m.partitions[key] = p
|
|
if stored, ok := m.positions[key]; ok && position.Generation != 0 &&
|
|
(stored.Generation > position.Generation || (stored.Generation == position.Generation && stored.Writer != position.Writer)) {
|
|
m.refused++
|
|
return fmt.Errorf("refused: %w", offset.ErrStaleGeneration)
|
|
}
|
|
if stored, ok := m.positions[key]; ok && position.Generation != 0 && stored.Generation < position.Generation {
|
|
// a takeover keeps the offset the older generation committed last
|
|
position.Value, position.Metadata = stored.Value, stored.Metadata
|
|
}
|
|
m.positions[key] = *position
|
|
if m.lostSaves > 0 {
|
|
m.lostSaves--
|
|
return fmt.Errorf("reply lost")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ListConsumerGroupPositions lists every partition directory but those skip
|
|
// reports, with what was saved in it, and remembers the directories loaded.
|
|
func (m *memoryPositions) ListConsumerGroupPositions(ctx context.Context, t topic.Topic, group string, skip func(dir string) bool) (map[string]*offset.ConsumerGroupPosition, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if m.failLists > 0 {
|
|
m.failLists--
|
|
return nil, fmt.Errorf("filer unavailable")
|
|
}
|
|
positions := map[string]*offset.ConsumerGroupPosition{}
|
|
for key, p := range m.partitions {
|
|
if skip != nil && skip(topic.PartitionDir(t, p)) {
|
|
continue
|
|
}
|
|
if m.loadLimit > 0 && len(positions) == m.loadLimit {
|
|
return positions, fmt.Errorf("listing ran out of time: %w", context.DeadlineExceeded)
|
|
}
|
|
positions[topic.PartitionDir(t, p)] = nil
|
|
if position, ok := m.positions[key]; ok {
|
|
positions[topic.PartitionDir(t, p)] = &position
|
|
}
|
|
m.listed = append(m.listed, topic.PartitionDir(t, p))
|
|
}
|
|
return positions, nil
|
|
}
|
|
|
|
// get is the position of the first generation's partition at rangeStart.
|
|
func (m *memoryPositions) get(rangeStart int32) offset.ConsumerGroupPosition {
|
|
return m.getAt(fakeLogKey{0, rangeStart})
|
|
}
|
|
|
|
func (m *memoryPositions) getAt(key fakeLogKey) offset.ConsumerGroupPosition {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return m.positions[fakeLogKey{atSecond(key.version), key.rangeStart}]
|
|
}
|
|
|
|
func (m *memoryPositions) set(rangeStart int32, position offset.ConsumerGroupPosition) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.positions[fakeLogKey{0, rangeStart}] = position
|
|
}
|
|
|
|
// addDirs lists the partition directories of a generation of count partitions,
|
|
// as the topic's directory does once they hold data.
|
|
func (m *memoryPositions) addDirs(version int64, count int32) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
for _, p := range generationPartitions(atSecond(version), count) {
|
|
m.partitions[fakeLogKey{atSecond(version), p.RangeStart}] = topic.FromPbPartition(p)
|
|
}
|
|
}
|
|
|
|
func (m *memoryPositions) refusals() int {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return m.refused
|
|
}
|
|
|
|
// fakeLocks grants each key to one lock at a time, in request order, with a
|
|
// new generation per grant.
|
|
type fakeLocks struct {
|
|
mu sync.Mutex
|
|
generation int64
|
|
holders map[string]*fakeLock
|
|
waiting map[string][]*fakeLock
|
|
// Stop waits for stopGate while it is set, as a release the lock server is slow to answer
|
|
stopGate chan struct{}
|
|
}
|
|
|
|
type fakeLock struct {
|
|
locks *fakeLocks
|
|
key string
|
|
held atomic.Bool
|
|
generation atomic.Int64
|
|
}
|
|
|
|
func newFakeLocks() *fakeLocks {
|
|
return &fakeLocks{holders: map[string]*fakeLock{}, waiting: map[string][]*fakeLock{}}
|
|
}
|
|
|
|
func (s *fakeLocks) start(key string) forwarderLock {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
l := &fakeLock{locks: s, key: key}
|
|
if s.holders[key] == nil {
|
|
s.grantLocked(l)
|
|
} else {
|
|
s.waiting[key] = append(s.waiting[key], l)
|
|
}
|
|
return l
|
|
}
|
|
|
|
func (s *fakeLocks) grantLocked(l *fakeLock) {
|
|
s.generation++
|
|
l.generation.Store(s.generation)
|
|
l.held.Store(true)
|
|
s.holders[l.key] = l
|
|
}
|
|
|
|
func (s *fakeLocks) holder(key string) *fakeLock {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.holders[key]
|
|
}
|
|
|
|
func (l *fakeLock) IsLocked() bool { return l.held.Load() }
|
|
func (l *fakeLock) Generation() int64 { return l.generation.Load() }
|
|
|
|
func (l *fakeLock) Stop() error {
|
|
s := l.locks
|
|
s.mu.Lock()
|
|
gate := s.stopGate
|
|
s.mu.Unlock()
|
|
if gate != nil {
|
|
<-gate
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.holders[l.key] != l {
|
|
waiting := s.waiting[l.key]
|
|
for i, w := range waiting {
|
|
if w == l {
|
|
s.waiting[l.key] = append(waiting[:i], waiting[i+1:]...)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
l.held.Store(false)
|
|
delete(s.holders, l.key)
|
|
if waiting := s.waiting[l.key]; len(waiting) > 0 {
|
|
s.waiting[l.key] = waiting[1:]
|
|
s.grantLocked(waiting[0])
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type forwarderSetup struct {
|
|
broker *fakeBroker
|
|
positions *memoryPositions
|
|
locks *fakeLocks
|
|
hook *webhookServer
|
|
}
|
|
|
|
func newForwarderSetup(t *testing.T) *forwarderSetup {
|
|
return &forwarderSetup{broker: startFakeBroker(t, &fakeBroker{}), positions: newMemoryPositions(), locks: newFakeLocks(), hook: newWebhookServer(t)}
|
|
}
|
|
|
|
func (s *forwarderSetup) forwarder(t *testing.T, owner string) *Forwarder {
|
|
t.Helper()
|
|
f := NewForwarder(func() []string { return []string{s.broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()), s.positions, nil, owner)
|
|
f.startLock = s.locks.start
|
|
f.lockCheckInterval = 10 * time.Millisecond
|
|
f.idleWait = 10 * time.Millisecond
|
|
f.minBackoff = 10 * time.Millisecond
|
|
f.maxBackoff = 50 * time.Millisecond
|
|
f.reclaimWait = time.Hour
|
|
f.partitionRefresh = 20 * time.Millisecond
|
|
t.Cleanup(f.Close)
|
|
return f
|
|
}
|
|
|
|
func (s *forwarderSetup) registry(t *testing.T, name string) *Registry {
|
|
t.Helper()
|
|
reg, err := ParseTargets([]byte(fmt.Sprintf(`{"targets":[{"name":%q,"type":"webhook","enabled":true,"endpoint":%q,"bearer_token":"tok","allowed_buckets":["*"]}]}`, name, s.hook.URL)))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return reg
|
|
}
|
|
|
|
// deliveredNames lists the records the webhook took, in the order it took them.
|
|
func (s *webhookServer) deliveredNames(t *testing.T) []string {
|
|
t.Helper()
|
|
var names []string
|
|
for _, body := range s.delivered() {
|
|
names = append(names, bodyNames(t, body)...)
|
|
}
|
|
return names
|
|
}
|
|
|
|
func sequence(from, to int) []string {
|
|
var names []string
|
|
for i := from; i < to; i++ {
|
|
names = append(names, fmt.Sprint(i))
|
|
}
|
|
return names
|
|
}
|
|
|
|
func waitForRecords(t *testing.T, hook *webhookServer, want []string) {
|
|
t.Helper()
|
|
waitUntil(t, fmt.Sprintf("%d records delivered", len(want)), func() bool { return len(hook.deliveredNames(t)) >= len(want) })
|
|
if got := hook.deliveredNames(t); strings.Join(got, ",") != strings.Join(want, ",") {
|
|
t.Fatalf("delivered %v, want %v", got, want)
|
|
}
|
|
}
|
|
|
|
func TestForwarderDeliversInOffsetOrderAcrossSegmentBoundaries(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.segment = 4
|
|
s.broker.appendRecords(sequence(0, 25)...)
|
|
deliveredBefore := testutil.ToFloat64(stats.S3NotificationDeliveredCounter.WithLabelValues("ordered"))
|
|
f := s.forwarder(t, "gw1")
|
|
f.Sync(s.registry(t, "ordered"))
|
|
|
|
waitForRecords(t, s.hook, sequence(0, 25))
|
|
waitUntil(t, "offset 25 stored", func() bool { return s.positions.get(0).Value == 25 })
|
|
if posts := len(s.hook.delivered()); posts < 7 {
|
|
t.Fatalf("%d posts, want one per fetch that stops at a segment boundary", posts)
|
|
}
|
|
if got := s.positions.get(0); got.Writer != "gw1" || got.Generation == 0 {
|
|
t.Fatalf("stored %+v", got)
|
|
}
|
|
waitUntil(t, "lag 0", func() bool {
|
|
return testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("ordered")) == 0
|
|
})
|
|
if got := testutil.ToFloat64(stats.S3NotificationDeliveredCounter.WithLabelValues("ordered")) - deliveredBefore; got != 25 {
|
|
t.Fatalf("delivered counter rose by %v, want 25", got)
|
|
}
|
|
s.hook.mu.Lock()
|
|
defer s.hook.mu.Unlock()
|
|
for _, auth := range s.hook.auth {
|
|
if auth != "Bearer tok" {
|
|
t.Fatalf("authorization %q", auth)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestForwarderRetriesRejectedSendsAndCommitsOnlyAfterSuccess(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.hook.setStatus(http.StatusInternalServerError)
|
|
s.broker.appendRecords("a", "b")
|
|
f := s.forwarder(t, "gw1")
|
|
f.Sync(s.registry(t, "flaky"))
|
|
|
|
start := testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("flaky"))
|
|
retries := func() float64 {
|
|
return testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("flaky")) - start
|
|
}
|
|
waitUntil(t, "retries after 500", func() bool { return retries() >= 2 })
|
|
s.hook.setStatus(http.StatusUnauthorized)
|
|
before := retries()
|
|
waitUntil(t, "retries after 401", func() bool { return retries() >= before+2 })
|
|
if got := s.positions.get(0).Value; got != 0 {
|
|
t.Fatalf("offset %d stored before the batch was taken", got)
|
|
}
|
|
if lag := testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("flaky")); lag != 2 {
|
|
t.Fatalf("lag %v while blocked, want 2", lag)
|
|
}
|
|
|
|
s.hook.setStatus(http.StatusAccepted)
|
|
waitForRecords(t, s.hook, []string{"a", "b"})
|
|
waitUntil(t, "offset 2 stored", func() bool { return s.positions.get(0).Value == 2 })
|
|
}
|
|
|
|
// A lead claiming a partition starts where the previous lead committed last,
|
|
// though that lead committed again after the claim loaded the offset.
|
|
func TestAClaimStartsAtTheOffsetItReplaces(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
f := s.forwarder(t, "gw2")
|
|
tf := &targetForwarder{f: f, name: "claimed", topic: topic.NewTopic(TopicNamespace, "claimed"), lags: map[topic.Partition]int64{}}
|
|
partition := topic.FromPbPartition(generationPartitions(0, TopicPartitionCount)[0])
|
|
s.positions.mu.Lock()
|
|
s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 10, Generation: 1, Writer: "gw1"}
|
|
s.positions.afterLoad = func() {
|
|
s.positions.mu.Lock()
|
|
defer s.positions.mu.Unlock()
|
|
s.positions.afterLoad = nil
|
|
s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 20, Generation: 1, Writer: "gw1"}
|
|
}
|
|
s.positions.mu.Unlock()
|
|
|
|
next, fence, _, err := tf.claim(context.Background(), partition, 2, false)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if next != 20 || fence != 2 {
|
|
t.Fatalf("claimed at offset %d fence %d, want offset 20 fence 2", next, fence)
|
|
}
|
|
}
|
|
|
|
// A claim whose takeover was applied but whose reply was lost retries at the
|
|
// offset the takeover kept, not the one it loaded: by then the stored entry
|
|
// is its own, so a retry at the loaded offset would rewind the partition.
|
|
func TestAClaimRetriedAfterALostReplyDoesNotRewind(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
f := s.forwarder(t, "gw2")
|
|
tf := &targetForwarder{f: f, name: "lost", topic: topic.NewTopic(TopicNamespace, "lost"), lags: map[topic.Partition]int64{}}
|
|
partition := topic.FromPbPartition(generationPartitions(0, TopicPartitionCount)[0])
|
|
s.positions.mu.Lock()
|
|
s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 10, Generation: 1, Writer: "gw1"}
|
|
s.positions.afterLoad = func() {
|
|
s.positions.mu.Lock()
|
|
defer s.positions.mu.Unlock()
|
|
s.positions.afterLoad = nil
|
|
s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 20, Generation: 1, Writer: "gw1"}
|
|
}
|
|
s.positions.lostSaves = 1
|
|
s.positions.mu.Unlock()
|
|
|
|
next, _, _, err := tf.claim(context.Background(), partition, 2, false)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if stored := s.positions.get(0); next != 20 || stored.Value != 20 {
|
|
t.Fatalf("claimed at offset %d, stored %+v; want both at 20", next, stored)
|
|
}
|
|
}
|
|
|
|
func TestForwarderResumesFromTheStoredOffset(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords(sequence(0, 10)...)
|
|
s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 6})
|
|
f := s.forwarder(t, "gw1")
|
|
f.Sync(s.registry(t, "resume"))
|
|
waitForRecords(t, s.hook, sequence(6, 10))
|
|
|
|
// a restart picks up where the last batch was stored
|
|
waitUntil(t, "offset 10 stored", func() bool { return s.positions.get(0).Value == 10 })
|
|
f.Close()
|
|
s.broker.appendRecords(sequence(10, 13)...)
|
|
s.forwarder(t, "gw1-restarted").Sync(s.registry(t, "resume"))
|
|
waitForRecords(t, s.hook, sequence(6, 13))
|
|
}
|
|
|
|
func TestForwarderSkipsRecordsThatCanNeverBeDelivered(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("a", "unrenderable", "b")
|
|
s.broker.mu.Lock()
|
|
s.broker.appendLocked(fakeLogKey{}, []byte(`{"Records":[]}`)) // not a RecordValue
|
|
s.broker.mu.Unlock()
|
|
s.broker.appendRecords("c")
|
|
skipped := func(reason string) float64 {
|
|
return testutil.ToFloat64(stats.S3NotificationSkippedCounter.WithLabelValues("poison", reason))
|
|
}
|
|
unrenderableBefore, undecodableBefore := skipped("unrenderable"), skipped("undecodable")
|
|
retriesBefore := testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("poison"))
|
|
f := s.forwarder(t, "gw1")
|
|
f.newDestination = func(t *Target) destination {
|
|
hook := newWebhook(t)
|
|
hook.render = renderRefusing
|
|
return hook
|
|
}
|
|
f.Sync(s.registry(t, "poison"))
|
|
|
|
waitForRecords(t, s.hook, []string{"a", "b", "c"})
|
|
waitUntil(t, "offset 5 stored", func() bool { return s.positions.get(0).Value == 5 })
|
|
if got := skipped("unrenderable") - unrenderableBefore; got != 1 {
|
|
t.Fatalf("skipped %v unrenderable records, want 1", got)
|
|
}
|
|
if got := skipped("undecodable") - undecodableBefore; got != 1 {
|
|
t.Fatalf("skipped %v undecodable records, want 1", got)
|
|
}
|
|
if got := testutil.ToFloat64(stats.S3NotificationSendRetriesCounter.WithLabelValues("poison")) - retriesBefore; got != 0 {
|
|
t.Fatalf("%v send retries for a record that cannot render", got)
|
|
}
|
|
}
|
|
|
|
// position of name in delivered, failing when it is not there exactly once.
|
|
func position(t *testing.T, delivered []string, name string) int {
|
|
t.Helper()
|
|
at := -1
|
|
for i, got := range delivered {
|
|
if got == name {
|
|
if at >= 0 {
|
|
t.Fatalf("%s delivered twice in %v", name, delivered)
|
|
}
|
|
at = i
|
|
}
|
|
}
|
|
if at < 0 {
|
|
t.Fatalf("%s not delivered in %v", name, delivered)
|
|
}
|
|
return at
|
|
}
|
|
|
|
// A repartition leaves records undelivered in the retired ranges; they go out
|
|
// first, in order, and the new ranges only after them, so a key's records keep
|
|
// their order across the repartition, after a restart too.
|
|
// A forwarder taking over after a repartition finds the retired ranges it never
|
|
// read and delivers them before the new ones.
|
|
func TestForwarderDeliversRetiredRangesItNeverRead(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("a1", "a2")
|
|
s.broker.repartition(7_000_000_123, 2)
|
|
s.broker.appendRecords("a3")
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "late"))
|
|
waitForRecords(t, s.hook, []string{"a1", "a2", "a3"})
|
|
}
|
|
|
|
func TestForwarderDeliversARepartitionedTopicInOrder(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
// one record per fetch, so a2 is still in the old range when it is retired
|
|
s.broker.segment = 1
|
|
s.hook.setStatus(http.StatusServiceUnavailable)
|
|
s.broker.appendRecords("a1", "a2")
|
|
s.broker.appendTo(fakeLogKey{0, 630}, "x1")
|
|
first := s.forwarder(t, "gw1")
|
|
first.Sync(s.registry(t, "split"))
|
|
waitUntil(t, "a send attempt", func() bool { return s.hook.attempts() > 0 })
|
|
|
|
s.broker.repartition(7_000_000_123, 2)
|
|
s.broker.appendRecords("a3")
|
|
s.broker.appendTo(fakeLogKey{7_000_000_123, 1260}, "y1")
|
|
// several re-lists see the repartition while the endpoint still refuses
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
s.hook.setStatus(http.StatusOK)
|
|
waitUntil(t, "five records delivered", func() bool { return len(s.hook.deliveredNames(t)) >= 5 })
|
|
delivered := s.hook.deliveredNames(t)
|
|
a1, a2, a3 := position(t, delivered, "a1"), position(t, delivered, "a2"), position(t, delivered, "a3")
|
|
x1, y1 := position(t, delivered, "x1"), position(t, delivered, "y1")
|
|
if !(a1 < a2 && a2 < a3 && x1 < a3 && x1 < y1 && a2 < y1) {
|
|
t.Fatalf("delivered %v, want every retired record before the new ranges' and a's in order", delivered)
|
|
}
|
|
waitUntil(t, "the offsets stored", func() bool {
|
|
return s.positions.get(0).Value == 2 && s.positions.get(630).Value == 1 && s.positions.getAt(fakeLogKey{7_000_000_123, 0}).Value == 1 &&
|
|
s.positions.getAt(fakeLogKey{7_000_000_123, 1260}).Value == 1
|
|
})
|
|
|
|
// a restart forwards nothing twice and carries on in the new ranges
|
|
first.Close()
|
|
s.broker.appendRecords("a4")
|
|
s.forwarder(t, "gw2").Sync(s.registry(t, "split"))
|
|
waitUntil(t, "a4 delivered", func() bool { return len(s.hook.deliveredNames(t)) >= 6 })
|
|
time.Sleep(100 * time.Millisecond)
|
|
delivered = s.hook.deliveredNames(t)
|
|
if len(delivered) != 6 || position(t, delivered, "a4") != 5 {
|
|
t.Fatalf("after the restart delivered %v", delivered)
|
|
}
|
|
}
|
|
|
|
// A range retired while its batch is retried keeps its one loop, though the
|
|
// topic lists it at the second its generation's directory is named for.
|
|
func TestForwarderKeepsOneLoopForARangeRetiredMidBatch(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.repartition(5_000_000_123, 2)
|
|
s.broker.segment = 1
|
|
s.hook.setStatus(http.StatusServiceUnavailable)
|
|
s.broker.appendRecords("a1", "a2")
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "midbatch"))
|
|
waitUntil(t, "a send attempt", func() bool { return s.hook.attempts() > 0 })
|
|
|
|
s.broker.repartition(9_000_000_456, 2)
|
|
// several re-lists see the retired range while the endpoint still refuses
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
s.hook.setStatus(http.StatusOK)
|
|
waitForRecords(t, s.hook, []string{"a1", "a2"})
|
|
time.Sleep(200 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1,a2" {
|
|
t.Fatalf("delivered %v, want a1,a2 once each", got)
|
|
}
|
|
}
|
|
|
|
// A range drained but not sealed yet pauses its loop; offered again as
|
|
// retired, it is forwarded once that loop has finished its batch.
|
|
func TestForwarderReplacesAPausedLoopOnlyOnceItEnds(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.repartition(5_000_000_123, 2)
|
|
s.broker.segment = 1
|
|
s.hook.setStatus(http.StatusServiceUnavailable)
|
|
s.broker.appendRecords("a1", "a2")
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "unsealed"))
|
|
waitUntil(t, "a send attempt", func() bool { return s.hook.attempts() > 0 })
|
|
|
|
s.broker.setSealed(5_000_000_123, false)
|
|
s.broker.repartition(9_000_000_456, 2)
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
s.broker.setSealed(5_000_000_123, true)
|
|
// several re-lists offer the retired range while the paused loop still retries
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
s.hook.setStatus(http.StatusOK)
|
|
waitForRecords(t, s.hook, []string{"a1", "a2"})
|
|
time.Sleep(200 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1,a2" {
|
|
t.Fatalf("delivered %v, want a1,a2 once each", got)
|
|
}
|
|
}
|
|
|
|
// While a drained range is not sealed yet, the topic offers it neither as
|
|
// assigned nor as retired; the new ranges wait for it, so no key's new record
|
|
// goes out before its old ones.
|
|
func TestForwarderHoldsTheNewRangesWhileAnOldOneIsUnsealed(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.repartition(5_000_000_123, 2)
|
|
s.broker.appendRecords("a1")
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "held"))
|
|
waitForRecords(t, s.hook, []string{"a1"})
|
|
|
|
// a2 lands just before the repartition, whose drain has not sealed the old range
|
|
s.broker.setSealed(5_000_000_123, false)
|
|
s.broker.repartition(9_000_000_456, 4, "a2")
|
|
s.broker.appendRecords("a3")
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1" {
|
|
t.Fatalf("delivered %v while the old range was unsealed, want only a1", got)
|
|
}
|
|
|
|
s.broker.setSealed(5_000_000_123, true)
|
|
waitForRecords(t, s.hook, []string{"a1", "a2", "a3"})
|
|
}
|
|
|
|
// A forwarder starting for the first time while a drained range is still
|
|
// unsealed has no offset stored in it, and still holds the new ranges until
|
|
// that range is offered as retired and delivered.
|
|
func TestAFreshForwarderHoldsTheNewRangesWhileAnOldOneIsUnsealed(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.repartition(5_000_000_123, 2)
|
|
s.broker.appendRecords("a1")
|
|
s.broker.setSealed(5_000_000_123, false)
|
|
s.broker.repartition(9_000_000_456, 4, "a2")
|
|
s.broker.appendRecords("a3")
|
|
s.positions.addDirs(5_000_000_123, 2)
|
|
s.positions.addDirs(9_000_000_456, 4)
|
|
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "fresh"))
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); len(got) != 0 {
|
|
t.Fatalf("delivered %v with the old range unsealed, want nothing yet", got)
|
|
}
|
|
// the held new range's record counts toward the lag; the unsealed range's cannot be read yet
|
|
waitUntil(t, "the held range's lag", func() bool {
|
|
return testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("fresh")) == 1
|
|
})
|
|
|
|
s.broker.setSealed(5_000_000_123, true)
|
|
waitForRecords(t, s.hook, []string{"a1", "a2", "a3"})
|
|
}
|
|
|
|
// A generation still unsealed holds back the retired generations after it, not
|
|
// only the current one, so each key's records keep their order across both.
|
|
func TestAnUnsealedGenerationHoldsTheRetiredOnesAfterIt(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.repartition(5_000_000_123, 2)
|
|
s.broker.appendRecords("g1")
|
|
s.broker.setSealed(5_000_000_123, false)
|
|
s.broker.repartition(7_000_000_123, 2)
|
|
s.broker.appendRecords("g2")
|
|
s.broker.repartition(9_000_000_456, 4)
|
|
s.broker.appendRecords("g3")
|
|
s.positions.addDirs(5_000_000_123, 2)
|
|
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "barrier"))
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); len(got) != 0 {
|
|
t.Fatalf("delivered %v with the oldest generation unsealed, want nothing yet", got)
|
|
}
|
|
|
|
s.broker.setSealed(5_000_000_123, true)
|
|
waitForRecords(t, s.hook, []string{"g1", "g2", "g3"})
|
|
}
|
|
|
|
// A lead reads the stored offset of a historical range once, until it finds it
|
|
// settled, and never that of a range the topic offers, however often it looks.
|
|
func TestALeadLoadsOnlyTheRangesItDoesNotKnow(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
var historical []int64
|
|
for i := int64(1); i <= 10; i++ {
|
|
version := i * 1_000_000_000
|
|
s.broker.repartition(version, 2)
|
|
s.positions.addDirs(version, 2)
|
|
historical = append(historical, version)
|
|
}
|
|
s.broker.repartition(20_000_000_123, 4)
|
|
s.positions.addDirs(20_000_000_123, 4)
|
|
s.broker.appendRecords("a")
|
|
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "known"))
|
|
waitForRecords(t, s.hook, []string{"a"})
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
|
|
s.positions.mu.Lock()
|
|
defer s.positions.mu.Unlock()
|
|
loads := map[string]int{}
|
|
for _, dir := range s.positions.listed {
|
|
loads[dir]++
|
|
}
|
|
current := topic.NewTopic(TopicNamespace, topicPrefix+"known")
|
|
for _, p := range generationPartitions(20_000_000_123, 4) {
|
|
if n := loads[topic.PartitionDir(current, topic.FromPbPartition(p))]; n != 0 {
|
|
t.Errorf("current range %v loaded %d times", p, n)
|
|
}
|
|
}
|
|
for _, version := range historical {
|
|
for _, p := range generationPartitions(version, 2) {
|
|
if n := loads[topic.PartitionDir(current, topic.FromPbPartition(p))]; n != 1 {
|
|
t.Errorf("settled range %v loaded %d times, want once", p, n)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// A retired range's loop that fails, as on being deposed, has not delivered its
|
|
// range, so the lead ends without starting the generation after it.
|
|
func TestAFailedRetiredLoopDoesNotLetTheNextGenerationStart(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("a1")
|
|
s.broker.repartition(7_000_000_123, 2)
|
|
s.broker.appendRecords("c1")
|
|
// a newer holder has taken the retired range over
|
|
s.positions.mu.Lock()
|
|
s.positions.positions[fakeLogKey{0, 0}] = offset.ConsumerGroupPosition{Type: "offset", Value: 0, Generation: 1 << 40, Writer: "gw2"}
|
|
s.positions.mu.Unlock()
|
|
f := s.forwarder(t, "gw1")
|
|
var once sync.Once
|
|
f.loopEnded = func(err error) {
|
|
if err != nil {
|
|
// widen the moment between the loop ending and the lead stopping
|
|
once.Do(func() { time.Sleep(10 * 20 * time.Millisecond) })
|
|
}
|
|
}
|
|
f.Sync(s.registry(t, "deposed"))
|
|
|
|
time.Sleep(20 * 20 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); slices.Contains(got, "c1") {
|
|
t.Fatalf("delivered %v: the next generation started after the retired range's loop failed", got)
|
|
}
|
|
}
|
|
|
|
// With no older generation unsealed, a failing listing alone holds both the
|
|
// retired and the current ranges, and they go out once a listing succeeds.
|
|
func TestAFailedListingAloneHoldsEveryRange(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("r1")
|
|
s.broker.repartition(7_000_000_123, 2)
|
|
s.broker.appendRecords("c1")
|
|
s.positions.mu.Lock()
|
|
s.positions.failLists = 1 << 20
|
|
s.positions.mu.Unlock()
|
|
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "unlisted-only"))
|
|
waitUntil(t, "several failed listings", func() bool {
|
|
s.positions.mu.Lock()
|
|
defer s.positions.mu.Unlock()
|
|
return s.positions.failLists <= 1<<20-3
|
|
})
|
|
if got := s.hook.deliveredNames(t); len(got) != 0 {
|
|
t.Fatalf("delivered %v while the stored offsets could not be listed, want nothing yet", got)
|
|
}
|
|
|
|
s.positions.mu.Lock()
|
|
s.positions.failLists = 0
|
|
s.positions.mu.Unlock()
|
|
waitForRecords(t, s.hook, []string{"r1", "c1"})
|
|
}
|
|
|
|
// A history too long to check within one listing's time is checked over several:
|
|
// each keeps the ranges it found settled, the next reads only the rest, and the
|
|
// current ranges start once all are checked.
|
|
func TestALongHistoryIsCheckedAcrossListings(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
var historical []int64
|
|
for i := int64(1); i <= 10; i++ {
|
|
version := i * 1_000_000_000
|
|
s.broker.repartition(version, 2)
|
|
s.positions.addDirs(version, 2)
|
|
historical = append(historical, version)
|
|
}
|
|
s.broker.repartition(20_000_000_123, 4)
|
|
s.broker.appendRecords("a")
|
|
s.positions.mu.Lock()
|
|
s.positions.loadLimit = 6
|
|
s.positions.mu.Unlock()
|
|
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "long"))
|
|
waitForRecords(t, s.hook, []string{"a"})
|
|
|
|
s.positions.mu.Lock()
|
|
defer s.positions.mu.Unlock()
|
|
loads := map[string]int{}
|
|
for _, dir := range s.positions.listed {
|
|
loads[dir]++
|
|
}
|
|
long := topic.NewTopic(TopicNamespace, topicPrefix+"long")
|
|
for _, version := range historical {
|
|
for _, p := range generationPartitions(version, 2) {
|
|
if n := loads[topic.PartitionDir(long, topic.FromPbPartition(p))]; n != 1 {
|
|
t.Errorf("range %v read %d times, want once", p, n)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// While the stored offsets cannot be listed, an older generation may still be
|
|
// unsealed, so retired generations are held as well as the current ones.
|
|
func TestAFailedListingHoldsTheRetiredGenerations(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.repartition(5_000_000_123, 2)
|
|
s.broker.appendRecords("g1")
|
|
s.broker.setSealed(5_000_000_123, false)
|
|
s.broker.repartition(7_000_000_123, 2)
|
|
s.broker.appendRecords("g2")
|
|
s.broker.repartition(9_000_000_456, 4)
|
|
s.broker.appendRecords("g3")
|
|
s.positions.addDirs(5_000_000_123, 2)
|
|
s.positions.mu.Lock()
|
|
s.positions.failLists = 1 << 20
|
|
s.positions.mu.Unlock()
|
|
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "unlisted-retired"))
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); len(got) != 0 {
|
|
t.Fatalf("delivered %v while the stored offsets could not be listed, want nothing yet", got)
|
|
}
|
|
|
|
s.positions.mu.Lock()
|
|
s.positions.failLists = 0
|
|
s.positions.mu.Unlock()
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); len(got) != 0 {
|
|
t.Fatalf("delivered %v with the oldest generation unsealed, want nothing yet", got)
|
|
}
|
|
|
|
s.broker.setSealed(5_000_000_123, true)
|
|
waitForRecords(t, s.hook, []string{"g1", "g2", "g3"})
|
|
}
|
|
|
|
// A lead that cannot list the stored offsets does not know whether an old range
|
|
// is still unsealed, so it holds the new ranges until a listing succeeds.
|
|
func TestForwarderHoldsTheNewRangesUntilItCanListStoredOffsets(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.repartition(5_000_000_123, 2)
|
|
s.broker.appendRecords("a1")
|
|
reg := s.registry(t, "unlisted")
|
|
first := s.forwarder(t, "gw1")
|
|
first.Sync(reg)
|
|
waitForRecords(t, s.hook, []string{"a1"})
|
|
first.Close()
|
|
|
|
s.broker.setSealed(5_000_000_123, false)
|
|
s.broker.repartition(9_000_000_456, 4, "a2")
|
|
s.broker.appendRecords("a3")
|
|
s.positions.mu.Lock()
|
|
s.positions.failLists = 3
|
|
s.positions.mu.Unlock()
|
|
s.forwarder(t, "gw2").Sync(reg)
|
|
waitUntil(t, "the listings to fail", func() bool {
|
|
s.positions.mu.Lock()
|
|
defer s.positions.mu.Unlock()
|
|
return s.positions.failLists == 0
|
|
})
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a1" {
|
|
t.Fatalf("delivered %v with the old range unsealed, want only a1", got)
|
|
}
|
|
|
|
s.broker.setSealed(5_000_000_123, true)
|
|
waitForRecords(t, s.hook, []string{"a1", "a2", "a3"})
|
|
}
|
|
|
|
func TestForwarderWaitsAtAnOffsetTheBrokerReturnsNothingFor(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.segment = 1
|
|
s.broker.holding, s.broker.holdAt = true, 1
|
|
s.broker.appendRecords("a", "b", "c")
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "held"))
|
|
|
|
waitForRecords(t, s.hook, []string{"a"})
|
|
waitUntil(t, "fetches at the held offset", func() bool { return s.broker.fetchCount(fakeLogKey{}) > 5 })
|
|
if got := s.positions.get(0).Value; got != 1 {
|
|
t.Fatalf("offset %d stored past records never delivered", got)
|
|
}
|
|
if lag := testutil.ToFloat64(stats.S3NotificationLagGauge.WithLabelValues("held")); lag != 2 {
|
|
t.Fatalf("lag %v, want 2", lag)
|
|
}
|
|
|
|
s.broker.mu.Lock()
|
|
s.broker.holding = false
|
|
s.broker.mu.Unlock()
|
|
waitForRecords(t, s.hook, []string{"a", "b", "c"})
|
|
}
|
|
|
|
func TestForwarderRetriesFailedFetches(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("a")
|
|
s.broker.failFetches = 8
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "fetchfail"))
|
|
waitForRecords(t, s.hook, []string{"a"})
|
|
}
|
|
|
|
func TestForwarderSkipsWhatRetentionRemoved(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords(sequence(0, 10)...)
|
|
s.broker.purgeBefore(0, 5)
|
|
s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 2})
|
|
gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("aged"))
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "aged"))
|
|
|
|
waitForRecords(t, s.hook, sequence(5, 10))
|
|
if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("aged")) - gapBefore; gap != 3 {
|
|
t.Fatalf("gap %v, want 3", gap)
|
|
}
|
|
}
|
|
|
|
// A lead that claimed a partition and stopped before it read anything left an
|
|
// offset no records were delivered from, so the next lead counts no gap below
|
|
// the log start.
|
|
func TestAClaimNeverStartedCountsNoGap(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords(sequence(0, 10)...)
|
|
s.broker.purgeBefore(0, 5)
|
|
s.locks.mu.Lock()
|
|
s.locks.generation = 5
|
|
s.locks.mu.Unlock()
|
|
s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 0, Generation: 5, Writer: "gw0", Metadata: claimedPosition})
|
|
gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("unstarted"))
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "unstarted"))
|
|
|
|
waitForRecords(t, s.hook, sequence(5, 10))
|
|
if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("unstarted")) - gapBefore; gap != 0 {
|
|
t.Fatalf("gap %v below an offset only claimed, want 0", gap)
|
|
}
|
|
}
|
|
|
|
// A lead that read an empty partition has established its offset, though it
|
|
// did not move, so records retention removes while no gateway forwards count
|
|
// as a gap for the next lead.
|
|
func TestAnOffsetReadButNotMovedCountsTheGapAfterIt(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
reg := s.registry(t, "idle")
|
|
first := s.forwarder(t, "gw1")
|
|
first.Sync(reg)
|
|
waitUntil(t, "a few empty fetches", func() bool { return s.broker.fetchCount(fakeLogKey{}) > 2 })
|
|
first.Close()
|
|
|
|
s.broker.appendRecords(sequence(0, 5)...)
|
|
s.broker.purgeBefore(0, 3)
|
|
gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("idle"))
|
|
s.forwarder(t, "gw2").Sync(reg)
|
|
waitForRecords(t, s.hook, sequence(3, 5))
|
|
if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("idle")) - gapBefore; gap != 3 {
|
|
t.Fatalf("gap %v, want the 3 records retention removed while no gateway forwarded", gap)
|
|
}
|
|
}
|
|
|
|
func TestForwarderStartsAtTheEarliestOffsetWithoutCountingAGap(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords(sequence(0, 4)...)
|
|
s.broker.purgeBefore(0, 1)
|
|
gapBefore := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("fresh"))
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "fresh"))
|
|
|
|
waitForRecords(t, s.hook, sequence(1, 4))
|
|
if gap := testutil.ToFloat64(stats.S3NotificationRetentionGapCounter.WithLabelValues("fresh")) - gapBefore; gap != 0 {
|
|
t.Fatalf("gap %v for a forwarder that never stored an offset", gap)
|
|
}
|
|
}
|
|
|
|
func TestDeposedForwarderStopsDelivering(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("a")
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "deposed"))
|
|
waitForRecords(t, s.hook, []string{"a"})
|
|
waitUntil(t, "offset 1 stored", func() bool { return s.positions.get(0).Value == 1 })
|
|
|
|
// a newer forwarder claims the partition while this one still thinks it holds the lock
|
|
mine := s.positions.get(0)
|
|
s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 1, Generation: mine.Generation + 1, Writer: "gw2"})
|
|
s.broker.appendRecords("b", "c")
|
|
waitUntil(t, "the save refused", func() bool { return s.positions.refusals() > 0 })
|
|
// b and c went out once before the refused save; nothing goes out after it
|
|
s.broker.appendRecords("d")
|
|
time.Sleep(200 * time.Millisecond)
|
|
if got := s.hook.deliveredNames(t); strings.Join(got, ",") != "a,b,c" {
|
|
t.Fatalf("deposed forwarder delivered %v, want a,b,c", got)
|
|
}
|
|
if stored := s.positions.get(0); stored.Writer != "gw2" || stored.Value != 1 {
|
|
t.Fatalf("deposed forwarder overwrote the position: %+v", stored)
|
|
}
|
|
}
|
|
|
|
func TestForwarderReclaimsAfterTheLockGenerationRestarts(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords(sequence(0, 3)...)
|
|
// stored before the lock server restarted and its generations began again
|
|
s.positions.set(0, offset.ConsumerGroupPosition{Type: "offset", Value: 1, Generation: 50, Writer: "gw-old"})
|
|
f := s.forwarder(t, "gw1")
|
|
f.reclaimWait = 50 * time.Millisecond
|
|
f.Sync(s.registry(t, "restarted"))
|
|
|
|
waitForRecords(t, s.hook, sequence(1, 3))
|
|
waitUntil(t, "offset 3 stored", func() bool { return s.positions.get(0).Value == 3 })
|
|
if got := s.positions.get(0); got.Generation != 51 || got.Writer != "gw1" {
|
|
t.Fatalf("stored %+v, want generation 51 by gw1", got)
|
|
}
|
|
}
|
|
|
|
// stalledFiler answers no offset read until the caller gives up.
|
|
type stalledFiler struct {
|
|
filer_pb.UnimplementedSeaweedFilerServer
|
|
stalled atomic.Int32
|
|
}
|
|
|
|
func (f *stalledFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
|
f.stalled.Add(1)
|
|
<-ctx.Done()
|
|
return nil, ctx.Err()
|
|
}
|
|
|
|
// ListEntries lists no stored offsets, so the lead goes on to read one.
|
|
func (f *stalledFiler) ListEntries(*filer_pb.ListEntriesRequest, grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
|
|
return nil
|
|
}
|
|
|
|
func TestForwarderCloseIsNotHeldByAStalledFiler(t *testing.T) {
|
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
filer := &stalledFiler{}
|
|
server := grpc.NewServer()
|
|
filer_pb.RegisterSeaweedFilerServer(server, filer)
|
|
go server.Serve(listener)
|
|
t.Cleanup(server.Stop)
|
|
address := pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port)
|
|
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
|
|
|
|
s := newForwarderSetup(t)
|
|
f := s.forwarder(t, "gw1")
|
|
f.positions = offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filer_client.NewFilerClientAccessor([]pb.ServerAddress{address}, dialOption))
|
|
f.Sync(s.registry(t, "stalled"))
|
|
waitUntil(t, "an offset read to stall", func() bool { return filer.stalled.Load() > 0 })
|
|
|
|
closed := make(chan struct{})
|
|
go func() {
|
|
f.Close()
|
|
close(closed)
|
|
}()
|
|
select {
|
|
case <-closed:
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("Close waited on a stalled filer")
|
|
}
|
|
if holder := s.locks.holder(ForwarderLockPrefix + "stalled"); holder != nil {
|
|
t.Fatal("the forwarder lock was not released")
|
|
}
|
|
}
|
|
|
|
// A retired range is read from any broker, so one that answers with a storage
|
|
// error is passed over for the next.
|
|
func TestARetiredRangeIsReadPastABrokerThatCannotReadIt(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("a1")
|
|
s.broker.repartition(7_000_000_123, 2)
|
|
s.broker.appendRecords("a2")
|
|
failing := startFakeBroker(t, &fakeBroker{failLookups: true, fetchErrorCode: broker.BrokerErrorStorageError})
|
|
f := s.forwarder(t, "gw1")
|
|
f.brokers = func() []string { return []string{failing.addr, s.broker.addr} }
|
|
f.Sync(s.registry(t, "unreadable"))
|
|
waitForRecords(t, s.hook, []string{"a1", "a2"})
|
|
}
|
|
|
|
// A lead that loses its lock while it fetches a batch does not send it: the
|
|
// next holder starts from the stored offset and sends that batch itself.
|
|
func TestALeadThatLostItsLockDoesNotSend(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
s.broker.appendRecords("a", "b")
|
|
var once sync.Once
|
|
s.broker.mu.Lock()
|
|
s.broker.onFetch = func() {
|
|
once.Do(func() { s.locks.holder(ForwarderLockPrefix + "lost").held.Store(false) })
|
|
}
|
|
s.broker.mu.Unlock()
|
|
s.forwarder(t, "gw1").Sync(s.registry(t, "lost"))
|
|
waitUntil(t, "a fetch", func() bool { return s.broker.fetchCount(fakeLogKey{}) > 0 })
|
|
time.Sleep(10 * 20 * time.Millisecond)
|
|
if n := s.hook.attempts(); n != 0 {
|
|
t.Fatalf("%d sends after the lock was lost", n)
|
|
}
|
|
}
|
|
|
|
// A target removed from the registry is still releasing its lock when the
|
|
// gateway closes, and Close waits for that release too.
|
|
func TestCloseWaitsForARemovedTargetToReleaseItsLock(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
f := s.forwarder(t, "gw1")
|
|
f.Sync(s.registry(t, "removed"))
|
|
waitUntil(t, "the lock taken", func() bool { return s.locks.holder(ForwarderLockPrefix+"removed") != nil })
|
|
|
|
gate := make(chan struct{})
|
|
s.locks.mu.Lock()
|
|
s.locks.stopGate = gate
|
|
s.locks.mu.Unlock()
|
|
empty, err := ParseTargets([]byte(`{"targets":[]}`))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f.Sync(empty)
|
|
closed := make(chan struct{})
|
|
go func() {
|
|
f.Close()
|
|
close(closed)
|
|
}()
|
|
select {
|
|
case <-closed:
|
|
close(gate)
|
|
t.Fatal("Close returned while a removed target still held its lock")
|
|
case <-time.After(200 * time.Millisecond):
|
|
}
|
|
close(gate)
|
|
select {
|
|
case <-closed:
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("Close never returned")
|
|
}
|
|
if holder := s.locks.holder(ForwarderLockPrefix + "removed"); holder != nil {
|
|
t.Fatal("the removed target's lock is still held")
|
|
}
|
|
}
|
|
|
|
func TestOneForwarderPerTarget(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
reg := s.registry(t, "elected")
|
|
first, second := s.forwarder(t, "gw1"), s.forwarder(t, "gw2")
|
|
first.Sync(reg)
|
|
waitUntil(t, "gw1 to take the lock", func() bool { return s.locks.holder(ForwarderLockPrefix+"elected") != nil })
|
|
second.Sync(reg)
|
|
s.broker.appendRecords(sequence(0, 20)...)
|
|
waitForRecords(t, s.hook, sequence(0, 20))
|
|
waitUntil(t, "offset 20 stored", func() bool { return s.positions.get(0).Value == 20 })
|
|
if writer := s.positions.get(0).Writer; writer != "gw1" {
|
|
t.Fatalf("offsets stored by %s, want the lock holder gw1", writer)
|
|
}
|
|
|
|
// the holder's gateway stops; the other takes over from the stored offset
|
|
first.Close()
|
|
waitUntil(t, "gw2 to hold the lock", func() bool {
|
|
h := s.locks.holder(ForwarderLockPrefix + "elected")
|
|
return h != nil && h.IsLocked()
|
|
})
|
|
s.broker.appendRecords(sequence(20, 30)...)
|
|
waitForRecords(t, s.hook, sequence(0, 30))
|
|
waitUntil(t, "gw2 to store", func() bool { return s.positions.get(0).Writer == "gw2" })
|
|
}
|
|
|
|
func TestForwarderFollowsTheRegistry(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
f := s.forwarder(t, "gw1")
|
|
f.Sync(s.registry(t, "moving"))
|
|
s.broker.appendRecords("a")
|
|
waitForRecords(t, s.hook, []string{"a"})
|
|
|
|
// a new endpoint takes the next batch without giving up the lock
|
|
moved := newWebhookServer(t)
|
|
reg, err := ParseTargets([]byte(fmt.Sprintf(`{"targets":[{"name":"moving","type":"webhook","enabled":true,"endpoint":%q,"allowed_buckets":["*"]}]}`, moved.URL)))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f.Sync(reg)
|
|
s.broker.appendRecords("b")
|
|
waitForRecords(t, moved, []string{"b"})
|
|
|
|
// a topic target and a removed one have no forwarder, and the lock is released
|
|
reg, err = ParseTargets([]byte(`{"targets":[{"name":"moving","type":"topic","enabled":true,"allowed_buckets":["*"]}]}`))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f.Sync(reg)
|
|
waitUntil(t, "the lock released", func() bool { return s.locks.holder(ForwarderLockPrefix+"moving") == nil })
|
|
f.mu.Lock()
|
|
running := len(f.targets)
|
|
f.mu.Unlock()
|
|
if running != 0 {
|
|
t.Fatalf("%d forwarders running for a topic target", running)
|
|
}
|
|
}
|
|
|
|
func TestPublishedEventsReachTheWebhook(t *testing.T) {
|
|
s := newForwarderSetup(t)
|
|
reg := s.registry(t, "e2e")
|
|
p := NewPublisher(func() []string { return []string{s.broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
|
t.Cleanup(p.Close)
|
|
p.Sync(reg)
|
|
s.forwarder(t, "gw1").Sync(reg)
|
|
|
|
var messages []Message
|
|
for _, key := range []string{"a", "b", "c"} {
|
|
messages = append(messages, Message{Target: "e2e", Key: MessageKey("photos", "same"), Value: namedRecord(key)})
|
|
}
|
|
// a record not acked within the wait stays queued, so this publishes each once
|
|
p.Publish(context.Background(), messages)
|
|
waitForRecords(t, s.hook, []string{"a", "b", "c"})
|
|
}
|