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>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-12-01 21:45:41 -08:00
1 parent 960230f86d
commit 284d491587
17 files changed
+4347 -215

No files matched your search

+406
View File
@@ -15239,6 +15239,412 @@
"pluginVersion": "10.3.1"
}
]
},
{
"type": "row",
"title": "S3 Notifications",
"collapsed": true,
"id": 275,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 30
},
"panels": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification records delivered",
"type": "timeseries",
"id": 276,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 31
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_delivered_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification lag",
"description": "Undelivered bucket event records the forwarder can see: current ranges, ranges held back behind an older generation, and sealed retired ranges. An old range still being sealed after a repartition cannot be read yet and is not counted.",
"type": "timeseries",
"id": 277,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 31
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (SeaweedFS_s3_notification_lag_records{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification send retries",
"type": "timeseries",
"id": 278,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 39
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (rate(SeaweedFS_s3_notification_send_retries_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Notification records skipped or lost",
"type": "timeseries",
"id": 279,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 39
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target, reason) (increase(SeaweedFS_s3_notification_skipped_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{target}} skipped {{reason}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (target) (increase(SeaweedFS_s3_notification_retention_gap_records_total{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "B",
"legendFormat": "{{target}} retention gap"
}
],
"pluginVersion": "10.3.1"
}
]
}
],
"refresh": "30s",
+436
View File
@@ -0,0 +1,436 @@
package offset
import (
"context"
"errors"
"net"
"slices"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"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/s3api/s3_constants"
"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"
)
// conditionalFiler keeps entries in memory and evaluates the two write
// conditions a fenced save uses.
type conditionalFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
mu sync.Mutex
entries map[string]*filer_pb.Entry
// beforeWrite runs once, ahead of the next transaction, to model a
// concurrent writer landing between a save's read and its write.
beforeWrite func()
// looked counts the lookups of each path
looked map[string]int
// failLookups fails the lookups of these paths, as a filer that cannot read them
failLookups map[string]bool
}
func (f *conditionalFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.looked == nil {
f.looked = map[string]int{}
}
f.looked[req.Directory+"/"+req.Name]++
if f.failLookups[req.Directory+"/"+req.Name] {
return nil, status.Error(codes.Unavailable, "store unavailable")
}
entry, ok := f.entries[req.Directory+"/"+req.Name]
if !ok {
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
}
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil
}
func (f *conditionalFiler) ObjectTransaction(ctx context.Context, req *filer_pb.ObjectTransactionRequest) (*filer_pb.ObjectTransactionResponse, error) {
f.mu.Lock()
hook := f.beforeWrite
f.beforeWrite = nil
f.mu.Unlock()
if hook != nil {
hook()
}
f.mu.Lock()
defer f.mu.Unlock()
current := f.entries[req.ConditionKey]
for _, clause := range req.Condition.GetClauses() {
held := true
switch clause.Kind {
case filer_pb.WriteCondition_IF_NOT_EXISTS:
held = current == nil
case filer_pb.WriteCondition_IF_ENTRY_EQUAL:
held = current != nil && proto.Equal(current, clause.ExpectedEntry)
}
if !held {
return &filer_pb.ObjectTransactionResponse{ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED, Error: "precondition failed"}, nil
}
}
for _, m := range req.Mutations {
f.entries[m.Directory+"/"+m.Entry.Name] = proto.Clone(m.Entry).(*filer_pb.Entry)
}
return &filer_pb.ObjectTransactionResponse{}, nil
}
func (f *conditionalFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.entries[req.Directory+"/"+req.Entry.Name] = proto.Clone(req.Entry).(*filer_pb.Entry)
return &filer_pb.CreateEntryResponse{}, nil
}
func (f *conditionalFiler) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.entries[req.Directory+"/"+req.Entry.Name] = proto.Clone(req.Entry).(*filer_pb.Entry)
return &filer_pb.UpdateEntryResponse{}, nil
}
// ListEntries lists the stored entries directly under req.Directory and the
// directories their paths imply.
func (f *conditionalFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
f.mu.Lock()
children := map[string]*filer_pb.Entry{}
for path, entry := range f.entries {
rest, ok := strings.CutPrefix(path, req.Directory+"/")
if !ok {
continue
}
if name, _, deeper := strings.Cut(rest, "/"); deeper {
children[name] = &filer_pb.Entry{Name: name, IsDirectory: true}
} else {
children[name] = entry
}
}
f.mu.Unlock()
names := make([]string, 0, len(children))
for name := range children {
names = append(names, name)
}
slices.Sort(names)
for _, name := range names {
if name <= req.StartFromFileName {
continue
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: children[name]}); err != nil {
return err
}
}
return nil
}
func TestListConsumerGroupPositionsAcrossGenerations(t *testing.T) {
_, s := newFencedStorage(t)
later := topic.Partition{RingSize: 4096, RangeStart: 1024, RangeStop: 2048, UnixTimeNs: 3_000_000_000}
if err := savePosition(s, 10, 5, "a"); err != nil {
t.Fatal(err)
}
if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, later, "forwarder", &ConsumerGroupPosition{Type: "offset", Value: 20}); err != nil {
t.Fatal(err)
}
if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, later, "other", &ConsumerGroupPosition{Type: "offset", Value: 30}); err != nil {
t.Fatal(err)
}
// a partition only another group has a position in is listed without one
untouched := topic.Partition{RingSize: 4096, RangeStart: 2048, RangeStop: 4096, UnixTimeNs: 3_000_000_000}
if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, untouched, "other", &ConsumerGroupPosition{Type: "offset", Value: 40}); err != nil {
t.Fatal(err)
}
positions, err := s.ListConsumerGroupPositions(context.Background(), fenceTopic, "forwarder", nil)
if err != nil {
t.Fatal(err)
}
value := func(p topic.Partition) int64 {
if position := positions[topic.PartitionDir(fenceTopic, p)]; position != nil {
return position.Value
}
return -1
}
none, listed := positions[topic.PartitionDir(fenceTopic, untouched)]
if len(positions) != 3 || value(fencePartition) != 10 || value(later) != 20 || !listed || none != nil {
t.Fatalf("listed %v", positions)
}
}
// A listing whose read of one position fails still returns the positions it
// read, so a caller retrying need not read them again.
func TestListConsumerGroupPositionsReturnsWhatItReadOnAFailure(t *testing.T) {
f, s := newFencedStorage(t)
var dirs []string
for generation := int64(1); generation <= 3; generation++ {
p := topic.Partition{RingSize: 4096, RangeStart: 0, RangeStop: 4096, UnixTimeNs: generation * 1_000_000_000}
if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, p, "forwarder", &ConsumerGroupPosition{Type: "offset", Value: generation}); err != nil {
t.Fatal(err)
}
dirs = append(dirs, topic.PartitionDir(fenceTopic, p))
}
f.mu.Lock()
f.failLookups = map[string]bool{dirs[1] + "/consumers/forwarder.offset": true}
f.mu.Unlock()
positions, err := s.ListConsumerGroupPositions(context.Background(), fenceTopic, "forwarder", nil)
if err == nil {
t.Fatal("listing with an unreadable position succeeded")
}
first, third := positions[dirs[0]], positions[dirs[2]]
if _, failed := positions[dirs[1]]; len(positions) != 2 || failed || first == nil || first.Value != 1 || third == nil || third.Value != 3 {
t.Fatalf("listed %v, want the two positions that could be read", positions)
}
}
// Of many historical partition directories, a listing reads the positions of
// only those the caller does not already know about.
func TestListConsumerGroupPositionsLoadsOnlyWhatIsNotSkipped(t *testing.T) {
f, s := newFencedStorage(t)
var unknown []string
for generation := int64(1); generation <= 40; generation++ {
p := topic.Partition{RingSize: 4096, RangeStart: 0, RangeStop: 4096, UnixTimeNs: generation * 1_000_000_000}
if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, p, "forwarder", &ConsumerGroupPosition{Type: "offset", Value: generation}); err != nil {
t.Fatal(err)
}
if generation%20 == 0 {
unknown = append(unknown, topic.PartitionDir(fenceTopic, p))
}
}
f.mu.Lock()
f.looked = nil
f.mu.Unlock()
positions, err := s.ListConsumerGroupPositions(context.Background(), fenceTopic, "forwarder", func(dir string) bool {
return !slices.Contains(unknown, dir)
})
if err != nil {
t.Fatal(err)
}
first, second := positions[unknown[0]], positions[unknown[1]]
if len(positions) != 2 || first == nil || first.Value != 20 || second == nil || second.Value != 40 {
t.Fatalf("listed %v, want only %v", positions, unknown)
}
f.mu.Lock()
defer f.mu.Unlock()
loads := 0
for path, n := range f.looked {
if strings.HasSuffix(path, ".offset") {
loads += n
}
}
if loads != 2 {
t.Fatalf("%d position loads, want 2", loads)
}
}
func startConditionalFiler(t *testing.T) (*conditionalFiler, pb.ServerAddress) {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
f := &conditionalFiler{entries: map[string]*filer_pb.Entry{}}
server := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(server, f)
go server.Serve(listener)
t.Cleanup(server.Stop)
return f, pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port)
}
func newFencedStorage(t *testing.T) (*conditionalFiler, *FilerConsumerGroupOffsetStorage) {
t.Helper()
f, address := startConditionalFiler(t)
accessor := filer_client.NewFilerClientAccessor([]pb.ServerAddress{address}, grpc.WithTransportCredentials(insecure.NewCredentials()))
return f, NewFilerConsumerGroupOffsetStorageWithAccessor(accessor)
}
func TestLoadReadsAtTheOwnerFiler(t *testing.T) {
// the accessor's filer still holds an older position than the key's owner
_, s := newFencedStorage(t)
if err := savePosition(s, 50, 5, "a"); err != nil {
t.Fatal(err)
}
_, ownerAddress := startConditionalFiler(t)
s.WriteOwner = func(routeKey string) pb.ServerAddress { return ownerAddress }
if _, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder"); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("load before the owner holds a position: %v, want ErrNotFound", err)
}
if err := savePosition(s, 100, 6, "b"); err != nil {
t.Fatal(err)
}
got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder")
if err != nil {
t.Fatal(err)
}
if got.Value != 100 || got.Generation != 6 {
t.Fatalf("loaded %+v, want the owner's offset 100 at generation 6", got)
}
}
// While the owner of a position is not known yet, as before the lock ring is
// learned, another filer's answer is not taken: its "not found" may only mean
// it has not caught up, and a takeover there would rewind the partition.
func TestAPositionWaitsForItsOwnerToBeKnown(t *testing.T) {
_, s := newFencedStorage(t)
s.WriteOwner = func(string) pb.ServerAddress { return "" }
if _, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder"); err == nil || errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("load with no owner known: %v, want an error other than not found", err)
}
if err := savePosition(s, 10, 5, "a"); err == nil {
t.Fatal("fenced save with no owner known succeeded")
}
}
func TestFencedSaveReadsAndWritesAtTheOwnerFiler(t *testing.T) {
// the accessor's filer holds an older copy than the key's owner
replica, s := newFencedStorage(t)
owner, ownerAddress := startConditionalFiler(t)
if err := savePosition(s, 10, 5, "a"); err != nil {
t.Fatal(err)
}
var routed []string
s.WriteOwner = func(routeKey string) pb.ServerAddress {
routed = append(routed, routeKey)
return ownerAddress
}
if err := savePosition(s, 20, 7, "c"); err != nil {
t.Fatal(err)
}
if err := savePosition(s, 30, 6, "b"); !errors.Is(err, ErrStaleGeneration) {
t.Fatalf("save below the owner's generation: %v, want ErrStaleGeneration", err)
}
path := topic.PartitionDir(fenceTopic, fencePartition) + "/consumers/forwarder.offset"
if len(routed) != 2 || routed[0] != s3_constants.ObjectWriteRouteKeyPrefix+path {
t.Fatalf("routed %v", routed)
}
owner.mu.Lock()
stored := string(owner.entries[path].GetContent())
owner.mu.Unlock()
replica.mu.Lock()
stale := string(replica.entries[path].GetContent())
replica.mu.Unlock()
if !strings.Contains(stored, `"generation":7`) || !strings.Contains(stale, `"generation":5`) {
t.Fatalf("owner holds %s, replica %s", stored, stale)
}
}
var (
fenceTopic = topic.NewTopic("s3", "notify-orders")
fencePartition = topic.Partition{RingSize: 4096, RangeStart: 0, RangeStop: 1024, UnixTimeNs: 1}
)
func savePosition(s *FilerConsumerGroupOffsetStorage, value, generation int64, writer string) error {
return s.SaveConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder", &ConsumerGroupPosition{
Type: "offset", Value: value, Generation: generation, Writer: writer,
})
}
func TestFencedSaveRefusesAnOlderGeneration(t *testing.T) {
_, s := newFencedStorage(t)
if _, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder"); !errors.Is(err, filer_pb.ErrNotFound) {
t.Fatalf("load of a missing position: %v, want ErrNotFound", err)
}
if err := savePosition(s, 10, 5, "a"); err != nil {
t.Fatal(err)
}
if err := savePosition(s, 20, 6, "b"); err != nil {
t.Fatalf("newer generation refused: %v", err)
}
if err := savePosition(s, 30, 5, "a"); !errors.Is(err, ErrStaleGeneration) {
t.Fatalf("deposed writer's save: %v, want ErrStaleGeneration", err)
}
if err := savePosition(s, 30, 6, "c"); !errors.Is(err, ErrStaleGeneration) {
t.Fatalf("another writer at the same generation: %v, want ErrStaleGeneration", err)
}
if err := savePosition(s, 25, 6, "b"); err != nil {
t.Fatalf("holder's own save refused: %v", err)
}
got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder")
if err != nil {
t.Fatal(err)
}
if got.Value != 25 || got.Generation != 6 || got.Writer != "b" {
t.Fatalf("stored %+v", got)
}
}
// A new generation's first save takes over the partition at the offset the old
// generation committed last, not the one the new one loaded before it, even
// when the old one commits again between that save's read and its write.
func TestATakeoverKeepsTheOffsetItReplaces(t *testing.T) {
f, s := newFencedStorage(t)
if err := savePosition(s, 10, 5, "a"); err != nil {
t.Fatal(err)
}
// generation 6 loaded 10; generation 5 commits 20 and then 30
if err := savePosition(s, 20, 5, "a"); err != nil {
t.Fatal(err)
}
f.mu.Lock()
f.beforeWrite = func() {
if err := savePosition(s, 30, 5, "a"); err != nil {
t.Error(err)
}
}
f.mu.Unlock()
claim := &ConsumerGroupPosition{Type: "offset", Value: 10, Generation: 6, Writer: "b", Metadata: "claimed"}
if err := s.SaveConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder", claim); err != nil {
t.Fatal(err)
}
if claim.Value != 30 || claim.Metadata != "" {
t.Fatalf("takeover answered offset %d metadata %q, want offset 30 and the replaced entry's metadata", claim.Value, claim.Metadata)
}
got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder")
if err != nil {
t.Fatal(err)
}
if got.Value != 30 || got.Generation != 6 || got.Writer != "b" {
t.Fatalf("stored %+v, want offset 30 at generation 6 by b", got)
}
}
func TestFencedSaveRechecksWhenAWriterLandsBetweenReadAndWrite(t *testing.T) {
f, s := newFencedStorage(t)
if err := savePosition(s, 10, 5, "a"); err != nil {
t.Fatal(err)
}
// a newer generation lands after this save read generation 5
f.mu.Lock()
f.beforeWrite = func() {
if err := savePosition(s, 40, 7, "c"); err != nil {
t.Error(err)
}
}
f.mu.Unlock()
if err := savePosition(s, 20, 6, "b"); !errors.Is(err, ErrStaleGeneration) {
t.Fatalf("save racing a newer generation: %v, want ErrStaleGeneration", err)
}
got, err := s.LoadConsumerGroupPosition(context.Background(), fenceTopic, fencePartition, "forwarder")
if err != nil {
t.Fatal(err)
}
// generation 7 took over at the offset generation 5 committed
if got.Value != 10 || got.Generation != 7 || got.Writer != "c" {
t.Fatalf("stored %+v, want the newer generation's", got)
}
}
func TestUnfencedSaveStillOverwrites(t *testing.T) {
_, s := newFencedStorage(t)
if err := savePosition(s, 10, 5, "a"); err != nil {
t.Fatal(err)
}
if err := s.SaveConsumerGroupOffset(fenceTopic, fencePartition, "forwarder", 3); err != nil {
t.Fatal(err)
}
got, err := s.LoadConsumerGroupOffset(fenceTopic, fencePartition, "forwarder")
if err != nil || got != 3 {
t.Fatalf("offset %d, %v", got, err)
}
}
+218 -15
View File
@@ -3,17 +3,32 @@ package offset
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"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/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/util"
"golang.org/x/sync/errgroup"
)
// ErrStaleGeneration refuses a save fenced by a generation that another
// writer has superseded.
var ErrStaleGeneration = errors.New("consumer group position is held by a newer generation")
// fencedSaveAttempts bounds the retries of a fenced save whose stored position
// changed between its read and its write.
const fencedSaveAttempts = 5
// ConsumerGroupPosition represents a consumer's position in a partition
// This can be either a timestamp or an offset
type ConsumerGroupPosition struct {
@@ -22,6 +37,15 @@ type ConsumerGroupPosition struct {
OffsetType string `json:"offset_type"` // Optional: OffsetType enum name (e.g., "EXACT_OFFSET")
CommittedAt int64 `json:"committed_at"` // Unix timestamp in milliseconds when committed
Metadata string `json:"metadata"` // Optional: application-specific metadata
// Generation, when set, fences the save: it is refused when the stored
// position carries a newer generation, or the same one from another Writer.
Generation int64 `json:"generation,omitempty"`
Writer string `json:"writer,omitempty"`
}
// supersedes reports whether a stored position fences out a save of p.
func (stored *ConsumerGroupPosition) supersedes(p *ConsumerGroupPosition) bool {
return stored.Generation > p.Generation || (stored.Generation == p.Generation && stored.Writer != p.Writer)
}
// ConsumerGroupOffsetStorage handles consumer group offset persistence
@@ -31,14 +55,15 @@ type ConsumerGroupOffsetStorage interface {
// SaveConsumerGroupOffset saves the committed offset for a consumer group
SaveConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string, offset int64) error
// SaveConsumerGroupPosition saves the committed position (offset or timestamp) for a consumer group
SaveConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error
// SaveConsumerGroupPosition saves the committed position (offset or timestamp) for a consumer group;
// a position with a Generation is refused with ErrStaleGeneration when a newer one is stored
SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error
// LoadConsumerGroupOffset loads the committed offset for a consumer group (backward compatible)
LoadConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string) (int64, error)
// LoadConsumerGroupPosition loads the committed position for a consumer group
LoadConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error)
LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error)
// ListConsumerGroups returns all consumer groups for a topic partition
ListConsumerGroups(t topic.Topic, p topic.Partition) ([]string, error)
@@ -50,6 +75,10 @@ type ConsumerGroupOffsetStorage interface {
// FilerConsumerGroupOffsetStorage implements ConsumerGroupOffsetStorage using SeaweedFS filer
type FilerConsumerGroupOffsetStorage struct {
filerClientAccessor *filer_client.FilerClientAccessor
// WriteOwner, when set, names the filer owning a route key. Loads and
// fenced saves then go there, so a save's condition is checked against what
// it read and a load sees the latest save, not another filer's copy.
WriteOwner func(routeKey string) pb.ServerAddress
}
// NewFilerConsumerGroupOffsetStorageWithAccessor creates storage using a shared filer client accessor
@@ -69,31 +98,111 @@ func (f *FilerConsumerGroupOffsetStorage) SaveConsumerGroupOffset(t topic.Topic,
OffsetType: schema_pb.OffsetType_EXACT_OFFSET.String(),
CommittedAt: time.Now().UnixMilli(),
}
return f.SaveConsumerGroupPosition(t, p, consumerGroup, position)
return f.SaveConsumerGroupPosition(context.Background(), t, p, consumerGroup, position)
}
// SaveConsumerGroupPosition saves the committed position (offset or timestamp) for a consumer group
// Stores as JSON: /topics/{namespace}/{topic}/{version}/{partition}/consumers/{consumer_group}.offset
func (f *FilerConsumerGroupOffsetStorage) SaveConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error {
func (f *FilerConsumerGroupOffsetStorage) SaveConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string, position *ConsumerGroupPosition) error {
partitionDir := topic.PartitionDir(t, p)
consumersDir := fmt.Sprintf("%s/consumers", partitionDir)
offsetFileName := fmt.Sprintf("%s.offset", consumerGroup)
// Marshal position to JSON
jsonBytes, err := json.Marshal(position)
if err != nil {
return fmt.Errorf("failed to marshal position to JSON: %w", err)
if position.Generation == 0 {
jsonBytes, err := json.Marshal(position)
if err != nil {
return fmt.Errorf("failed to marshal position to JSON: %w", err)
}
return f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer.SaveInsideFiler(ctx, client, consumersDir, offsetFileName, jsonBytes)
})
}
return f.saveFencedPosition(ctx, consumersDir, offsetFileName, position)
}
return f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer.SaveInsideFiler(context.Background(), client, consumersDir, offsetFileName, jsonBytes)
// saveFencedPosition writes the position only while no newer generation is
// stored, as a conditional write on the stored entry routed to its owner filer.
// A save taking over from an older generation keeps the offset and metadata
// that generation committed last, and sets them in position.
func (f *FilerConsumerGroupOffsetStorage) saveFencedPosition(ctx context.Context, dir, name string, position *ConsumerGroupPosition) error {
path := dir + "/" + name
routeKey := s3_constants.ObjectWriteRouteKeyPrefix + path
// a refusal is returned from outside the accessor, which would otherwise
// try the next filer and flatten the error
var stale *ConsumerGroupPosition
requested, requestedMetadata := position.Value, position.Metadata
err := f.withPositionFiler(routeKey, func(client filer_pb.SeaweedFilerClient) error {
for attempt := 1; ; attempt++ {
condition := &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}
position.Value, position.Metadata = requested, requestedMetadata
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: name})
switch {
case err == nil:
stored := &ConsumerGroupPosition{}
if json.Unmarshal(resp.Entry.Content, stored) == nil {
if stored.supersedes(position) {
stale = stored
return nil
}
if stored.Generation < position.Generation {
position.Value, position.Metadata = stored.Value, stored.Metadata
}
}
condition = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: resp.Entry}
case !errors.Is(err, filer_pb.ErrNotFound):
return err
}
content, err := json.Marshal(position)
if err != nil {
return fmt.Errorf("failed to marshal position to JSON: %w", err)
}
now := time.Now()
entry := &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{
Mtime: now.Unix(),
Crtime: now.Unix(),
FileMode: uint32(0644),
FileSize: uint64(len(content)),
Md5: util.Md5(content),
},
Content: content,
}
txn, err := client.ObjectTransaction(ctx, &filer_pb.ObjectTransactionRequest{
LockKey: path,
RouteKey: routeKey,
ConditionKey: path,
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{condition}},
Mutations: []*filer_pb.ObjectMutation{{Type: filer_pb.ObjectMutation_PUT, Directory: dir, Entry: entry}},
})
if err != nil {
return err
}
if txn.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED && attempt < fencedSaveAttempts {
continue
}
if txn.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED {
return fmt.Errorf("save %s: changed by another writer %d times in a row", path, attempt)
}
if txn.Error != "" {
return fmt.Errorf("save %s: %s", path, txn.Error)
}
return nil
}
})
if err != nil {
return err
}
if stale != nil {
return fmt.Errorf("%s at generation %d by %s: %w", path, stale.Generation, stale.Writer, ErrStaleGeneration)
}
return nil
}
// LoadConsumerGroupOffset loads the committed offset for a consumer group
// This method provides backward compatibility and returns just the offset value
func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string) (int64, error) {
position, err := f.LoadConsumerGroupPosition(t, p, consumerGroup)
position, err := f.LoadConsumerGroupPosition(context.Background(), t, p, consumerGroup)
if err != nil {
return -1, err
}
@@ -101,14 +210,21 @@ func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupOffset(t topic.Topic,
}
// LoadConsumerGroupPosition loads the committed position for a consumer group
func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupPosition(t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error) {
func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupPosition(ctx context.Context, t topic.Topic, p topic.Partition, consumerGroup string) (*ConsumerGroupPosition, error) {
partitionDir := topic.PartitionDir(t, p)
consumersDir := fmt.Sprintf("%s/consumers", partitionDir)
offsetFileName := fmt.Sprintf("%s.offset", consumerGroup)
var position *ConsumerGroupPosition
err := f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
data, err := filer.ReadInsideFiler(context.Background(), client, consumersDir, offsetFileName)
notFound := false
routeKey := s3_constants.ObjectWriteRouteKeyPrefix + consumersDir + "/" + offsetFileName
err := f.withPositionFiler(routeKey, func(client filer_pb.SeaweedFilerClient) error {
data, err := filer.ReadInsideFiler(ctx, client, consumersDir, offsetFileName)
if errors.Is(err, filer_pb.ErrNotFound) {
// answered by a reachable filer, so no other filer is asked
notFound = true
return nil
}
if err != nil {
return err
}
@@ -125,10 +241,97 @@ func (f *FilerConsumerGroupOffsetStorage) LoadConsumerGroupPosition(t topic.Topi
if err != nil {
return nil, err
}
if notFound {
return nil, fmt.Errorf("%s/%s: %w", consumersDir, offsetFileName, filer_pb.ErrNotFound)
}
return position, nil
}
// ListConsumerGroupPositions lists every partition directory of every generation
// of t but those skip reports, with consumerGroup's position in it, nil where
// the group stored none. Only the directories listed have their position read.
// When a read fails, as on ctx ending, it returns the positions read along with
// the error, so a caller retrying can skip those next time.
func (f *FilerConsumerGroupOffsetStorage) ListConsumerGroupPositions(ctx context.Context, t topic.Topic, consumerGroup string, skip func(dir string) bool) (map[string]*ConsumerGroupPosition, error) {
var partitions []topic.Partition
err := f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
partitions = nil
var versions []string
err := filer_pb.SeaweedList(ctx, client, t.Dir(), "", func(entry *filer_pb.Entry, isLast bool) error {
if _, parseErr := topic.ParseTopicVersion(entry.Name); entry.IsDirectory && parseErr == nil {
versions = append(versions, entry.Name)
}
return nil
}, "", false, math.MaxInt32)
if err != nil {
return err
}
for _, version := range versions {
versionTime, _ := topic.ParseTopicVersion(version)
err := filer_pb.SeaweedList(ctx, client, t.Dir()+"/"+version, "", func(entry *filer_pb.Entry, isLast bool) error {
if start, stop := topic.ParsePartitionBoundary(entry.Name); entry.IsDirectory && start != stop {
partitions = append(partitions, topic.Partition{RangeStart: start, RangeStop: stop, UnixTimeNs: versionTime.UnixNano()})
}
return nil
}, "", false, math.MaxInt32)
if err != nil {
return err
}
}
return nil
})
if errors.Is(err, filer_pb.ErrNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
var mu sync.Mutex
positions := map[string]*ConsumerGroupPosition{}
var loads errgroup.Group
loads.SetLimit(listPositionLoads)
for _, p := range partitions {
dir := topic.PartitionDir(t, p)
if skip != nil && skip(dir) {
continue
}
loads.Go(func() error {
position, err := f.LoadConsumerGroupPosition(ctx, t, p, consumerGroup)
if errors.Is(err, filer_pb.ErrNotFound) {
position, err = nil, nil
}
if err != nil {
return err
}
mu.Lock()
positions[dir] = position
mu.Unlock()
return nil
})
}
err = loads.Wait()
return positions, err
}
// listPositionLoads bounds the position reads a listing has in flight.
const listPositionLoads = 8
// withPositionFiler runs fn against the filer owning routeKey when WriteOwner
// is set, so a load sees what a fenced save there wrote, else any filer. With
// WriteOwner set but no owner known yet it fails rather than ask another filer,
// whose "not found" may only mean it has not caught up.
func (f *FilerConsumerGroupOffsetStorage) withPositionFiler(routeKey string, fn func(filer_pb.SeaweedFilerClient) error) error {
if f.WriteOwner != nil {
owner := f.WriteOwner(routeKey)
if owner == "" {
return fmt.Errorf("no filer owns %s yet", routeKey)
}
return pb.WithGrpcFilerClient(false, 0, owner, f.filerClientAccessor.GetGrpcDialOption(), f.filerClientAccessor.TokenSource, fn)
}
return f.filerClientAccessor.WithFilerClient(false, fn)
}
// ListConsumerGroups returns all consumer groups for a topic partition
func (f *FilerConsumerGroupOffsetStorage) ListConsumerGroups(t topic.Topic, p topic.Partition) ([]string, error) {
partitionDir := topic.PartitionDir(t, p)
+4 -3
View File
@@ -103,15 +103,16 @@ func (f *fakeNotificationPublisher) published() []s3notification.Message {
return append([]s3notification.Message(nil), f.messages...)
}
func TestNotificationTargetsChangeSyncsThePublisher(t *testing.T) {
publisher := &fakeNotificationPublisher{}
s3a := &S3ApiServer{notificationPublisher: publisher}
func TestNotificationTargetsChangeSyncsThePublisherAndForwarder(t *testing.T) {
publisher, forwarder := &fakeNotificationPublisher{}, &fakeNotificationPublisher{}
s3a := &S3ApiServer{notificationPublisher: publisher, notificationForwarder: forwarder}
dir, file := s3notification.TargetsDirectory, s3notification.TargetsFile
s3a.onNotificationTargetsChange(dir, nil, targetsEntry(file, testNotificationTargets))
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), targetsEntry(file, `{"targets":[{"name":"x","type":"nope"}]}`))
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), nil)
require.Equal(t, [][]string{{"orders", "raw", "off"}, nil}, publisher.synced)
require.Equal(t, [][]string{{"orders", "raw", "off"}, nil}, forwarder.synced)
}
func TestLoadNotificationTargets(t *testing.T) {
+46 -1
View File
@@ -2,13 +2,17 @@ package s3api
import (
"context"
"fmt"
"net/http"
"slices"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
@@ -17,6 +21,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
"google.golang.org/grpc"
)
const notificationBrokerListTimeout = 5 * time.Second
@@ -40,6 +45,42 @@ func (s3a *S3ApiServer) newNotificationPublisher() notificationPublisher {
return s3notification.NewPublisher(s3a.notificationBrokers, dialOption)
}
// notificationForwarder is what the gateway needs from s3notification.Forwarder.
type notificationForwarder interface {
Sync(reg *s3notification.Registry)
Close()
}
// newNotificationForwarder elects forwarders through the filers' lock ring and
// stores their offsets in the filer; without filers there is neither. As for
// the publisher, an unusable grpc.msg_broker client TLS config leaves it off.
func (s3a *S3ApiServer) newNotificationForwarder() notificationForwarder {
if s3a.objectWriteLockClient == nil || len(s3a.option.Filers) == 0 {
return nil
}
dialOption, err := security.TryLoadClientTLS(util.GetViper(), "grpc.msg_broker", "grpc.msg_broker")
if err != nil {
glog.Errorf("bucket notification forwarding is off: %v", err)
return nil
}
accessor := &filer_client.FilerClientAccessor{
GetGrpcDialOption: func() grpc.DialOption { return s3a.option.GrpcDialOption },
GetFilers: func() []pb.ServerAddress {
if s3a.filerClient != nil {
if filers := s3a.filerClient.GetAllFilers(); len(filers) > 0 {
return filers
}
}
return s3a.option.Filers
},
TokenSource: security.FilerAdminToken,
}
positions := offset.NewFilerConsumerGroupOffsetStorageWithAccessor(accessor)
positions.WriteOwner = s3a.objectWriteLockClient.PrimaryForKey
owner := fmt.Sprintf("s3-%s-%d", util.JoinHostPort(s3a.option.AdvertisedHost(), s3a.option.Port), s3a.randomClientId)
return s3notification.NewForwarder(s3a.notificationBrokers, dialOption, positions, s3a.objectWriteLockClient, owner)
}
// notificationBrokers lists the brokers a publisher bootstraps from: the one
// beside this gateway first, then every broker the masters know.
func (s3a *S3ApiServer) notificationBrokers() []string {
@@ -207,9 +248,13 @@ func notificationPrincipal(r *http.Request) string {
return s3_constants.AccountAnonymousId
}
// syncNotificationPublisher gives every target in reg a publisher worker.
// syncNotificationPublisher gives every target in reg a publisher worker and,
// when it has a destination, a forwarder.
func (s3a *S3ApiServer) syncNotificationPublisher(reg *s3notification.Registry) {
if s3a.notificationPublisher != nil {
s3a.notificationPublisher.Sync(reg)
}
if s3a.notificationForwarder != nil {
s3a.notificationForwarder.Sync(reg)
}
}
@@ -3,8 +3,12 @@ package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func TestNotificationBrokersStartWithTheGatewaysOwn(t *testing.T) {
@@ -28,3 +32,18 @@ func TestABadBrokerTLSConfigTurnsNotificationsOff(t *testing.T) {
require.NotNil(t, publisher)
publisher.Close()
}
func TestABadBrokerTLSConfigTurnsForwardingOff(t *testing.T) {
v := util.GetViper()
v.Set("grpc.msg_broker.cert", "/nonexistent/broker.crt")
t.Cleanup(func() { v.Set("grpc.msg_broker.cert", "") })
option := &S3ApiServerOption{Filers: []pb.ServerAddress{"127.0.0.1:8888"}, GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials())}
s3a := &S3ApiServer{option: option, objectWriteLockClient: cluster.NewLockClient(option.GrpcDialOption, option.Filers[0])}
require.Nil(t, s3a.newNotificationForwarder(), "a cert without its key must leave forwarding off, not stop the gateway")
v.Set("grpc.msg_broker.cert", "")
forwarder := s3a.newNotificationForwarder()
require.NotNil(t, forwarder)
forwarder.Close()
}
+5
View File
@@ -171,6 +171,7 @@ type S3ApiServer struct {
notificationTargets atomic.Pointer[s3notification.Registry]
notificationPublisher notificationPublisher
notificationForwarder notificationForwarder
}
type objectWriteLock interface {
@@ -588,6 +589,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
watched = append(watched, dir)
}
s3ApiServer.notificationPublisher = s3ApiServer.newNotificationPublisher()
s3ApiServer.notificationForwarder = s3ApiServer.newNotificationForwarder()
s3ApiServer.loadNotificationTargets()
go s3ApiServer.subscribeMetaEvents("s3", startTsNs, filer.DirectoryEtcRoot, watched)
@@ -634,6 +636,9 @@ func (s3a *S3ApiServer) Shutdown() {
if s3a.notificationPublisher != nil {
s3a.notificationPublisher.Close()
}
if s3a.notificationForwarder != nil {
s3a.notificationForwarder.Close()
}
}
// getFilerAddress returns the current active filer address
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+72 -9
View File
@@ -176,7 +176,10 @@ func TestPublishGivesUpWaitingButKeepsTheRecord(t *testing.T) {
if waited := time.Since(start); waited < tp.ackWait || waited > tp.ackWait+time.Second {
t.Fatalf("waited %v, want about %v", waited, tp.ackWait)
}
waitUntil(t, "the record to reach the publisher", func() bool { return len(tp.topic("slow").published()) == 1 })
waitUntil(t, "the record to reach the publisher", func() bool {
f := tp.topic("slow")
return f != nil && len(f.published()) == 1
})
if d := dropped("slow"); d != 0 {
t.Fatalf("a late record was counted dropped %v times", d)
}
@@ -469,7 +472,8 @@ func TestStoppingATargetReleasesAPublisherBlockedOnAFullBuffer(t *testing.T) {
}
// fakeBroker is an in-process broker that refuses topic configuration while
// it is "starting", then leads every partition and acks each message.
// it is "starting", then leads every partition, acks each message, and serves
// what it holds to FetchMessage.
type fakeBroker struct {
mq_pb.UnimplementedSeaweedMessagingServer
addr string
@@ -484,6 +488,28 @@ type fakeBroker struct {
recordType []*schema_pb.RecordType // every record type a ConfigureTopic carried
stored map[string][]string
values [][]byte
logs map[fakeLogKey]*fakeLog
fetches map[fakeLogKey]int
// version and partitionCount are the generation and number of the
// partitions lookups list; a repartition changes them
version int64
partitionCount int32
// retired holds the partition count of each generation a repartition replaced
retired map[int64]int32
// unsealed retired generations are neither listed nor served, as before a drain seals them
unsealed map[int64]bool
// segment, when set, ends each fetch at the next multiple of it, as a
// flushed segment's boundary does
segment int64
failFetches int
// holding makes a fetch at holdAt return no records, as a broker that
// cannot read a span it reports below its high-water mark does
holding bool
holdAt int64
// onFetch runs as a fetch arrives
onFetch func()
// fetchErrorCode, when set, answers every fetch with that broker error, as a broker that cannot read the files does
fetchErrorCode int32
}
func (b *fakeBroker) ConfigureTopic(ctx context.Context, req *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
@@ -509,21 +535,56 @@ func (b *fakeBroker) LookupTopicBrokers(ctx context.Context, req *mq_pb.LookupTo
if b.failLookups {
return nil, status.Error(codes.Unavailable, "no broker available")
}
b.mu.Lock()
defer b.mu.Unlock()
resp := &mq_pb.LookupTopicBrokersResponse{Topic: req.Topic}
width := int32(pub_balancer.MaxPartitionCount / TopicPartitionCount)
for i := int32(0); i < TopicPartitionCount; i++ {
stop := (i + 1) * width
if i == TopicPartitionCount-1 {
stop = pub_balancer.MaxPartitionCount
}
for _, partition := range b.assignedLocked() {
resp.BrokerPartitionAssignments = append(resp.BrokerPartitionAssignments, &mq_pb.BrokerPartitionAssignment{
Partition: &schema_pb.Partition{RingSize: pub_balancer.MaxPartitionCount, RangeStart: i * width, RangeStop: stop},
Partition: partition,
LeaderBroker: b.addr,
})
}
if req.IncludeRetired {
for version, count := range b.retired {
if b.unsealed[version] {
continue
}
// listed as the broker finds them, from their directory names
for _, partition := range generationPartitions(atSecond(version), count) {
if log := b.logs[fakeLogKey{version, partition.RangeStart}]; log != nil && int64(len(log.values)) > log.start {
resp.RetiredPartitions = append(resp.RetiredPartitions, &mq_pb.RetiredPartition{
Partition: partition, LogStartOffset: log.start, HighWaterMark: int64(len(log.values)),
})
}
}
}
}
return resp, nil
}
// assignedLocked is the current generation's partitions, TopicPartitionCount
// of them unless a repartition set partitionCount.
func (b *fakeBroker) assignedLocked() []*schema_pb.Partition {
count := int32(TopicPartitionCount)
if b.partitionCount > 0 {
count = b.partitionCount
}
return generationPartitions(b.version, count)
}
func generationPartitions(version int64, count int32) []*schema_pb.Partition {
width := pub_balancer.MaxPartitionCount / count
var partitions []*schema_pb.Partition
for i := int32(0); i < count; i++ {
stop := (i + 1) * width
if i == count-1 {
stop = pub_balancer.MaxPartitionCount
}
partitions = append(partitions, &schema_pb.Partition{RingSize: pub_balancer.MaxPartitionCount, RangeStart: i * width, RangeStop: stop, UnixTimeNs: version})
}
return partitions
}
func (b *fakeBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
init, err := stream.Recv()
if err != nil {
@@ -548,6 +609,8 @@ func (b *fakeBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessage
b.mu.Lock()
b.stored[partition] = append(b.stored[partition], string(data.Key))
b.values = append(b.values, data.Value)
p := init.GetInit().GetPartition()
b.appendLocked(fakeLogKey{p.GetUnixTimeNs(), p.GetRangeStart()}, data.Value)
b.mu.Unlock()
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs}); err != nil {
return err
+175
View File
@@ -0,0 +1,175 @@
package s3notification
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/netguard"
)
const (
webhookTimeout = 30 * time.Second
// webhookErrorBodyLimit is how much of a refusal's body is kept for the log.
webhookErrorBodyLimit = 256
maxWebhookRedirects = 10
)
// destination delivers a batch of records in order; nil means the
// destination took all of them, and an *unrenderableError names records it
// never will.
type destination interface {
Send(ctx context.Context, records []*schema_pb.RecordValue) error
}
// webhook POSTs a batch as one {"Records":[...]} body, a test event in its
// own body, and takes any 2xx as delivered.
type webhook struct {
endpoint string
token string
render func(records ...*schema_pb.RecordValue) ([]byte, error)
client *http.Client
}
func newWebhook(t *Target) *webhook {
return &webhook{
endpoint: t.Endpoint,
token: t.BearerToken,
render: Render,
client: &http.Client{
Timeout: webhookTimeout,
Transport: &http.Transport{
// no proxy, so the dialer checks the address actually connected to
Proxy: nil,
DialContext: netguard.DialContext(redactedEndpoint(t.Endpoint), netguard.Local),
ForceAttemptHTTP2: true,
MaxIdleConnsPerHost: 4,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
},
CheckRedirect: sameHostRedirect,
},
}
}
// sameHostRedirect follows a redirect only to the endpoint's own host and
// never from https to http, so the token and records stay with the endpoint
// the operator configured. Only 307 and 308 are followed: on 301, 302 and 303
// Go resends the POST as a bodiless GET, whose 2xx would pass for delivery.
func sameHostRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= maxWebhookRedirects {
return fmt.Errorf("stopped after %d redirects", len(via))
}
if code := req.Response.StatusCode; code != http.StatusTemporaryRedirect && code != http.StatusPermanentRedirect {
return fmt.Errorf("refusing redirect %d, which would drop the posted records", code)
}
from := via[0].URL
if req.URL.Host != from.Host || (from.Scheme == "https" && req.URL.Scheme != "https") {
return fmt.Errorf("refusing redirect from %s://%s to %s://%s", from.Scheme, from.Host, req.URL.Scheme, req.URL.Host)
}
return nil
}
// redactedEndpoint names an endpoint in errors and logs without what it may
// carry in its userinfo, query or fragment.
func redactedEndpoint(endpoint string) string {
u, err := url.Parse(endpoint)
if err != nil {
return "unparsable endpoint"
}
return (&url.URL{Scheme: u.Scheme, Host: u.Host, Path: u.Path}).String()
}
func (w *webhook) Send(ctx context.Context, records []*schema_pb.RecordValue) error {
if u, err := url.Parse(w.endpoint); err != nil {
return errors.New("unparsable endpoint")
} else if netguard.IsMetadataHost(u.Hostname()) {
return fmt.Errorf("endpoint %s targets the instance metadata service", u.Hostname())
}
// render everything before posting anything, so dropping an unrenderable
// record and sending the rest again does not repeat a body
var bodies [][]byte
unrenderable := &unrenderableError{}
renderRun := func(start, end int) {
if start == end {
return
}
if body, err := w.render(records[start:end]...); err == nil {
bodies = append(bodies, body)
return
}
for i := start; i < end; i++ {
body, err := w.render(records[i])
if err != nil {
unrenderable.indexes = append(unrenderable.indexes, i)
unrenderable.err = err
continue
}
bodies = append(bodies, body)
}
}
start := 0
for i, r := range records {
if IsTestEvent(r) {
renderRun(start, i)
renderRun(i, i+1)
start = i + 1
}
}
renderRun(start, len(records))
if len(unrenderable.indexes) > 0 {
return unrenderable
}
for _, body := range bodies {
if err := w.post(ctx, body); err != nil {
return err
}
}
return nil
}
// unrenderableError names the records of a batch that cannot be rendered, so
// sending them again cannot succeed.
type unrenderableError struct {
indexes []int // into the batch given to Send
err error
}
func (e *unrenderableError) Error() string {
return fmt.Sprintf("%d records cannot be rendered: %v", len(e.indexes), e.err)
}
func (e *unrenderableError) Unwrap() error { return e.err }
func (w *webhook) post(ctx context.Context, body []byte) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.endpoint, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("post to %s: invalid request", redactedEndpoint(w.endpoint))
}
req.Header.Set("Content-Type", "application/json")
if w.token != "" {
req.Header.Set("Authorization", "Bearer "+w.token)
}
resp, err := w.client.Do(req)
if err != nil {
var urlErr *url.Error
if errors.As(err, &urlErr) {
// the URL may carry credentials in its query; the cause is enough
return fmt.Errorf("post: %w", urlErr.Err)
}
return err
}
defer resp.Body.Close()
if resp.StatusCode/100 == 2 {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024))
return nil
}
detail, _ := io.ReadAll(io.LimitReader(resp.Body, webhookErrorBodyLimit))
return fmt.Errorf("endpoint answered %s: %s", resp.Status, bytes.TrimSpace(detail))
}
+279
View File
@@ -0,0 +1,279 @@
package s3notification
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/netguard"
)
// webhookServer records what reaches it and answers with status.
type webhookServer struct {
*httptest.Server
mu sync.Mutex
status int
bodies []string
auth []string
received int
}
func newWebhookServer(t *testing.T) *webhookServer {
t.Helper()
s := &webhookServer{status: http.StatusOK}
s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
s.mu.Lock()
s.received++
status := s.status
if status/100 == 2 {
s.bodies = append(s.bodies, string(body))
s.auth = append(s.auth, r.Header.Get("Authorization"))
}
s.mu.Unlock()
w.WriteHeader(status)
}))
t.Cleanup(s.Close)
return s
}
func (s *webhookServer) setStatus(status int) {
s.mu.Lock()
defer s.mu.Unlock()
s.status = status
}
func (s *webhookServer) delivered() []string {
s.mu.Lock()
defer s.mu.Unlock()
return append([]string(nil), s.bodies...)
}
func (s *webhookServer) attempts() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.received
}
func webhookTarget(endpoint string) *Target {
return &Target{Name: "hook", Type: TargetTypeWebhook, Enabled: true, Endpoint: endpoint, BearerToken: "secret"}
}
// namedRecord is a PUT of the object name, or, for a name starting with
// test-event, an s3:TestEvent with that request id.
func namedRecord(name string) *schema_pb.RecordValue {
if strings.HasPrefix(name, "test-event") {
return TestEventRecord("photos", name, 1)
}
return (&Event{Name: EventObjectCreatedPut, Bucket: "photos", Key: name, LogTsNs: 1}).RecordValue("rule")
}
// bodyNames is the object keys of a {"Records":[...]} body, or the request id
// of a test event.
func bodyNames(t *testing.T, body string) []string {
t.Helper()
var test TestEvent
if err := json.Unmarshal([]byte(body), &test); err == nil && test.Event == EventTest {
return []string{test.RequestID}
}
var batch Records
if err := json.Unmarshal([]byte(body), &batch); err != nil {
t.Fatalf("body %s: %v", body, err)
}
var names []string
for _, r := range batch.Records {
names = append(names, r.S3.Object.Key)
}
return names
}
// renderRefusing renders as Render does, but refuses a record named unrenderable.
func renderRefusing(records ...*schema_pb.RecordValue) ([]byte, error) {
for _, r := range records {
if r.Fields[ColumnObjectKey].GetStringValue() == "unrenderable" {
return nil, errors.New("unrenderable record")
}
}
return Render(records...)
}
func TestWebhookPostsATestEventOnItsOwnInOrder(t *testing.T) {
server := newWebhookServer(t)
hook := newWebhook(webhookTarget(server.URL))
err := hook.Send(context.Background(), []*schema_pb.RecordValue{
namedRecord("a"), namedRecord("test-event-1"), namedRecord("test-event-2"), namedRecord("b"), namedRecord("c"),
})
if err != nil {
t.Fatal(err)
}
var got []string
for _, body := range server.delivered() {
got = append(got, strings.Join(bodyNames(t, body), ","))
}
if want := "a|test-event-1|test-event-2|b,c"; strings.Join(got, "|") != want {
t.Fatalf("posted %v, want %s", got, want)
}
}
func TestWebhookPostsOneBodyPerBatch(t *testing.T) {
server := newWebhookServer(t)
server.setStatus(http.StatusNoContent)
hook := newWebhook(webhookTarget(server.URL + "/events"))
if err := hook.Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a"), namedRecord("b")}); err != nil {
t.Fatal(err)
}
bodies := server.delivered()
if len(bodies) != 1 {
t.Fatalf("%d posts, want 1", len(bodies))
}
if got := strings.Join(bodyNames(t, bodies[0]), ","); got != "a,b" {
t.Fatalf("body %s carries %s, want a,b", bodies[0], got)
}
server.mu.Lock()
defer server.mu.Unlock()
if server.auth[0] != "Bearer secret" {
t.Fatalf("authorization %q", server.auth[0])
}
}
func TestWebhookNamesTheRecordsItCannotRenderAndPostsNothing(t *testing.T) {
server := newWebhookServer(t)
hook := newWebhook(webhookTarget(server.URL))
hook.render = renderRefusing
err := hook.Send(context.Background(), []*schema_pb.RecordValue{
namedRecord("a"), namedRecord("test-event"), namedRecord("b"), namedRecord("unrenderable"), namedRecord("c"),
})
var unrenderable *unrenderableError
if !errors.As(err, &unrenderable) || fmt.Sprint(unrenderable.indexes) != "[3]" {
t.Fatalf("send with an unrenderable record: %v", err)
}
if n := server.attempts(); n != 0 {
t.Fatalf("%d posts before the batch was known to render", n)
}
}
func TestWebhookTreatsAnythingButTwoHundredsAsFailed(t *testing.T) {
server := newWebhookServer(t)
hook := newWebhook(webhookTarget(server.URL))
for _, status := range []int{http.StatusInternalServerError, http.StatusUnauthorized, http.StatusBadRequest} {
server.setStatus(status)
if err := hook.Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}); err == nil || !strings.Contains(err.Error(), http.StatusText(status)) {
t.Fatalf("status %d: %v", status, err)
}
}
}
func TestWebhookErrorsCarryNoEndpointSecrets(t *testing.T) {
original := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = original })
netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) {
return []net.IPAddr{{IP: net.ParseIP("169.254.10.1")}}, nil
}
for _, endpoint := range []string{
"http://user:hunter2@169.254.169.254/hook?token=sekrit",
"http://user:hunter2@rebound.example.com:8080/hook?token=sekrit",
"http://user:hunter2@[fe80::1]:8080/hook?token=sekrit#frag",
} {
err := newWebhook(webhookTarget(endpoint)).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a")})
if err == nil {
t.Fatalf("%s: sent", endpoint)
}
for _, secret := range []string{"hunter2", "sekrit", "user"} {
if strings.Contains(err.Error(), secret) {
t.Errorf("error %q carries %q", err, secret)
}
}
if !strings.Contains(err.Error(), "/hook") {
t.Errorf("error %q no longer names the endpoint", err)
}
}
}
func TestWebhookFollowsOnlyRedirectsThatKeepThePost(t *testing.T) {
for _, code := range []int{http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
var mu sync.Mutex
var landed []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/old" {
http.Redirect(w, r, "/new", code)
return
}
body, _ := io.ReadAll(r.Body)
mu.Lock()
landed = append(landed, r.Method+" "+string(body))
mu.Unlock()
}))
err := newWebhook(webhookTarget(server.URL+"/old")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a")})
server.Close()
mu.Lock()
got := strings.Join(landed, "|")
mu.Unlock()
if method, body, ok := strings.Cut(got, " "); ok && method == "POST" && strings.HasPrefix(body, "{") {
got = "POST " + strings.Join(bodyNames(t, body), ",")
}
if code == http.StatusTemporaryRedirect || code == http.StatusPermanentRedirect {
if err != nil || got != "POST a" {
t.Errorf("%d: %v, landed %q, want the POST resent", code, err, got)
}
continue
}
if err == nil || got != "" {
t.Errorf("%d: %v, landed %q, want a failure and nothing sent", code, err, got)
}
}
}
func TestWebhookFollowsOnlySameHostRedirects(t *testing.T) {
target := newWebhookServer(t)
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/moved" {
http.Redirect(w, r, "/here", http.StatusTemporaryRedirect)
return
}
if r.URL.Path == "/here" {
w.WriteHeader(http.StatusOK)
return
}
http.Redirect(w, r, target.URL+"/stolen", http.StatusTemporaryRedirect)
}))
t.Cleanup(redirector.Close)
if err := newWebhook(webhookTarget(redirector.URL+"/moved")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}); err != nil {
t.Fatalf("same-host redirect: %v", err)
}
err := newWebhook(webhookTarget(redirector.URL+"/elsewhere")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")})
if err == nil || !strings.Contains(err.Error(), "refusing redirect") {
t.Fatalf("cross-host redirect: %v", err)
}
if n := target.attempts(); n != 0 {
t.Fatalf("the other host got %d requests", n)
}
}
func TestWebhookRefusesMetadataAndLinkLocalAddresses(t *testing.T) {
original := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = original })
netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) {
return []net.IPAddr{{IP: net.ParseIP("169.254.10.1")}}, nil
}
for _, endpoint := range []string{
"http://169.254.169.254/latest",
"http://[fe80::1]:8080/",
"http://metadata.google.internal/",
"http://rebound.example.com/hook",
} {
err := newWebhook(webhookTarget(endpoint)).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")})
if err == nil || !(strings.Contains(err.Error(), "metadata") || strings.Contains(err.Error(), "link-local")) {
t.Errorf("%s: %v", endpoint, err)
}
}
}
+20 -160
View File
@@ -35,20 +35,9 @@ import (
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/util/netguard"
)
// lookupIPAddrFunc resolves a host to one or more IP addresses. It is a
// package-level variable so tests can substitute a deterministic resolver.
var lookupIPAddrFunc = net.DefaultResolver.LookupIPAddr
// blockedIMDSHosts lists hostnames that target cloud instance metadata
// services (IMDS). These are blocked regardless of how they happen to
// resolve, because some environments alias the IMDS address under a name.
var blockedIMDSHosts = map[string]struct{}{
"metadata.google.internal": {},
"metadata": {},
}
// validateRemoteEndpoint returns an error if the supplied S3 endpoint is not
// safe to dial from a server that has network access to cluster-internal
// hosts. It rejects empty/non-http(s) schemes, loopback/link-local/
@@ -72,7 +61,7 @@ func validateRemoteEndpoint(ctx context.Context, endpoint string) error {
return fmt.Errorf("remote endpoint %q has no host", endpoint)
}
lowerHost := strings.ToLower(host)
if _, ok := blockedIMDSHosts[lowerHost]; ok {
if netguard.IsMetadataHost(lowerHost) {
return fmt.Errorf("remote endpoint %q targets instance metadata service", endpoint)
}
if ip := net.ParseIP(host); ip != nil {
@@ -83,7 +72,7 @@ func validateRemoteEndpoint(ctx context.Context, endpoint string) error {
}
resolveCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
addrs, lookupErr := lookupIPAddrFunc(resolveCtx, host)
addrs, lookupErr := netguard.LookupIPAddr(resolveCtx, host)
if lookupErr != nil {
return fmt.Errorf("resolve remote endpoint host %q: %w", host, lookupErr)
}
@@ -95,57 +84,8 @@ func validateRemoteEndpoint(ctx context.Context, endpoint string) error {
return nil
}
// imdsIPv4 is the AWS/Azure/GCP IPv4 IMDS address. It is link-local and is
// already covered by IsLinkLocalUnicast, but is named explicitly so the
// error message is unambiguous in logs.
var imdsIPv4 = net.ParseIP("169.254.169.254")
// cgnatNet is the RFC 6598 carrier-grade NAT range (100.64.0.0/10). The
// stdlib's IsPrivate covers RFC 1918 but not CGNAT, so check it explicitly.
var cgnatNet = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
func checkBlockedIP(endpoint string, ip net.IP) error {
return checkBlockedIPPolicy(endpoint, ip, false)
}
// checkBlockedIPPolicy rejects addresses that must never be dialed from a
// server with cluster-internal reach. allowPrivate keeps RFC 1918 / CGNAT
// reachable for callers whose target legitimately sits on an internal network
// (peer volume servers), while still blocking loopback, link-local (IMDS) and
// unspecified.
func checkBlockedIPPolicy(endpoint string, ip net.IP, allowPrivate bool) error {
if ip == nil {
return nil
}
if ip.Equal(imdsIPv4) {
return fmt.Errorf("remote endpoint %q targets instance metadata service %s", endpoint, ip)
}
switch {
case ip.IsLoopback():
return fmt.Errorf("remote endpoint %q resolves to loopback address %s", endpoint, ip)
case ip.IsUnspecified():
return fmt.Errorf("remote endpoint %q resolves to unspecified address %s", endpoint, ip)
case ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast():
return fmt.Errorf("remote endpoint %q resolves to link-local address %s", endpoint, ip)
case ip.IsInterfaceLocalMulticast():
return fmt.Errorf("remote endpoint %q resolves to interface-local address %s", endpoint, ip)
}
if !allowPrivate {
switch {
case ip.IsPrivate():
return fmt.Errorf("remote endpoint %q resolves to private address %s", endpoint, ip)
case cgnatNet.Contains(ip):
return fmt.Errorf("remote endpoint %q resolves to CGNAT address %s", endpoint, ip)
}
}
// IPv6 transition addresses embed an IPv4 destination that routes to the
// same host wherever the matching relay exists (common in IPv6-only cloud).
// net.IP only normalizes ::ffff: mapped addresses, so pull the embedded
// IPv4 out of the other forms and re-check it against the deny list.
if embedded := embeddedTransitionIPv4(ip); embedded != nil {
return checkBlockedIPPolicy(endpoint, embedded, allowPrivate)
}
return nil
return netguard.CheckIP(endpoint, ip, netguard.Public)
}
// validateReplicaTarget rejects a peer volume server address that could
@@ -169,110 +109,31 @@ func validateReplicaTarget(ctx context.Context, target string) error {
if host == "" {
return fmt.Errorf("replica target %q has no host", target)
}
if _, ok := blockedIMDSHosts[strings.ToLower(host)]; ok {
if netguard.IsMetadataHost(host) {
return fmt.Errorf("replica target %q targets instance metadata service", target)
}
if ip := net.ParseIP(host); ip != nil {
return checkBlockedIPPolicy(target, ip, true)
return netguard.CheckIP(target, ip, netguard.Private)
}
resolveCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
addrs, lookupErr := lookupIPAddrFunc(resolveCtx, host)
addrs, lookupErr := netguard.LookupIPAddr(resolveCtx, host)
if lookupErr != nil {
return fmt.Errorf("resolve replica target host %q: %w", host, lookupErr)
}
for _, addr := range addrs {
if err := checkBlockedIPPolicy(target, addr.IP, true); err != nil {
if err := netguard.CheckIP(target, addr.IP, netguard.Private); err != nil {
return err
}
}
return nil
}
// embeddedTransitionIPv4 returns the IPv4 address carried by an IPv6 transition
// address -- NAT64 64:ff9b::/96 (RFC 6052), 6to4 2002::/16 (RFC 3056), Teredo
// 2001:0000::/32 (RFC 4380), and the deprecated IPv4-compatible ::/96 (RFC
// 4291) -- or nil when ip is not one of those. IPv4-mapped ::ffff:0:0/96 is
// excluded because net.IP already normalizes it via To4.
func embeddedTransitionIPv4(ip net.IP) net.IP {
v6 := ip.To16()
if v6 == nil || ip.To4() != nil {
return nil
}
switch {
case v6[0] == 0x00 && v6[1] == 0x64 && v6[2] == 0xff && v6[3] == 0x9b && allZero(v6[4:12]):
return net.IPv4(v6[12], v6[13], v6[14], v6[15])
case v6[0] == 0x20 && v6[1] == 0x02:
return net.IPv4(v6[2], v6[3], v6[4], v6[5])
case v6[0] == 0x20 && v6[1] == 0x01 && v6[2] == 0x00 && v6[3] == 0x00:
// Teredo obfuscates the client IPv4 as its ones' complement.
return net.IPv4(v6[12]^0xff, v6[13]^0xff, v6[14]^0xff, v6[15]^0xff)
case allZero(v6[:12]):
// IPv4-compatible ::a.b.c.d; :: and ::1 are already handled above.
return net.IPv4(v6[12], v6[13], v6[14], v6[15])
}
return nil
}
func allZero(b []byte) bool {
for _, c := range b {
if c != 0 {
return false
}
}
return true
}
// guardedDialer returns a DialContext that resolves the host itself and
// re-applies checkBlockedIP to every resolved address immediately before
// dialing. This closes the DNS-rebinding window between
// validateRemoteEndpoint and the actual TCP connect performed by the AWS S3
// client: even if the attacker's DNS flips to 127.0.0.1 (or any other
// blocked range) after the up-front check, the dial is refused.
// guardedDialer returns a DialContext that refuses, at connect time, every
// address checkBlockedIP rejects, closing the DNS-rebinding window between
// validateRemoteEndpoint and the TCP connect performed by the AWS S3 client.
func guardedDialer(endpoint string) func(ctx context.Context, network, addr string) (net.Conn, error) {
return guardedDialerPolicy(endpoint, false)
}
// guardedDialerPolicy is guardedDialer with the same allowPrivate knob as
// checkBlockedIPPolicy, so the replica upload path can keep dialing private
// peers while still refusing loopback / link-local / unspecified at connect
// time (closing the rebinding window for replica hostnames too).
func guardedDialerPolicy(endpoint string, allowPrivate bool) func(ctx context.Context, network, addr string) (net.Conn, error) {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, splitErr := net.SplitHostPort(addr)
if splitErr != nil {
return nil, splitErr
}
// If the host is already a literal IP just validate and dial it.
if ip := net.ParseIP(host); ip != nil {
if err := checkBlockedIPPolicy(endpoint, ip, allowPrivate); err != nil {
return nil, err
}
return util.OutboundDialContext(ctx, network, addr)
}
// Otherwise resolve, validate every answer, and dial the first IP
// that passes the deny list. Using a literal-IP target prevents the
// kernel resolver in net.Dialer from looking the name up a second
// time inside Dial and getting a different answer.
addrs, lookupErr := lookupIPAddrFunc(ctx, host)
if lookupErr != nil {
return nil, fmt.Errorf("resolve remote endpoint host %q: %w", host, lookupErr)
}
var firstBlockErr error
for _, a := range addrs {
if err := checkBlockedIPPolicy(endpoint, a.IP, allowPrivate); err != nil {
if firstBlockErr == nil {
firstBlockErr = err
}
continue
}
return util.OutboundDialContext(ctx, network, net.JoinHostPort(a.IP.String(), port))
}
if firstBlockErr != nil {
return nil, firstBlockErr
}
return nil, fmt.Errorf("resolve remote endpoint host %q: no addresses", host)
}
return netguard.DialContext(endpoint, netguard.Public)
}
// guardedGrpcDialOption returns a grpc.DialOption that re-applies the replica
@@ -283,7 +144,7 @@ func (vs *VolumeServer) guardedGrpcDialOption(endpoint string) grpc.DialOption {
if vs.AllowUntrustedRemoteEndpoints {
return nil
}
dial := guardedDialerPolicy(endpoint, true)
dial := netguard.DialContext(endpoint, netguard.Private)
return grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
return dial(ctx, "tcp", addr)
})
@@ -294,7 +155,7 @@ func (vs *VolumeServer) guardedGrpcDialOption(endpoint string) grpc.DialOption {
// one remote configuration (BuildGuardedRemoteStorageClient caches it per
// configuration); never share it across remote configs.
func newGuardedHTTPClient(endpoint string) *http.Client {
client := newGuardedHTTPClientPolicy(endpoint, false)
client := newGuardedHTTPClientPolicy(endpoint, netguard.Public)
if t, ok := client.Transport.(*http.Transport); ok {
tuneSharedTransport(t)
}
@@ -427,10 +288,9 @@ func awsSharedFile(env, name string) string {
return ""
}
// newGuardedHTTPClientPolicy is newGuardedHTTPClient with the allowPrivate knob
// for the replica upload path, whose targets are cluster peers on private
// networks.
func newGuardedHTTPClientPolicy(endpoint string, allowPrivate bool) *http.Client {
// newGuardedHTTPClientPolicy is newGuardedHTTPClient with an address policy,
// so the replica upload path can reach cluster peers on private networks.
func newGuardedHTTPClientPolicy(endpoint string, policy netguard.Policy) *http.Client {
return &http.Client{
Transport: &http.Transport{
// No proxy: guardedDialer must see the real target address. Through
@@ -439,7 +299,7 @@ func newGuardedHTTPClientPolicy(endpoint string, allowPrivate bool) *http.Client
// dialer exists to close. Operators that need a proxy can opt out
// with -volume.allowUntrustedRemoteEndpoints.
Proxy: nil,
DialContext: guardedDialerPolicy(endpoint, allowPrivate),
DialContext: netguard.DialContext(endpoint, policy),
ForceAttemptHTTP2: true,
MaxIdleConns: 16,
IdleConnTimeout: 60 * time.Second,
@@ -456,7 +316,7 @@ func newGuardedHTTPClientPolicy(endpoint string, allowPrivate bool) *http.Client
// data and auth headers to plaintext.
func newGuardedPeerHTTPClient(endpoint string) *http.Client {
globalClient := util_http.GetGlobalHttpClient()
client := newGuardedHTTPClientPolicy(endpoint, true)
client := newGuardedHTTPClientPolicy(endpoint, netguard.Private)
client.Transport.(*http.Transport).TLSClientConfig =
globalClient.GetClientTransport().TLSClientConfig
client.CheckRedirect = globalClient.Client.CheckRedirect
@@ -655,7 +515,7 @@ func validateRemoteEndpointForLoad(endpoint string) error {
if host == "" {
return fmt.Errorf("remote endpoint %q has no host", endpoint)
}
if _, ok := blockedIMDSHosts[strings.ToLower(host)]; ok {
if netguard.IsMetadataHost(host) {
return fmt.Errorf("remote endpoint %q targets instance metadata service", endpoint)
}
if ip := net.ParseIP(host); ip != nil {
+28 -27
View File
@@ -28,6 +28,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/remote_storage"
s3remote "github.com/seaweedfs/seaweedfs/weed/remote_storage/s3"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/util/netguard"
)
// stubLookup returns a resolver func that maps the supplied hostnames to
@@ -48,10 +49,10 @@ func stubLookup(t *testing.T, mapping map[string][]net.IP) func(ctx context.Cont
}
func TestValidateRemoteEndpoint(t *testing.T) {
originalLookup := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = originalLookup })
originalLookup := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = originalLookup })
lookupIPAddrFunc = stubLookup(t, map[string][]net.IP{
netguard.LookupIPAddr = stubLookup(t, map[string][]net.IP{
"s3.us-east-1.amazonaws.com": {net.ParseIP("52.216.10.10")},
"internal.example.com": {net.ParseIP("127.0.0.1")},
"linklocal.example.com": {net.ParseIP("169.254.10.20")},
@@ -269,11 +270,11 @@ func TestValidateRemoteEndpoint(t *testing.T) {
}
func TestValidateRemoteEndpointResolverFailure(t *testing.T) {
originalLookup := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = originalLookup })
originalLookup := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = originalLookup })
resolveErr := errors.New("simulated DNS failure")
lookupIPAddrFunc = func(_ context.Context, _ string) ([]net.IPAddr, error) {
netguard.LookupIPAddr = func(_ context.Context, _ string) ([]net.IPAddr, error) {
return nil, resolveErr
}
@@ -292,14 +293,14 @@ func TestValidateRemoteEndpointResolverFailure(t *testing.T) {
// dial time). The dial path must refuse the loopback answer instead of
// connecting to it.
func TestGuardedDialerRebind(t *testing.T) {
originalLookup := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = originalLookup })
originalLookup := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = originalLookup })
const host = "rebind.example.com"
endpoint := "https://" + host + "/"
var calls atomic.Int32
lookupIPAddrFunc = func(_ context.Context, name string) ([]net.IPAddr, error) {
netguard.LookupIPAddr = func(_ context.Context, name string) ([]net.IPAddr, error) {
if name != host {
return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true}
}
@@ -399,10 +400,10 @@ func TestRemoteEndpointGuardCoversAzure(t *testing.T) {
// host:port, since a scheme, path or query would move the upload to a different
// URL through the format string.
func TestValidateReplicaTarget(t *testing.T) {
originalLookup := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = originalLookup })
originalLookup := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = originalLookup })
lookupIPAddrFunc = stubLookup(t, map[string][]net.IP{
netguard.LookupIPAddr = stubLookup(t, map[string][]net.IP{
"peer.example.com": {net.ParseIP("10.0.0.7")},
"loop.example.com": {net.ParseIP("127.0.0.1")},
"linklocal.example.com": {net.ParseIP("169.254.169.254")},
@@ -497,9 +498,9 @@ func TestGuardedRemoteClientAzureBuildsGuardedClient(t *testing.T) {
// inline gcs credentials is the endpoint the guard validates, so a loopback
// token_uri is refused while the Google default passes.
func TestGuardedRemoteClientGuardsGcsTokenURL(t *testing.T) {
originalLookup := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = originalLookup })
lookupIPAddrFunc = stubLookup(t, map[string][]net.IP{
originalLookup := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = originalLookup })
netguard.LookupIPAddr = stubLookup(t, map[string][]net.IP{
"oauth2.googleapis.com": {net.ParseIP("142.250.72.10")},
})
@@ -568,9 +569,9 @@ func TestCheckGcsCredentials(t *testing.T) {
// TestGuardedDialerLiteralBlocked confirms that a literal blocked IP target
// is refused without any DNS lookup.
func TestGuardedDialerLiteralBlocked(t *testing.T) {
originalLookup := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = originalLookup })
lookupIPAddrFunc = func(_ context.Context, name string) ([]net.IPAddr, error) {
originalLookup := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = originalLookup })
netguard.LookupIPAddr = func(_ context.Context, name string) ([]net.IPAddr, error) {
t.Fatalf("resolver should not be called for IP literal target, got lookup of %q", name)
return nil, nil
}
@@ -588,14 +589,14 @@ func TestGuardedDialerLiteralBlocked(t *testing.T) {
// TestGuardedReplicaDialerRebind confirms the replica upload's dial-time guard
// refuses a hostname that rebinds to loopback after validateReplicaTarget, yet
// keeps letting private peers through (allowPrivate).
// keeps letting private peers through (netguard.Private).
func TestGuardedReplicaDialerRebind(t *testing.T) {
originalLookup := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = originalLookup })
originalLookup := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = originalLookup })
const host = "replica.example.com"
var calls atomic.Int32
lookupIPAddrFunc = func(_ context.Context, name string) ([]net.IPAddr, error) {
netguard.LookupIPAddr = func(_ context.Context, name string) ([]net.IPAddr, error) {
if name != host {
return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true}
}
@@ -610,7 +611,7 @@ func TestGuardedReplicaDialerRebind(t *testing.T) {
t.Fatalf("public replica target should validate, got %v", err)
}
// The dial then re-resolves to loopback and must refuse it.
dial := guardedDialerPolicy(host+":8080", true)
dial := netguard.DialContext(host+":8080", netguard.Private)
conn, err := dial(context.Background(), "tcp", host+":8080")
if conn != nil {
conn.Close()
@@ -624,7 +625,7 @@ func TestGuardedReplicaDialerRebind(t *testing.T) {
// fails on the already-cancelled context) rather than blocked as private.
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, perr := guardedDialerPolicy("10.0.0.5:80", true)(ctx, "tcp", "10.0.0.5:80"); perr != nil && strings.Contains(perr.Error(), "private") {
if _, perr := netguard.DialContext("10.0.0.5:80", netguard.Private)(ctx, "tcp", "10.0.0.5:80"); perr != nil && strings.Contains(perr.Error(), "private") {
t.Fatalf("private peer must be allowed by the replica dialer, got %v", perr)
}
}
@@ -998,11 +999,11 @@ func guardedCacheTest(t *testing.T, ips map[string][]net.IP) *atomic.Int64 {
t.Helper()
remote_storage.ResetRemoteStorageClients()
t.Cleanup(remote_storage.ResetRemoteStorageClients)
original := lookupIPAddrFunc
t.Cleanup(func() { lookupIPAddrFunc = original })
original := netguard.LookupIPAddr
t.Cleanup(func() { netguard.LookupIPAddr = original })
var lookups atomic.Int64
stub := stubLookup(t, ips)
lookupIPAddrFunc = func(ctx context.Context, host string) ([]net.IPAddr, error) {
netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) {
lookups.Add(1)
return stub(ctx, host)
}
+45
View File
@@ -930,6 +930,46 @@ var (
Buckets: prometheus.ExponentialBuckets(0.001, 2, 12),
})
S3NotificationDeliveredCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_delivered_records_total",
Help: "Bucket event records a forwarder delivered to its target.",
}, []string{"target"})
S3NotificationSendRetriesCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_send_retries_total",
Help: "Sends to a target that failed and are retried.",
}, []string{"target"})
S3NotificationRetentionGapCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_retention_gap_records_total",
Help: "Bucket event records retention removed from a target's topic before they were delivered.",
}, []string{"target"})
S3NotificationSkippedCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_skipped_records_total",
Help: "Bucket event records a forwarder skipped because they cannot be decoded or rendered.",
}, []string{"target", "reason"})
S3NotificationLagGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_lag_records",
Help: "Undelivered bucket event records the gateway forwarding a target can see: current ranges, ranges held back behind an older generation, and sealed retired ranges; an old range still being sealed after a repartition is not counted.",
}, []string{"target"})
S3BucketSizeBytesGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: Namespace,
@@ -1296,6 +1336,11 @@ func init() {
Gather.MustRegister(S3NotificationRecordsLateCounter)
Gather.MustRegister(S3NotificationQueueDepthGauge)
Gather.MustRegister(S3NotificationPublishWaitHistogram)
Gather.MustRegister(S3NotificationDeliveredCounter)
Gather.MustRegister(S3NotificationSendRetriesCounter)
Gather.MustRegister(S3NotificationRetentionGapCounter)
Gather.MustRegister(S3NotificationSkippedCounter)
Gather.MustRegister(S3NotificationLagGauge)
Gather.MustRegister(S3BucketSizeBytesGauge)
Gather.MustRegister(S3BucketPhysicalSizeBytesGauge)
Gather.MustRegister(S3BucketObjectCountGauge)
+176
View File
@@ -0,0 +1,176 @@
// Package netguard refuses outbound connections to addresses a server with
// cluster-internal reach must not be steered to, such as the cloud instance
// metadata service.
package netguard
import (
"context"
"fmt"
"net"
"strings"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// LookupIPAddr resolves a host to one or more IP addresses. It is a variable
// so tests can substitute a deterministic resolver.
var LookupIPAddr = net.DefaultResolver.LookupIPAddr
// Policy is which addresses besides public ones a connection may reach.
// Metadata-service, link-local, unspecified and interface-local addresses are
// refused under every policy.
type Policy int
const (
// Public allows only public addresses.
Public Policy = iota
// Private also allows RFC 1918 and CGNAT addresses, where cluster peers
// legitimately sit.
Private
// Local also allows loopback, for endpoints an operator configured, which
// may be a sidecar on the same host.
Local
)
// blockedIMDSHosts lists hostnames that target cloud instance metadata
// services (IMDS). These are blocked regardless of how they happen to
// resolve, because some environments alias the IMDS address under a name.
var blockedIMDSHosts = map[string]struct{}{
"metadata.google.internal": {},
"metadata": {},
}
// IsMetadataHost reports whether host names a cloud instance metadata service.
func IsMetadataHost(host string) bool {
_, ok := blockedIMDSHosts[strings.ToLower(host)]
return ok
}
// metadataIPs are instance metadata service addresses. 169.254.169.254 is
// link-local and already refused, but is named so the log is unambiguous.
// AWS's IPv6 fd00:ec2::254 is unique-local and Alibaba's 100.100.100.200 is in
// the CGNAT range, so the Private and Local policies would otherwise allow them.
var metadataIPs = []net.IP{
net.ParseIP("169.254.169.254"),
net.ParseIP("fd00:ec2::254"),
net.ParseIP("100.100.100.200"),
}
// cgnatNet is the RFC 6598 carrier-grade NAT range (100.64.0.0/10). The
// stdlib's IsPrivate covers RFC 1918 but not CGNAT, so check it explicitly.
var cgnatNet = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
// CheckIP rejects an address that policy does not let endpoint reach.
func CheckIP(endpoint string, ip net.IP, policy Policy) error {
if ip == nil {
return nil
}
for _, metadataIP := range metadataIPs {
if ip.Equal(metadataIP) {
return fmt.Errorf("remote endpoint %q targets instance metadata service %s", endpoint, ip)
}
}
switch {
case ip.IsLoopback() && policy != Local:
return fmt.Errorf("remote endpoint %q resolves to loopback address %s", endpoint, ip)
case ip.IsUnspecified():
return fmt.Errorf("remote endpoint %q resolves to unspecified address %s", endpoint, ip)
case ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast():
return fmt.Errorf("remote endpoint %q resolves to link-local address %s", endpoint, ip)
case ip.IsInterfaceLocalMulticast():
return fmt.Errorf("remote endpoint %q resolves to interface-local address %s", endpoint, ip)
}
if policy == Public {
switch {
case ip.IsPrivate():
return fmt.Errorf("remote endpoint %q resolves to private address %s", endpoint, ip)
case cgnatNet.Contains(ip):
return fmt.Errorf("remote endpoint %q resolves to CGNAT address %s", endpoint, ip)
}
}
// IPv6 transition addresses embed an IPv4 destination that routes to the
// same host wherever the matching relay exists (common in IPv6-only cloud).
// net.IP only normalizes ::ffff: mapped addresses, so pull the embedded
// IPv4 out of the other forms and re-check it against the deny list.
if embedded := embeddedTransitionIPv4(ip); embedded != nil {
return CheckIP(endpoint, embedded, policy)
}
return nil
}
// embeddedTransitionIPv4 returns the IPv4 address carried by an IPv6 transition
// address -- NAT64 64:ff9b::/96 (RFC 6052), 6to4 2002::/16 (RFC 3056), Teredo
// 2001:0000::/32 (RFC 4380), and the deprecated IPv4-compatible ::/96 (RFC
// 4291) -- or nil when ip is not one of those. IPv4-mapped ::ffff:0:0/96 is
// excluded because net.IP already normalizes it via To4.
func embeddedTransitionIPv4(ip net.IP) net.IP {
v6 := ip.To16()
if v6 == nil || ip.To4() != nil {
return nil
}
switch {
case v6[0] == 0x00 && v6[1] == 0x64 && v6[2] == 0xff && v6[3] == 0x9b && allZero(v6[4:12]):
return net.IPv4(v6[12], v6[13], v6[14], v6[15])
case v6[0] == 0x20 && v6[1] == 0x02:
return net.IPv4(v6[2], v6[3], v6[4], v6[5])
case v6[0] == 0x20 && v6[1] == 0x01 && v6[2] == 0x00 && v6[3] == 0x00:
// Teredo obfuscates the client IPv4 as its ones' complement.
return net.IPv4(v6[12]^0xff, v6[13]^0xff, v6[14]^0xff, v6[15]^0xff)
case allZero(v6[:12]):
// IPv4-compatible ::a.b.c.d; :: and ::1 are already handled above.
return net.IPv4(v6[12], v6[13], v6[14], v6[15])
}
return nil
}
func allZero(b []byte) bool {
for _, c := range b {
if c != 0 {
return false
}
}
return true
}
// DialContext returns a DialContext that resolves the host itself and applies
// CheckIP to every resolved address immediately before dialing. This closes
// the DNS-rebinding window between an up-front check of endpoint and the
// actual TCP connect: even if its DNS flips to a blocked address afterwards,
// the dial is refused.
func DialContext(endpoint string, policy Policy) func(ctx context.Context, network, addr string) (net.Conn, error) {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, splitErr := net.SplitHostPort(addr)
if splitErr != nil {
return nil, splitErr
}
// If the host is already a literal IP just validate and dial it.
if ip := net.ParseIP(host); ip != nil {
if err := CheckIP(endpoint, ip, policy); err != nil {
return nil, err
}
return util.OutboundDialContext(ctx, network, addr)
}
// Otherwise resolve, validate every answer, and dial the first IP
// that passes the deny list. Using a literal-IP target prevents the
// kernel resolver in net.Dialer from looking the name up a second
// time inside Dial and getting a different answer.
addrs, lookupErr := LookupIPAddr(ctx, host)
if lookupErr != nil {
return nil, fmt.Errorf("resolve remote endpoint host %q: %w", host, lookupErr)
}
var firstBlockErr error
for _, a := range addrs {
if err := CheckIP(endpoint, a.IP, policy); err != nil {
if firstBlockErr == nil {
firstBlockErr = err
}
continue
}
return util.OutboundDialContext(ctx, network, net.JoinHostPort(a.IP.String(), port))
}
if firstBlockErr != nil {
return nil, firstBlockErr
}
return nil, fmt.Errorf("resolve remote endpoint host %q: no addresses", host)
}
}
+36
View File
@@ -0,0 +1,36 @@
package netguard
import (
"net"
"testing"
)
func TestCheckIPByPolicy(t *testing.T) {
cases := []struct {
ip string
public, private, local bool
}{
{"8.8.8.8", true, true, true},
{"10.1.2.3", false, true, true},
{"100.64.0.1", false, true, true},
{"127.0.0.1", false, false, true},
{"::1", false, false, true},
{"169.254.169.254", false, false, false},
{"169.254.1.1", false, false, false},
{"fe80::1", false, false, false},
{"0.0.0.0", false, false, false},
{"64:ff9b::a9fe:a9fe", false, false, false},
{"fd00:ec2::254", false, false, false},
{"fd00::1", false, true, true},
{"100.100.100.200", false, false, false},
{"64:ff9b::6464:64c8", false, false, false},
}
for _, c := range cases {
ip := net.ParseIP(c.ip)
for policy, want := range map[Policy]bool{Public: c.public, Private: c.private, Local: c.local} {
if got := CheckIP("e", ip, policy) == nil; got != want {
t.Errorf("%s under policy %d: allowed %v, want %v", c.ip, policy, got, want)
}
}
}
}