s3: publish bucket events to each notification target's MQ topic (#13244)

* mq: report when a published message is acknowledged

Publish now returns a channel the publisher closes once the broker acks
that message, including an ack that arrives on a later stream after a
resend. A caller that has to know its message is stored, such as the S3
gateway answering a request only after its event is durable, can wait on
it with its own bound; callers that do not care ignore it.

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

* s3: build bucket event records in the AWS shape

An Event is what one operation did to one object; Record turns it into
an eventVersion 2.7 record for one rule, and Message wraps that record
in the Records envelope a consumer receives. The key is form-encoded per
path segment as AWS does it, size and eTag are left off removals, and
the sequencer is the filer's commit stamp as 16 hex digits, so one key's
sequencers compare as strings in commit order. The s3:TestEvent message
is built here too.

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

* s3: publish bucket event records to each target's MQ topic

The Publisher runs one worker per enabled target. The worker creates the
target's topic, s3.notify-<target> with 4 partitions and 7 days of
retention, then hands records to the MQ publisher keyed by bucket/key so
one object's events stay in one partition in order. Setup retries with
backoff, so a broker that is down or still taking the balancer lock after
a cold start delays records instead of losing them. A removed or
disabled target's worker stops; its topic is left for retention to age
out, since a forwarder may still be draining it.

Publish queues every record and waits up to 2 seconds, or until the
request ends, for all of them to be acked, and reports whether they
were. A record not acked by then stays queued and is still sent; the MQ
publisher resends it across leader changes. Each target's queue holds
10000 records; past that, and for records whose target has no worker, a
record is dropped. Acked, late and dropped records, the queue depth and
the wait are exported as metrics.

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

* s3api: start a bucket event publisher with the gateway

The gateway creates one event publisher and syncs it with the target
registry whenever the registry loads or changes, so each enabled target
gets its topic and worker. The publisher bootstraps from the broker the
command started beside the gateway, passed in as MqBroker once it bound,
and from every broker the masters list, so a gateway running without its
own broker still finds the cluster's. Broker connections use the
grpc.msg_broker TLS section. Shutdown stops the workers.

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

* s3api: send the test event before storing a notification configuration

Unless x-amz-skip-destination-validation is true, PUT notification
publishes an s3:TestEvent to the topic of every target the configuration
names, in parallel, and fails with InvalidArgument listing the
destinations whose topic did not ack it within the publisher's 2 second
wait. Nothing is stored in that case. The registry checks still run
with the header, and an empty configuration sends nothing.

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

* s3api: publish ObjectCreated events for PUT and POST

A PUT, including a "dir/" marker, publishes ObjectCreated:Put and a POST
upload ObjectCreated:Post, after the filer commit and before the
response, once per matching rule of the bucket's configuration, waiting
for the acks within the publisher's bound. A failed write publishes
nothing and a slow or absent broker never fails the request.

The sequencer is the filer's stamp of the commit. putToFiler records it,
from the routed ObjectTransaction or the lock path's CreateEntry, with
the committed size, into the request so the handler finds it; the marker
write and a create recovered after an ambiguous route return none, and
take the gateway's clock instead.

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

* s3api: publish ObjectCreated events for copy and multipart completion

CopyObject, including a metadata-only copy onto itself, publishes
ObjectCreated:Copy, and CompleteMultipartUpload publishes
ObjectCreated:CompleteMultipartUpload, both after the commit and before
the response; a copy that keeps the connection alive publishes before
its final answer.

The write wrappers these use dropped the transaction response, so they
now return the filer's commit stamp: routedMkFile, writeMultipartObject,
routedVersionedFinalize, routedMultipartFinalize, routedSelfCopy and
finalizeCopyDestination. Writes that go off the owner, through mkFile,
still return none and the event takes the gateway's clock.

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

* s3api: publish ObjectRemoved events for deletes

DeleteObject and DeleteObjects publish ObjectRemoved:DeleteMarkerCreated
when a delete without a version id leaves a marker in place of the key,
in a versioning-enabled or suspended bucket, and ObjectRemoved:Delete
for any other delete, including the delete of a marker by its version
id. The record carries the marker's or the deleted version's id.
DeleteObjects publishes one event per key it deleted and waits for all
of them at once.

The routed delete wrappers now return the filer's commit stamp:
routedDeleteSpecificVersion, routedDeleteNullVersion,
routedDemoteNullVersion and createDeleteMarker; deleteMutationResult
carries it to the handler. A suspended delete uses the stamp of the null
version's delete, since the marker write after it returns none. Deletes
on the lock path go through DeleteEntry, which has no stamp, and take
the gateway's clock.

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

* mq: report the ack of a published record too

PublishRecord now returns the same ack channel as Publish, so a caller
publishing to a topic with a record type can wait for its record to be
stored. Both go through doPublish, which registers the waiter for every
message.

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

* s3: carry bucket events as schematized records

A notification topic now has a record type, EventRecordType, the single
source for its flat snake_case columns: the event, requester, bucket and
object fields, the commit stamp as sequencer, and multipart columns for
later. event_time, event_name and bucket_name are required, the rest
optional, and changes to it are additive only. The topic is configured
with it, with bucket_name and object_key as key columns and the schema
format left empty as for the other schematized topics, and records go
out through PublishRecord.

The record holds raw values: the object key unencoded, the sequencer as
an int64, and nulls where a value is absent, such as size and eTag on
removals. Render turns records into the AWS JSON a destination receives,
the Records envelope with eventVersion 2.7, a form-encoded key and a hex
sequencer, or the test event message for an s3:TestEvent, so forwarders
produce exactly the body the gateway used to publish.

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

* s3: shut a stopped target's publisher down even while it is blocked

With the broker away long enough to fill a partition's unacked buffer,
the worker blocks inside PublishRecord. Removing, disabling or closing
the target only cancelled the worker's context, which the blocked worker
never looked at, so the publisher and its queued records lived on and
resumed sending once the broker came back. Stopping a target now shuts
its MQ publisher down directly, which releases the blocked publish, and
does it in the background so Sync and Close do not wait for the flush. A
publisher that finishes setting up after the stop is shut down at once,
and a worker that dequeues a record after the stop drops it.

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

* s3api: publish nothing for a retried multipart completion

A CompleteMultipartUpload retried after the object committed is answered
from that commit and writes nothing, yet the handler still published an
ObjectCreated:CompleteMultipartUpload, with size 0 since no commit was
noted. AWS sends the event once, for the completion that created the
object, so the handler now publishes only when the request itself
committed.

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

* s3api: take an event's principal from the authenticated identity only

With auth off, the gateway keeps the s3-account-id header the client
sent, and an event's principal_id fell back to it, so any client could
name itself as the requester in the record a destination trusts. The
principal is now the identity name authentication put in the request
context, or anonymous.

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

* s3api: turn notifications off instead of exiting on a bad broker TLS config

The event publisher loaded the grpc.msg_broker client TLS with
LoadClientTLS, which exits the process on a config it cannot use, such
as a cert without its key, so a broker-only TLS mistake took the S3
gateway down even with no notification targets. It now loads it with
TryLoadClientTLS and, on an error, logs it and runs without a
publisher: object writes publish nothing and a notification
configuration's test event fails. It never falls back to an insecure
connection.

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

* s3: count a record dropped while its request waits only as dropped

A record dropped while a request waited for it, by a PublishRecord error
or its target being stopped, was counted dropped where it was dropped,
and then late when the request's wait ran out, which it also sat
through in full. Each queued record now carries a done signal that both
its ack and its drop close, so the wait ends as soon as the record's
fate is known and the drop is not counted again as late. Late still
counts a record that was neither acked nor dropped when the request
answered.

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

* mq: let a caller cancel starting a topic publisher

NewTopicPublisher returned only once a partition lookup succeeded, and
retried the lookup for as long as the broker refused it, with nothing a
caller could stop it with. It now takes a context that bounds the start:
the topic configuration runs under it, and cancelling it stops the
lookup loop and returns an error. A publisher already returned is not
affected. Existing callers pass context.Background().

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

* s3: stop a removed target's publisher that is still starting

A target's MQ publisher was started without the worker's context, so a
target removed while its partitions had no leader kept its publisher
looking them up, and its worker waiting, until a lookup succeeded. The
worker's context now bounds the start, so removing or disabling the
target ends both.

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

* s3: bound each broker's ConfigureTopic during a target's setup

Setup asked each broker in turn to configure the target's topic with
the worker's context alone, so a broker that accepted the call and never
answered held the worker there for good. Each broker now gets 10
seconds before setup moves on to the next, and a stopped worker does not
ask the rest.

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

* s3api: stamp a suspended delete's event with its marker write

A suspended-bucket delete removes the null version, then writes the null
delete marker and points latest at it. Its DeleteMarkerCreated event
took the stamp of the first step, so a write landing between the steps
got a later sequencer although the marker it lost to is what remained.
The event now takes the stamp of the pointer write, the delete's last
commit.

To get it, MkFile, the gateway's mkFile and
updateLatestVersionInDirectory return the CreateEntry stamp, and
createNullDeleteMarker returns it. createDeleteMarker's unrouted path
and writeMultipartObject off the owner now return their write's stamp
too instead of none.

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

* mq: bound each broker's ConfigureTopic when a publisher starts

NewTopicPublisher configures the topic again before its lookups, with
no deadline per broker, so a broker that accepted the call and hung
held the start until the caller gave up, even with a healthy broker
next in the list. Each broker now gets 10s before the next is tried.

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

* s3api: sequence a key's events only with stamps from its owner filer

The previous change stamped a suspended delete's DeleteMarkerCreated
with the null marker's pointer write, but that write goes to the
gateway's default filer, not the key's owner. Filer clocks differ, so a
delete could get a smaller sequencer than the PUT before it, and a
consumer deduplicating on the sequencer would drop it as stale.

Routing the marker write to the owner would move the suspended delete
onto the transaction path, a change to the write itself. Until then the
event goes back to the stamp of the null version's routed delete on the
owner, and gateway clock when the delete is not routed. The same
reasoning applies to the other stamps that change began returning from
off-owner writes, a delete marker or a multipart object written through
mkFile, so those return none again, and MkFile, mkFile and
updateLatestVersionInDirectory go back to returning only an error.

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

* s3: count each queued record once as acked or dropped, and late apart

A drop counted the record as dropped and then closed its done channel,
so a request whose wait ran out between the two still saw it pending and
counted it late in the same counter. Each queued record now has a
terminal outcome, acked or dropped, set once by compare-and-swap, and
notification_records_total counts that outcome alone, so every lost
record shows as dropped exactly once.

Late moves to its own counter, notification_records_late_total, counted
once per record when its request stops waiting on it before it is acked
or dropped; that record is still counted acked or dropped when it
settles.

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

* s3api: publish the event of a completion recovered after its commit

When a finalize committed but returned an error, completeMultipartUpload
answered from committedCompletion without noting the commit, so the handler
published no ObjectCreated:CompleteMultipartUpload. A retry is answered as
a replay and publishes nothing either, so the event was lost although the
object exists. The recovery now notes the commit when the stored object
holds this attempt's parts, stamped by the gateway clock as the filer's
stamp is not known. One answered from another attempt's commit stays
silent.

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

* s3api: sequence a recovered completion's event with its entry's commit stamp

A completion whose finalize committed but returned an error is answered
from the stored object, and its event took the gateway clock. The stored
entry carries CommitTsNs, the meta log stamp the committing filer gave
the write, from the same sequence as the stamps the routed write paths
return, and peers that replicate the entry keep it. The event now takes
that stamp, and falls back to the gateway clock only for an entry
written by a filer that predates it.

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 19:53:18 -08:00
1 parent 2cde975c25
commit 3f2f625822
37 files changed
+3116 -171

No files matched your search

+2 -2
View File
@@ -379,7 +379,7 @@ func createTopicData(masterAddr, filerAddr, namespace, topicName string,
}
// Create publisher
publisher, err := pub_client.NewTopicPublisher(config)
publisher, err := pub_client.NewTopicPublisher(context.Background(), config)
if err != nil {
return fmt.Errorf("failed to create publisher: %v", err)
}
@@ -397,7 +397,7 @@ func createTopicData(masterAddr, filerAddr, namespace, topicName string,
}
// Publish structured record
err = publisher.PublishRecord([]byte(fmt.Sprintf("key-%d", i)), recordValue)
_, err = publisher.PublishRecord([]byte(fmt.Sprintf("key-%d", i)), recordValue)
if err != nil {
log.Printf("Error publishing message %d: %v", i+1, err)
continue
+9
View File
@@ -139,6 +139,15 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) listenQueueServer() (grpcL, localL
return grpcL, localL, nil
}
// boundAddress is the address the broker registers with the master, or empty
// when it is not running.
func (mqBrokerOpt *MessageQueueBrokerOptions) boundAddress() pb.ServerAddress {
if mqBrokerOpt == nil || !mqBrokerOpt.bound.Load() {
return ""
}
return pb.ServerAddress(util.JoinHostPort(*mqBrokerOpt.ip, *mqBrokerOpt.port))
}
func (mqBrokerOpt *MessageQueueBrokerOptions) serveQueueServer(grpcL, localL net.Listener) error {
qs, err := broker.NewMessageBroker(&broker.MessageQueueBrokerOption{
Masters: mqBrokerOpt.masters,
+1
View File
@@ -492,6 +492,7 @@ func (s3opt *S3Options) startS3Server() bool {
AllowBackslashInKey: *s3opt.allowBackslashInKey,
LancePort: s3opt.lancePort(),
S3Endpoint: s3opt.s3Endpoint(),
MqBroker: s3opt.mqBroker.boundAddress(),
IamSelfServiceRequiresGrant: *s3opt.iamSelfServiceRequiresGrant,
RoutedLookupTimeout: *s3opt.routedLookupTimeout,
UnreachableOwnerTTL: *s3opt.unreachableOwnerTTL,
+6
View File
@@ -143,6 +143,9 @@ func TestS3GatewaySurvivesBrokerThatFailsToStart(t *testing.T) {
if b.bound.Load() {
t.Error("broker on an occupied port reported bound")
}
if address := b.boundAddress(); address != "" {
t.Errorf("broker on an occupied port has address %q", address)
}
if !waitMiniClientsDrained(t, 5*time.Second) {
t.Fatal("broker on an occupied port did not return")
}
@@ -175,6 +178,9 @@ func TestS3GatewayBrokerStopsWithGateway(t *testing.T) {
if !b.bound.Load() {
t.Fatal("broker not bound once startMqBroker returned")
}
if want := pb.ServerAddress(util.JoinHostPort(*b.ip, *b.port)); b.boundAddress() != want {
t.Fatalf("bound address %q, want %q", b.boundAddress(), want)
}
if waitMiniClientsDrained(t, 300*time.Millisecond) {
t.Fatal("broker returned before the gateway shut down")
}
+1 -1
View File
@@ -14,7 +14,7 @@ import (
func (a *MessageQueueAgent) StartPublishSession(ctx context.Context, req *mq_agent_pb.StartPublishSessionRequest) (*mq_agent_pb.StartPublishSessionResponse, error) {
sessionId := rand.Int64()
topicPublisher, err := pub_client.NewTopicPublisher(
topicPublisher, err := pub_client.NewTopicPublisher(context.Background(),
&pub_client.PublisherConfiguration{
Topic: topic.NewTopic(req.Topic.Namespace, req.Topic.Name),
PartitionCount: req.PartitionCount,
+2 -2
View File
@@ -29,7 +29,7 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
}()
if m.Value != nil {
if err := publisherEntry.entry.PublishRecord(m.Key, m.Value); err != nil {
if _, err := publisherEntry.entry.PublishRecord(m.Key, m.Value); err != nil {
return err
}
}
@@ -45,7 +45,7 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
if m.Value == nil {
continue
}
if err := publisherEntry.entry.PublishRecord(m.Key, m.Value); err != nil {
if _, err := publisherEntry.entry.PublishRecord(m.Key, m.Value); err != nil {
return err
}
}
+17 -12
View File
@@ -16,15 +16,18 @@ import (
var errPublisherClosed = errors.New("publisher is closed")
func (p *TopicPublisher) Publish(key, value []byte) error {
// Publish queues the message and returns a channel closed once the broker acks
// it. A message still unacked when the publisher shuts down never closes it.
func (p *TopicPublisher) Publish(key, value []byte) (acked <-chan struct{}, err error) {
if p.config.RecordType != nil {
return fmt.Errorf("record type is set, use PublishRecord instead")
return nil, fmt.Errorf("record type is set, use PublishRecord instead")
}
return p.doPublish(key, value)
}
// doPublish blocks while the partition already holds maxBufferedMessages queued or unacked messages.
func (p *TopicPublisher) doPublish(key, value []byte) error {
// The returned channel is closed once the broker acks the message.
func (p *TopicPublisher) doPublish(key, value []byte) (<-chan struct{}, error) {
hashKey := util.HashToInt32(key) % pub_balancer.MaxPartitionCount
if hashKey < 0 {
hashKey = -hashKey
@@ -33,32 +36,35 @@ func (p *TopicPublisher) doPublish(key, value []byte) error {
job, found := p.partition2Buffer.Floor(hashKey+1, hashKey+1)
p.Unlock()
if !found {
return fmt.Errorf("no input buffer found for key %d", hashKey)
return nil, fmt.Errorf("no input buffer found for key %d", hashKey)
}
select {
case job.slots <- struct{}{}:
case <-p.inputDone:
return errPublisherClosed
return nil, errPublisherClosed
}
p.inputLock.RLock()
defer p.inputLock.RUnlock()
if p.inputClosed {
<-job.slots
return errPublisherClosed
return nil, errPublisherClosed
}
// the in-flight list matches acks by TsNs, so a partition's queue must be in TsNs order
job.enqueueLock.Lock()
job.accepted.Add(1)
job.inputQueue <- &mq_pb.DataMessage{
data := &mq_pb.DataMessage{
// The caller may reuse its buffers while this message awaits a retry.
Key: bytes.Clone(key),
Value: bytes.Clone(value),
TsNs: p.nextTsNs(),
}
acked := make(chan struct{})
job.addWaiter(data.TsNs, acked)
job.inputQueue <- data
job.enqueueLock.Unlock()
return nil
return acked, nil
}
func (p *TopicPublisher) nextTsNs() int64 {
@@ -74,13 +80,12 @@ func (p *TopicPublisher) nextTsNs() int64 {
}
}
func (p *TopicPublisher) PublishRecord(key []byte, recordValue *schema_pb.RecordValue) error {
// serialize record value
// PublishRecord is Publish for a topic with a record type.
func (p *TopicPublisher) PublishRecord(key []byte, recordValue *schema_pb.RecordValue) (acked <-chan struct{}, err error) {
value, err := proto.Marshal(recordValue)
if err != nil {
return fmt.Errorf("failed to marshal record value: %w", err)
return nil, fmt.Errorf("failed to marshal record value: %w", err)
}
return p.doPublish(key, value)
}
+19 -8
View File
@@ -1,6 +1,7 @@
package pub_client
import (
"context"
"fmt"
"sync"
"time"
@@ -15,6 +16,9 @@ import (
// how long FinishPublish or Shutdown keeps resending before giving up on unacked messages
var flushTimeout = time.Minute
// how long one broker's ConfigureTopic may take before the next broker is tried
var configureTopicTimeout = 10 * time.Second
type PublisherConfiguration struct {
Topic topic.Topic
PartitionCount int32
@@ -41,7 +45,10 @@ type TopicPublisher struct {
schedulerDone chan struct{}
}
func NewTopicPublisher(config *PublisherConfiguration) (tp *TopicPublisher, err error) {
// NewTopicPublisher configures the topic and returns once its partitions are
// looked up. ctx bounds only that start: cancelling it stops the lookups and
// returns an error; it has no effect on a publisher already returned.
func NewTopicPublisher(ctx context.Context, config *PublisherConfiguration) (tp *TopicPublisher, err error) {
grpcDialOption := config.GrpcDialOption
if grpcDialOption == nil {
grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
@@ -58,16 +65,20 @@ func NewTopicPublisher(config *PublisherConfiguration) (tp *TopicPublisher, err
schedulerDone: make(chan struct{}),
}
if err = tp.doConfigureTopic(); err != nil {
if err = tp.doConfigureTopic(ctx); err != nil {
return nil, fmt.Errorf("configure topic %s: %w", config.Topic, err)
}
wg := sync.WaitGroup{}
wg.Add(1)
go tp.startSchedulerThread(&wg)
wg.Wait()
return
ready := make(chan struct{})
go tp.startSchedulerThread(ready)
select {
case <-ready:
return tp, nil
case <-ctx.Done():
tp.stop()
<-tp.schedulerDone
return nil, fmt.Errorf("start publisher for %s: %w", config.Topic, ctx.Err())
}
}
// Shutdown stops accepting messages and returns once every queued message is acked,
+155 -11
View File
@@ -2,6 +2,7 @@ package pub_client
import (
"context"
"errors"
"fmt"
"io"
"net"
@@ -37,6 +38,10 @@ type fakeBroker struct {
receivedData chan *mq_pb.DataMessage
// stallLookup, when set, holds lookup n (0-based) until the caller gives up.
stallLookup func(n int) bool
// failLookups, when set, refuses every lookup at once.
failLookups bool
// stallConfigure, when set, holds ConfigureTopic until the caller gives up.
stallConfigure bool
mu sync.Mutex
lookups int
@@ -62,6 +67,10 @@ func startFakeBroker(t *testing.T, fb *fakeBroker) *fakeBroker {
}
func (fb *fakeBroker) ConfigureTopic(ctx context.Context, req *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
if fb.stallConfigure {
<-ctx.Done()
return nil, ctx.Err()
}
return &mq_pb.ConfigureTopicResponse{}, nil
}
@@ -74,6 +83,9 @@ func (fb *fakeBroker) LookupTopicBrokers(ctx context.Context, req *mq_pb.LookupT
<-ctx.Done()
return nil, ctx.Err()
}
if fb.failLookups {
return nil, status.Error(codes.Unavailable, "no balancer")
}
return &mq_pb.LookupTopicBrokersResponse{
Topic: req.Topic,
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
@@ -190,7 +202,7 @@ func (fb *fakeBroker) storedKeys() map[string]int {
func newTestPublisher(t *testing.T, fb *fakeBroker) *TopicPublisher {
t.Helper()
publisher, err := NewTopicPublisher(&PublisherConfiguration{
publisher, err := NewTopicPublisher(t.Context(), &PublisherConfiguration{
Topic: topic.NewTopic("test", t.Name()),
PartitionCount: 1,
Brokers: []string{fb.addr},
@@ -228,7 +240,7 @@ func TestPublisherLooksUpAgainAfterStreamFailure(t *testing.T) {
})
publisher := newTestPublisher(t, fb)
if err := publisher.Publish([]byte(testKey(0)), []byte("v")); err != nil {
if _, err := publisher.Publish([]byte(testKey(0)), []byte("v")); err != nil {
t.Fatalf("publish: %v", err)
}
waitFor(t, "a second lookup and stream", func() bool {
@@ -257,7 +269,7 @@ func TestPublisherResendsOriginalBytesAfterCallerReusesBuffers(t *testing.T) {
defer allowReconnect()
key, value := []byte("key"), []byte("value")
if err := publisher.Publish(key, value); err != nil {
if _, err := publisher.Publish(key, value); err != nil {
t.Fatal(err)
}
select {
@@ -291,7 +303,7 @@ func TestPublisherResendsUnackedInOrder(t *testing.T) {
publisher := newTestPublisher(t, fb)
for i := 0; i < total; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
if _, err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
@@ -326,13 +338,14 @@ func TestPublishBlocksWhenBufferIsFull(t *testing.T) {
publisher := newTestPublisher(t, fb)
for i := 0; i < maxBufferedMessages; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
if _, err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
published := make(chan error, 1)
go func() {
published <- publisher.Publish([]byte(testKey(maxBufferedMessages)), []byte("v"))
_, err := publisher.Publish([]byte(testKey(maxBufferedMessages)), []byte("v"))
published <- err
}()
select {
case err := <-published:
@@ -365,7 +378,7 @@ func TestShutdownFlushesQueuedMessages(t *testing.T) {
publisher := newTestPublisher(t, fb)
for i := 0; i < total; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
if _, err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
@@ -389,7 +402,7 @@ func TestShutdownFlushesQueuedMessages(t *testing.T) {
t.Fatal("close marker was not delivered")
}
if err := publisher.Publish([]byte("late"), []byte("v")); err == nil {
if _, err := publisher.Publish([]byte("late"), []byte("v")); err == nil {
t.Fatal("publish after Shutdown should fail")
}
}
@@ -405,7 +418,7 @@ func TestShutdownGivesUpAfterFlushTimeout(t *testing.T) {
publisher := newTestPublisher(t, fb)
for i := 0; i < 5; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
if _, err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
@@ -431,7 +444,7 @@ func TestShutdownCancelsAStalledLookup(t *testing.T) {
stallLookup: func(n int) bool { return n > 0 },
})
publisher := newTestPublisher(t, fb)
if err := publisher.Publish([]byte(testKey(0)), []byte("v")); err != nil {
if _, err := publisher.Publish([]byte(testKey(0)), []byte("v")); err != nil {
t.Fatalf("publish: %v", err)
}
waitFor(t, "a second lookup", func() bool {
@@ -487,7 +500,7 @@ func TestBootstrapUsesPublisherCredentials(t *testing.T) {
}
var err error
if rpc == "configure" {
err = p.doConfigureTopic()
err = p.doConfigureTopic(t.Context())
} else {
_, err = p.doLookupTopicPartitions(t.Context())
}
@@ -498,3 +511,134 @@ func TestBootstrapUsesPublisherCredentials(t *testing.T) {
})
}
}
func TestNewTopicPublisherStopsWhenItsContextEnds(t *testing.T) {
fb := startFakeBroker(t, &fakeBroker{failLookups: true})
ctx, cancel := context.WithCancel(context.Background())
result := make(chan error, 1)
go func() {
_, err := NewTopicPublisher(ctx, &PublisherConfiguration{
Topic: topic.NewTopic("test", t.Name()),
PartitionCount: 1,
Brokers: []string{fb.addr},
PublisherName: "test",
})
result <- err
}()
waitFor(t, "lookups to be retried", func() bool { lookups, _ := fb.counts(); return lookups >= 2 })
cancel()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("NewTopicPublisher = %v, want context.Canceled", err)
}
case <-time.After(10 * time.Second):
t.Fatal("NewTopicPublisher kept waiting for its partitions after its context ended")
}
lookups, _ := fb.counts()
time.Sleep(lookupMaxBackoff + time.Second)
if after, _ := fb.counts(); after != lookups {
t.Fatalf("lookups went on after the start was cancelled: %d then %d", lookups, after)
}
}
func TestNewTopicPublisherMovesPastABrokerThatHangsOnConfigure(t *testing.T) {
saved := configureTopicTimeout
configureTopicTimeout = 100 * time.Millisecond
t.Cleanup(func() { configureTopicTimeout = saved })
hung := startFakeBroker(t, &fakeBroker{stallConfigure: true})
healthy := startFakeBroker(t, &fakeBroker{})
result := make(chan error, 1)
go func() {
publisher, err := NewTopicPublisher(context.Background(), &PublisherConfiguration{
Topic: topic.NewTopic("test", t.Name()),
PartitionCount: 1,
Brokers: []string{hung.addr, healthy.addr},
PublisherName: "test",
})
if err == nil {
publisher.closeInput(nil)
publisher.stop()
<-publisher.schedulerDone
}
result <- err
}()
select {
case err := <-result:
if err != nil {
t.Fatalf("NewTopicPublisher = %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("NewTopicPublisher kept waiting on a broker that does not answer ConfigureTopic")
}
}
func TestPublishRecordReportsItsAck(t *testing.T) {
gate := make(chan struct{})
fb := startFakeBroker(t, &fakeBroker{ackGate: gate})
recordType := &schema_pb.RecordType{Fields: []*schema_pb.Field{{Name: "name", Type: &schema_pb.Type{Kind: &schema_pb.Type_ScalarType{ScalarType: schema_pb.ScalarType_STRING}}}}}
publisher, err := NewTopicPublisher(t.Context(), &PublisherConfiguration{
Topic: topic.NewTopic("test", t.Name()),
PartitionCount: 1,
Brokers: []string{fb.addr},
PublisherName: "test",
RecordType: recordType,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
publisher.closeInput(nil)
publisher.stop()
<-publisher.schedulerDone
})
acked, err := publisher.PublishRecord([]byte("key"), &schema_pb.RecordValue{Fields: map[string]*schema_pb.Value{
"name": {Kind: &schema_pb.Value_StringValue{StringValue: "v"}},
}})
if err != nil {
t.Fatal(err)
}
select {
case <-acked:
t.Fatal("ack reported before the broker acked")
case <-time.After(100 * time.Millisecond):
}
close(gate)
select {
case <-acked:
case <-time.After(10 * time.Second):
t.Fatal("ack of the record not reported")
}
}
func TestPublishReportsTheAckOfEachMessage(t *testing.T) {
gate := make(chan struct{})
fb := startFakeBroker(t, &fakeBroker{
ackGate: gate,
// the first stream takes the message without acking it, then dies
breakStream: func(n int) (int, int, bool) { return 1, 0, n == 0 },
})
publisher := newTestPublisher(t, fb)
acked, err := publisher.Publish([]byte("key"), []byte("v"))
if err != nil {
t.Fatal(err)
}
waitFor(t, "a second stream", func() bool { _, streams := fb.counts(); return streams >= 2 })
select {
case <-acked:
t.Fatal("ack reported before the broker acked")
case <-time.After(100 * time.Millisecond):
}
close(gate)
select {
case <-acked:
case <-time.After(10 * time.Second):
t.Fatal("ack of the resent message not reported")
}
if got := fb.storedKeys()["key"]; got != 1 {
t.Fatalf("stored %d copies, want 1", got)
}
}
+27 -8
View File
@@ -31,7 +31,8 @@ type EachPartitionPublishJob struct {
accepted atomic.Int64 // data messages enqueued and not yet acked
inflightLock sync.Mutex
inflight []*mq_pb.DataMessage // sent but not acked, in send order
inflight []*mq_pb.DataMessage // sent but not acked, in send order
waiters map[int64]chan struct{} // by TsNs, closed on ack
inputDrained bool
// guarded by TopicPublisher.Mutex
@@ -41,7 +42,7 @@ type EachPartitionPublishJob struct {
wg sync.WaitGroup
}
func (p *TopicPublisher) startSchedulerThread(wg *sync.WaitGroup) {
func (p *TopicPublisher) startSchedulerThread(ready chan struct{}) {
defer close(p.schedulerDone)
glog.V(0).Infof("start scheduler thread for topic %s", p.config.Topic)
@@ -56,7 +57,7 @@ func (p *TopicPublisher) startSchedulerThread(wg *sync.WaitGroup) {
}
}()
ready := false
isReady := false
var backoff time.Duration
for {
if backoff > 0 {
@@ -75,9 +76,9 @@ func (p *TopicPublisher) startSchedulerThread(wg *sync.WaitGroup) {
continue
}
p.onEachAssignments(assignments)
if !ready {
ready = true
wg.Done()
if !isReady {
isReady = true
close(ready)
}
// wait until a partition needs a new leader
@@ -339,6 +340,15 @@ func (job *EachPartitionPublishJob) addInflight(data *mq_pb.DataMessage) {
job.inflightLock.Unlock()
}
func (job *EachPartitionPublishJob) addWaiter(tsNs int64, acked chan struct{}) {
job.inflightLock.Lock()
if job.waiters == nil {
job.waiters = make(map[int64]chan struct{})
}
job.waiters[tsNs] = acked
job.inflightLock.Unlock()
}
func (job *EachPartitionPublishJob) unacked() []*mq_pb.DataMessage {
job.inflightLock.Lock()
defer job.inflightLock.Unlock()
@@ -354,6 +364,10 @@ func (job *EachPartitionPublishJob) ack(tsNs int64) bool {
if job.inflight[n].Ctrl == nil {
<-job.slots
job.accepted.Add(-1)
if waiter, ok := job.waiters[job.inflight[n].TsNs]; ok {
close(waiter)
delete(job.waiters, job.inflight[n].TsNs)
}
}
job.inflight[n] = nil
n++
@@ -381,19 +395,24 @@ func (job *EachPartitionPublishJob) unackedCount() int {
return int(job.accepted.Load())
}
func (p *TopicPublisher) doConfigureTopic() (err error) {
func (p *TopicPublisher) doConfigureTopic(ctx context.Context) (err error) {
if len(p.config.Brokers) == 0 {
return fmt.Errorf("topic configuring found no bootstrap brokers")
}
var lastErr error
for _, brokerAddress := range p.config.Brokers {
if ctx.Err() != nil {
return ctx.Err()
}
// The configured dial option belongs to this publisher. A process-wide
// address cache can reuse a connection opened with different credentials.
err = pb.WithBrokerGrpcClient(true,
brokerAddress,
p.grpcDialOption,
func(client mq_pb.SeaweedMessagingClient) error {
_, err := client.ConfigureTopic(context.Background(), &mq_pb.ConfigureTopicRequest{
callCtx, cancel := context.WithTimeout(ctx, configureTopicTimeout)
defer cancel()
_, err := client.ConfigureTopic(callCtx, &mq_pb.ConfigureTopicRequest{
Topic: p.config.Topic.ToPbTopic(),
PartitionCount: p.config.PartitionCount,
MessageRecordType: p.config.RecordType, // Flat schema
+5 -3
View File
@@ -57,7 +57,8 @@ func (bc *BrokerClient) PublishSchematizedMessage(topicName string, key []byte,
}
// Step 3: Publish the decoded RecordValue to mq.broker
return publisher.PublishRecord(key, decoded.RecordValue)
_, err = publisher.PublishRecord(key, decoded.RecordValue)
return err
}
// PublishRawMessage publishes a raw message (non-schematized) to mq.broker
@@ -68,7 +69,8 @@ func (bc *BrokerClient) PublishRawMessage(topicName string, key []byte, value []
return fmt.Errorf("failed to get publisher for topic %s: %w", topicName, err)
}
return publisher.Publish(key, value)
_, err = publisher.Publish(key, value)
return err
}
// getOrCreatePublisher gets or creates a TopicPublisher for the given topic
@@ -106,7 +108,7 @@ func (bc *BrokerClient) getOrCreatePublisher(topicName string, recordType *schem
}
// Create the publisher
publisher, err := pub_client.NewTopicPublisher(config)
publisher, err := pub_client.NewTopicPublisher(context.Background(), config)
if err != nil {
return nil, fmt.Errorf("failed to create topic publisher: %w", err)
}
+20 -6
View File
@@ -852,7 +852,8 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
glog.Errorf("completeMultipartUpload %s upload %s unused part cleanup: %v", *input.Bucket, *input.UploadId, err)
return s3err.ErrInternalError
}
if code := s3a.routedMultipartFinalize(owner, *input.Bucket, *input.Key, useInvertedFormat, versionDir, versionFileName, completionState.finalParts, decorateVersionEntry, *input.UploadId, cond); code != s3err.ErrNone {
logTsNs, code := s3a.routedMultipartFinalize(owner, *input.Bucket, *input.Key, useInvertedFormat, versionDir, versionFileName, completionState.finalParts, decorateVersionEntry, *input.UploadId, cond)
if code != s3err.ErrNone {
if code == s3err.ErrNoSuchUpload {
return code
}
@@ -870,6 +871,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
return code
}
completionState.uploadDirRemoved = true
noteObjectCommit(r.Context(), logTsNs, completionState.offset)
} else {
if err := s3a.mkFile(versionDir, versionFileName, completionState.finalParts, decorateVersionEntry); err != nil {
glog.Errorf("completeMultipartUpload: failed to create version %s: %v", versionId, err)
@@ -883,6 +885,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
glog.Errorf("completeMultipartUpload: failed to update latest version in directory: %v", err)
return s3err.ErrInternalError
}
noteObjectCommit(r.Context(), 0, completionState.offset)
}
// For versioned buckets, all content is stored in .versions directory
@@ -909,7 +912,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
// The condition checks the null slot first, then the latest version,
// same resolution the gateway's conditional check performs.
versionsDir := dirName + "/" + entryName + s3_constants.VersionsFolder
if err := s3a.writeMultipartObject(owner, routeKey, dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
logTsNs, err := s3a.writeMultipartObject(owner, routeKey, dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
@@ -957,7 +960,8 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
entry.Attributes.Mime = completionState.mime
}
entry.Attributes.FileSize = uint64(completionState.offset)
}, removal, cond, versionsDir); err != nil {
}, removal, cond, versionsDir)
if err != nil {
if errors.Is(err, errUploadRemoved) {
return s3err.ErrNoSuchUpload
}
@@ -973,6 +977,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
return s3err.ErrInternalError
}
completionState.uploadDirRemoved = removal != nil
noteObjectCommit(r.Context(), logTsNs, completionState.offset)
// A failed finalize leaves the key reading as deleted, so fail rather than
// return 200 — a non-ErrNone finalize keeps the upload directory, so the
@@ -1002,7 +1007,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
glog.Errorf("completeMultipartUpload %s upload %s unused part cleanup: %v", *input.Bucket, *input.UploadId, err)
return s3err.ErrInternalError
}
if err := s3a.writeMultipartObject(owner, routeKey, dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
logTsNs, err := s3a.writeMultipartObject(owner, routeKey, dirName, entryName, completionState.finalParts, func(entry *filer_pb.Entry) {
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
@@ -1053,7 +1058,8 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
if completionState.entityWithTtl {
entry.Extended[s3_constants.SeaweedFSExpiresS3] = []byte("true")
}
}, removal, cond, ""); err != nil {
}, removal, cond, "")
if err != nil {
if errors.Is(err, errUploadRemoved) {
return s3err.ErrNoSuchUpload
}
@@ -1069,6 +1075,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
return s3err.ErrInternalError
}
completionState.uploadDirRemoved = removal != nil
noteObjectCommit(r.Context(), logTsNs, completionState.offset)
// For non-versioned buckets, return response without VersionId
output = &CompleteMultipartUploadResult{
@@ -1112,7 +1119,8 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
glog.Warningf("completeMultipartUpload %s/%s upload %s: committed despite %s", *input.Bucket, *input.Key, *input.UploadId, s3err.GetAPIError(finalizeCode).Code)
// Another attempt of this upload may own the commit, and its parts can
// include ones this attempt counts as unused.
if !sameFileChunks(committedEntry.GetChunks(), completionState.finalParts) {
ownCommit := sameFileChunks(committedEntry.GetChunks(), completionState.finalParts)
if !ownCommit {
completionState.metadataOnlyCleanup = true
}
parentCtx, cancel := context.WithTimeout(context.Background(), createLookupTimeout)
@@ -1122,6 +1130,12 @@ func (s3a *S3ApiServer) completeMultipartUpload(r *http.Request, input *s3.Compl
glog.Errorf("completeMultipartUpload %s/%s upload %s: committed object's directory %s is missing: %v", *input.Bucket, *input.Key, *input.UploadId, dirName, parentErr)
} else {
output = committed
// a retry is answered as a replay, so this is the commit's only chance at its
// event; the entry's commit stamp is the committing filer's log stamp, kept
// by peers that replicate it, and 0 from filers that predate it
if ownCommit {
noteObjectCommit(r.Context(), committedEntry.GetCommitTsNs(), completionState.offset)
}
}
}
+47
View File
@@ -191,6 +191,53 @@ func TestCompleteMultipartUploadCommittedDespiteFailure(t *testing.T) {
}
}
// The recovered completion is the commit's only answer, so it carries the
// commit to the event; one answered from another attempt's commit does not.
func TestCompleteMultipartUploadCommittedDespiteFailureNotesTheCommit(t *testing.T) {
other := &filer_pb.Entry{
Name: "a.bin",
Attributes: &filer_pb.FuseAttributes{FileSize: 11},
Chunks: []*filer_pb.FileChunk{{FileId: "3,02637037d6", Size: 11}},
Extended: map[string][]byte{s3_constants.SeaweedFSUploadId: []byte("u1")},
}
const ownerStamp = 1796165098673197123
for _, c := range []struct {
name string
stored func(*filer_pb.Entry) *filer_pb.Entry
want bool
wantStamp int64
}{
{"own commit", func(entry *filer_pb.Entry) *filer_pb.Entry {
entry.CommitTsNs = ownerStamp
return entry
}, true, ownerStamp},
{"own commit from a filer without commit stamps", func(entry *filer_pb.Entry) *filer_pb.Entry { return entry }, true, 0},
{"another attempt's commit", func(*filer_pb.Entry) *filer_pb.Entry { return other }, false, 0},
} {
t.Run(c.name, func(t *testing.T) {
f := &memCompleteFiler{entries: map[string]map[string]*filer_pb.Entry{}, createFailure: status.Error(codes.Internal, "response lost after commit"), storedOnFailure: c.stored}
s3a := newCompleteTestServer(t, f)
input := &s3.CompleteMultipartUploadInput{Bucket: aws.String("b"), Key: aws.String("a.bin"), UploadId: aws.String("u1")}
parts := &CompleteMultipartUpload{Parts: []CompletedPart{{PartNumber: 1, ETag: `"5eb63bbbe01eeed093cb22bb8f5acdc3"`}}}
r, commit := withObjectCommit(httptest.NewRequest("POST", "/b/a.bin?uploadId=u1", nil))
if _, code := s3a.completeMultipartUpload(r, input, parts); code != s3err.ErrNone {
t.Fatalf("code = %v, want success", s3err.GetAPIError(code).Code)
}
if commit.committed() != c.want {
t.Fatalf("committed = %v, want %v", commit.committed(), c.want)
}
logTsNs, size := commit.noted()
if c.want && size != 11 {
t.Errorf("noted size %d, want 11", size)
}
// the stored entry's commit stamp sequences the event, as the routed commit's would have
if logTsNs != c.wantStamp {
t.Errorf("noted stamp %d, want %d", logTsNs, c.wantStamp)
}
})
}
}
func newVersionedCommitTestServer(t *testing.T, versioning string) (*S3ApiServer, *memCompleteFiler) {
t.Helper()
f := &memCompleteFiler{entries: map[string]map[string]*filer_pb.Entry{}}
+13 -4
View File
@@ -163,7 +163,9 @@ func (s3a *S3ApiServer) PutBucketAccelerateConfigurationHandler(w http.ResponseW
// PutBucketNotificationConfigurationHandler stores the bucket's notification
// configuration. Every destination must resolve to an operator-defined target
// that allows this bucket; an empty configuration removes the stored one.
// that allows this bucket and, unless x-amz-skip-destination-validation is
// true, ack an s3:TestEvent on its topic; an empty configuration removes the
// stored one.
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketNotificationConfiguration.html
func (s3a *S3ApiServer) PutBucketNotificationConfigurationHandler(w http.ResponseWriter, r *http.Request) {
bucket, _ := s3_constants.GetBucketAndObject(r)
@@ -182,9 +184,9 @@ func (s3a *S3ApiServer) PutBucketNotificationConfigurationHandler(w http.Respons
}
return
}
// The header only skips the test event, which the publishing path sends;
// registry checks below always run.
if _, ok := parseSkipDestinationValidation(r); !ok {
// The header only skips the test event; registry checks always run.
skipTestEvent, ok := parseSkipDestinationValidation(r)
if !ok {
s3err.WriteErrorResponseWithMessage(w, r, s3err.ErrInvalidArgument, "Invalid value for header "+s3_constants.AmzSkipDestinationValidation)
return
}
@@ -203,6 +205,13 @@ func (s3a *S3ApiServer) PutBucketNotificationConfigurationHandler(w http.Respons
return
}
if !skipTestEvent {
if failed := s3a.sendNotificationTestEvents(r, bucket, config); len(failed) > 0 {
s3err.WriteErrorResponseWithMessage(w, r, s3err.ErrInvalidArgument, "Unable to validate the following destination configurations: "+strings.Join(failed, ", "))
return
}
}
var stored []byte
if len(config.Rules) > 0 {
stored = body
+2
View File
@@ -52,6 +52,7 @@ func (s3a *S3ApiServer) loadNotificationTargetsFromBytes(content []byte) error {
return err
}
s3a.notificationTargets.Store(reg)
s3a.syncNotificationPublisher(reg)
glog.V(1).Infof("loaded %d notification targets", len(reg.Names()))
return nil
}
@@ -71,6 +72,7 @@ func (s3a *S3ApiServer) onNotificationTargetsChange(dir string, oldEntry *filer_
}
if oldEntry != nil && oldEntry.Name == s3notification.TargetsFile {
s3a.notificationTargets.Store(nil)
s3a.syncNotificationPublisher(nil)
glog.V(1).Infof("notification targets removed")
}
}
+85 -1
View File
@@ -1,9 +1,11 @@
package s3api
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -67,6 +69,51 @@ func TestOnNotificationTargetsChange(t *testing.T) {
require.Nil(t, s3a.notificationTargetRegistry())
}
// fakeNotificationPublisher records what the gateway publishes; it acks
// every message unless stalled.
type fakeNotificationPublisher struct {
mu sync.Mutex
stalled bool
calls int
synced [][]string
messages []s3notification.Message
}
func (f *fakeNotificationPublisher) Sync(reg *s3notification.Registry) {
f.mu.Lock()
defer f.mu.Unlock()
f.synced = append(f.synced, reg.Names())
}
func (f *fakeNotificationPublisher) Publish(ctx context.Context, messages []s3notification.Message) bool {
f.mu.Lock()
defer f.mu.Unlock()
if len(messages) > 0 {
f.calls++
}
f.messages = append(f.messages, messages...)
return !f.stalled
}
func (f *fakeNotificationPublisher) Close() {}
func (f *fakeNotificationPublisher) published() []s3notification.Message {
f.mu.Lock()
defer f.mu.Unlock()
return append([]s3notification.Message(nil), f.messages...)
}
func TestNotificationTargetsChangeSyncsThePublisher(t *testing.T) {
publisher := &fakeNotificationPublisher{}
s3a := &S3ApiServer{notificationPublisher: publisher}
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)
}
func TestLoadNotificationTargets(t *testing.T) {
s3a := newHeadBucketTestServer(t, &fakeLookupFiler{entry: targetsEntry(s3notification.TargetsFile, testNotificationTargets)})
s3a.loadNotificationTargets()
@@ -104,6 +151,7 @@ const testNotificationXML = `<?xml version="1.0" encoding="UTF-8"?>
func newNotificationTestServer(t *testing.T, bucket string, extended map[string][]byte) (*S3ApiServer, *fakeLookupFiler) {
t.Helper()
s3a, filer := newPublicAccessBlockTestServer(t, &filer_pb.Entry{Name: bucket, IsDirectory: true, Extended: extended})
s3a.notificationPublisher = &fakeNotificationPublisher{}
require.NoError(t, s3a.loadNotificationTargetsFromBytes([]byte(testNotificationTargets)))
return s3a, filer
}
@@ -220,7 +268,7 @@ func TestPutBucketNotificationConfigurationRejects(t *testing.T) {
}
func TestPutBucketNotificationConfigurationAcceptsSkipHeader(t *testing.T) {
for _, value := range []string{"true", "false", "TRUE"} {
for value, testEvents := range map[string]int{"true": 0, "false": 2, "TRUE": 0} {
s3a, filer := newNotificationTestServer(t, "orders-eu", nil)
req := notificationRequest(http.MethodPut, "orders-eu", testNotificationXML)
req.Header.Set(s3_constants.AmzSkipDestinationValidation, value)
@@ -228,9 +276,45 @@ func TestPutBucketNotificationConfigurationAcceptsSkipHeader(t *testing.T) {
s3a.PutBucketNotificationConfigurationHandler(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Len(t, filer.txnSeen, 1)
require.Len(t, s3a.notificationPublisher.(*fakeNotificationPublisher).published(), testEvents, value)
}
}
func TestPutBucketNotificationConfigurationSendsTestEvents(t *testing.T) {
s3a, filer := newNotificationTestServer(t, "orders-eu", nil)
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "orders-eu", testNotificationXML))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Len(t, filer.txnSeen, 1)
messages := s3a.notificationPublisher.(*fakeNotificationPublisher).published()
var targets []string
for _, m := range messages {
targets = append(targets, m.Target)
require.Equal(t, "orders-eu/", string(m.Key))
require.True(t, s3notification.IsTestEvent(m.Value))
require.Equal(t, "orders-eu", m.Value.Fields[s3notification.ColumnBucketName].GetStringValue())
require.NotNil(t, m.Value.Fields[s3notification.ColumnEventTime].GetTimestampValue())
}
require.ElementsMatch(t, []string{"orders", "raw"}, targets)
}
func TestPutBucketNotificationConfigurationFailsWhenTheTestEventIsNotAcked(t *testing.T) {
s3a, filer := newNotificationTestServer(t, "orders-eu", nil)
s3a.notificationPublisher.(*fakeNotificationPublisher).stalled = true
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "orders-eu", testNotificationXML))
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Contains(t, rec.Body.String(), "<Code>InvalidArgument</Code>")
require.Contains(t, rec.Body.String(), "arn:aws:sns:us-east-1:123456789012:orders, arn:aws:sqs:::raw")
require.Empty(t, filer.txnSeen, "a configuration whose destination did not ack must not be stored")
// Removing the configuration sends nothing, so nothing can fail it.
rec = httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "orders-eu", `<NotificationConfiguration/>`))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
}
func TestPutBucketNotificationConfigurationWithoutTargets(t *testing.T) {
s3a, filer := newPublicAccessBlockTestServer(t, &filer_pb.Entry{Name: "b", IsDirectory: true})
rec := httptest.NewRecorder()
+4 -4
View File
@@ -181,7 +181,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
if lockErr == nil {
// The "null" version is the object entry, not a .versions file.
if req.VersionId == "null" {
code, settled := s3a.routedDeleteNullVersion(owner, req.Bucket, req.ObjectPath, worm, false, metadataOnly, nil)
_, code, settled := s3a.routedDeleteNullVersion(owner, req.Bucket, req.ObjectPath, worm, false, metadataOnly, nil)
if settled {
if code == s3err.ErrAccessDenied {
return retryLater("ACCESS_DENIED: deleteSpecificVersion: object lock"), nil
@@ -192,7 +192,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
versionDeleted = true
}
} else {
switch code := s3a.routedDeleteSpecificVersion(owner, req.Bucket, req.ObjectPath, req.VersionId, worm && !isDeleteMarkerEntry(entry), false, metadataOnly, nil); code {
switch _, code := s3a.routedDeleteSpecificVersion(owner, req.Bucket, req.ObjectPath, req.VersionId, worm && !isDeleteMarkerEntry(entry), false, metadataOnly, nil); code {
case s3err.ErrNone:
versionDeleted = true
case s3err.ErrAccessDenied:
@@ -266,7 +266,7 @@ func (s3a *S3ApiServer) lifecycleDeleteMarkerIf(bucket, object, normalized, expe
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL,
ExpectedEntry: pointer,
}}}
if _, err := s3a.createDeleteMarkerIf(bucket, object, guard); err != nil {
if _, _, err := s3a.createDeleteMarkerIf(bucket, object, guard); err != nil {
if errors.Is(err, errLatestVersionChanged) {
continue
}
@@ -308,7 +308,7 @@ func (s3a *S3ApiServer) lifecycleDeleteNullVersion(req *s3_lifecycle_pb.Lifecycl
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL,
ExpectedEntry: nullEntry,
}}}
switch code, _ := s3a.routedDeleteNullVersion(owner, req.Bucket, req.ObjectPath, worm, false, metadataOnly, guard); code {
switch _, code, _ := s3a.routedDeleteNullVersion(owner, req.Bucket, req.ObjectPath, worm, false, metadataOnly, guard); code {
case s3err.ErrNone, s3err.ErrPreconditionFailed:
return done()
case s3err.ErrAccessDenied:
+215
View File
@@ -0,0 +1,215 @@
package s3api
import (
"context"
"net/http"
"slices"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
)
const notificationBrokerListTimeout = 5 * time.Second
// notificationPublisher is what the gateway needs from s3notification.Publisher.
type notificationPublisher interface {
Sync(reg *s3notification.Registry)
Publish(ctx context.Context, messages []s3notification.Message) bool
Close()
}
// newNotificationPublisher returns nil, leaving notifications off, when the
// grpc.msg_broker client TLS config is unusable: the gateway keeps serving,
// and never talks to a broker without the TLS it was configured to use.
func (s3a *S3ApiServer) newNotificationPublisher() notificationPublisher {
dialOption, err := security.TryLoadClientTLS(util.GetViper(), "grpc.msg_broker", "grpc.msg_broker")
if err != nil {
glog.Errorf("bucket notifications are off: %v", err)
return nil
}
return s3notification.NewPublisher(s3a.notificationBrokers, dialOption)
}
// 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 {
var brokers []string
seen := map[string]bool{}
add := func(address string) {
if address != "" && !seen[address] {
seen[address] = true
brokers = append(brokers, address)
}
}
add(string(s3a.option.MqBroker))
if s3a.masterClient == nil {
return brokers
}
ctx, cancel := context.WithTimeout(context.Background(), notificationBrokerListTimeout)
defer cancel()
err := s3a.masterClient.WithClient(ctx, false, func(client master_pb.SeaweedClient) error {
resp, err := client.ListClusterNodes(ctx, &master_pb.ListClusterNodesRequest{
ClientType: cluster.BrokerType,
FilerGroup: s3a.option.FilerGroup,
})
if err != nil {
return err
}
for _, node := range resp.ClusterNodes {
add(node.Address)
}
return nil
})
if err != nil {
glog.V(1).Infof("list message queue brokers: %v", err)
}
return brokers
}
// sendNotificationTestEvents publishes s3:TestEvent to the topic of every
// target config names and returns the destinations whose target did not ack
// it within the publisher's wait.
func (s3a *S3ApiServer) sendNotificationTestEvents(r *http.Request, bucket string, config *s3notification.Configuration) []string {
destinations := map[string][]string{}
for _, rule := range config.Rules {
destinations[rule.Target] = append(destinations[rule.Target], rule.Destination)
}
if len(destinations) == 0 {
return nil
}
value := s3notification.TestEventRecord(bucket, request_id.GetFromRequest(r), time.Now().UnixNano())
var mu sync.Mutex
var failed []string
var wg sync.WaitGroup
for target, arns := range destinations {
wg.Add(1)
go func() {
defer wg.Done()
message := s3notification.Message{Target: target, Key: s3notification.MessageKey(bucket, ""), Value: value}
if s3a.notificationPublisher != nil && s3a.notificationPublisher.Publish(r.Context(), []s3notification.Message{message}) {
return
}
mu.Lock()
failed = append(failed, arns...)
mu.Unlock()
}()
}
wg.Wait()
slices.Sort(failed)
return slices.Compact(failed)
}
// objectCommit is what a request committed to the filer, noted where the
// commit happens, which can be far below the handler that publishes the event.
type objectCommit struct {
mu sync.Mutex
wrote bool
logTsNs int64
size int64
}
type objectCommitKey struct{}
// withObjectCommit gives r somewhere for noteObjectCommit to record into.
func withObjectCommit(r *http.Request) (*http.Request, *objectCommit) {
commit := &objectCommit{}
return r.WithContext(context.WithValue(r.Context(), objectCommitKey{}, commit)), commit
}
// noteObjectCommit records a commit's filer stamp, 0 when the write path did
// not return one, and the size of the object it committed.
func noteObjectCommit(ctx context.Context, logTsNs, size int64) {
commit, _ := ctx.Value(objectCommitKey{}).(*objectCommit)
if commit == nil {
return
}
commit.mu.Lock()
defer commit.mu.Unlock()
commit.wrote = true
commit.logTsNs = max(commit.logTsNs, logTsNs)
commit.size = size
}
// committed reports whether the request committed anything; a retried
// request answered from an earlier commit did not.
func (c *objectCommit) committed() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.wrote
}
func (c *objectCommit) noted() (logTsNs, size int64) {
c.mu.Lock()
defer c.mu.Unlock()
return c.logTsNs, c.size
}
// publishObjectEvent publishes each event once per rule of its bucket's
// configuration that matches it, and waits for all the acks within the
// publisher's bound. It never fails the request: what is not acked stays
// queued or is counted as dropped.
func (s3a *S3ApiServer) publishObjectEvent(r *http.Request, events ...s3notification.Event) {
if s3a.notificationPublisher == nil {
return
}
var messages []s3notification.Message
for _, event := range events {
config, errCode := s3a.getBucketConfig(event.Bucket)
if errCode != s3err.ErrNone || config.Notification == nil {
continue
}
matches := config.Notification.Match(event.Name, event.Key)
if len(matches) == 0 {
continue
}
event.Region = s3tables.DefaultRegion
event.BucketOwner = config.Owner
event.Principal = notificationPrincipal(r)
event.SourceIP = s3err.RemoteIP(r)
event.RequestID = request_id.GetFromRequest(r)
if event.LogTsNs == 0 {
// Write paths that do not return the filer's stamp take the gateway's
// clock, which orders one key's events only on this gateway.
event.LogTsNs = time.Now().UnixNano()
}
registry := s3a.notificationTargetRegistry()
for _, match := range matches {
if _, ok := registry.Resolve(match.Target, event.Bucket); !ok {
glog.V(1).Infof("bucket %s notification rule %s: target %s no longer resolves", event.Bucket, match.ID, match.Target)
continue
}
messages = append(messages, s3notification.Message{
Target: match.Target,
Key: s3notification.MessageKey(event.Bucket, event.Key),
Value: event.RecordValue(match.ID),
})
}
}
s3a.notificationPublisher.Publish(r.Context(), messages)
}
// notificationPrincipal is the authenticated identity, never a request
// header: with auth off, s3-account-id comes straight from the client.
func notificationPrincipal(r *http.Request) string {
if name := s3_constants.GetIdentityNameFromContext(r); name != "" {
return name
}
return s3_constants.AccountAnonymousId
}
// syncNotificationPublisher gives every target in reg a publisher worker.
func (s3a *S3ApiServer) syncNotificationPublisher(reg *s3notification.Registry) {
if s3a.notificationPublisher != nil {
s3a.notificationPublisher.Sync(reg)
}
}
@@ -0,0 +1,30 @@
package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/stretchr/testify/require"
)
func TestNotificationBrokersStartWithTheGatewaysOwn(t *testing.T) {
s3a := &S3ApiServer{option: &S3ApiServerOption{MqBroker: "10.0.0.1:17777"}}
require.Equal(t, []string{"10.0.0.1:17777"}, s3a.notificationBrokers())
none := &S3ApiServer{option: &S3ApiServerOption{}}
require.Empty(t, none.notificationBrokers())
}
func TestABadBrokerTLSConfigTurnsNotificationsOff(t *testing.T) {
v := util.GetViper()
v.Set("grpc.msg_broker.cert", "/nonexistent/broker.crt")
t.Cleanup(func() { v.Set("grpc.msg_broker.cert", "") })
s3a := &S3ApiServer{option: &S3ApiServerOption{}}
require.Nil(t, s3a.newNotificationPublisher(), "a cert without its key must leave notifications off, not stop the gateway")
v.Set("grpc.msg_broker.cert", "")
publisher := s3a.newNotificationPublisher()
require.NotNil(t, publisher)
publisher.Close()
}
+32 -16
View File
@@ -29,6 +29,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
@@ -364,6 +365,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
if replacesSource && (replaceMeta || replaceTagging || changesStorageClass) && s3a.canUseMetadataOnlySelfCopy(entry, r, dstBucket, dstObject) {
var dstVersionId string
var etag string
var logTsNs, size int64
// Bind the entire self-copy update to the snapshot read on each attempt.
// ACLs and their file mode must commit together, even when another writer
// changes the mode between the gateway's read and the owner's commit.
@@ -438,8 +440,10 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
updatedEntry.Attributes.FileMode |= uint32(os.ModeDir)
}
updatedEntry.Attributes.Mtime = t.Unix()
size = int64(filer.FileSize(currentEntry))
if owner != "" {
if err := s3a.routedSelfCopy(r.Context(), owner, dstBucket, dstObject, rawEntry, updatedEntry); err != nil {
var err error
if logTsNs, err = s3a.routedSelfCopy(r.Context(), owner, dstBucket, dstObject, rawEntry, updatedEntry); err != nil {
switch status.Code(err) {
case codes.FailedPrecondition:
return s3err.ErrConditionalRequestConflict
@@ -453,7 +457,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
return s3err.ErrNone
}
var finErr error
dstVersionId, etag, finErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, updatedEntry)
dstVersionId, etag, logTsNs, finErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, updatedEntry)
if finErr != nil {
return filerErrorToS3Error(finErr)
}
@@ -478,6 +482,10 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
s3err.WriteErrorResponse(w, r, updateCode)
return
}
s3a.publishObjectEvent(r, s3notification.Event{
Name: s3notification.EventObjectCreatedCopy, Bucket: dstBucket, Key: dstObject,
Size: size, ETag: etag, VersionID: dstVersionId, LogTsNs: logTsNs,
})
if dstVersionId != "" {
w.Header().Set("x-amz-version-id", dstVersionId)
@@ -676,6 +684,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
var dstVersionId string
var etag string
var logTsNs int64
applyPutObjectACL(r, dstEntry)
finalizeStarted := false
@@ -687,7 +696,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
}, func() s3err.ErrorCode {
finalizeStarted = true
var finalizeErr error
dstVersionId, etag, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry)
dstVersionId, etag, logTsNs, finalizeErr = s3a.finalizeCopyDestination(dstBucket, dstObject, dstVersioningState, dstEntry)
if finalizeErr != nil {
return filerErrorToS3Error(finalizeErr)
}
@@ -703,6 +712,10 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
keepAlive.writeError(finalizeCode)
return
}
s3a.publishObjectEvent(r, s3notification.Event{
Name: s3notification.EventObjectCreatedCopy, Bucket: dstBucket, Key: dstObject,
Size: int64(filer.FileSize(dstEntry)), ETag: etag, VersionID: dstVersionId, LogTsNs: logTsNs,
})
keepAlive.writeSuccess(func() {
if dstVersionId != "" {
@@ -800,7 +813,9 @@ func copyEntryToTarget(dst, src *filer_pb.Entry) {
dst.WormEnforcedAtTsNs = src.WormEnforcedAtTsNs
}
func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersioningState string, dstEntry *filer_pb.Entry) (versionId string, etag string, err error) {
// finalizeCopyDestination commits the copy's destination entry and returns
// the filer's stamp of the commit, 0 when the write path does not return one.
func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersioningState string, dstEntry *filer_pb.Entry) (versionId string, etag string, logTsNs int64, err error) {
normalizedObject := s3_constants.NormalizeObjectKey(dstObject)
dstPath := util.FullPath(fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), normalizedObject))
dstDir, dstName := dstPath.DirAndName()
@@ -830,7 +845,7 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
// The finalize recomputes the latest pointer by scanning .versions on
// the owner, so the version file must commit there too.
if owner != "" {
err = s3a.routedMkFile(owner, s3a.objectRouteKey(dstBucket, normalizedObject), bucketDir+"/"+normalizedObject+s3_constants.VersionsFolder, versionFileName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
_, err = s3a.routedMkFile(owner, s3a.objectRouteKey(dstBucket, normalizedObject), bucketDir+"/"+normalizedObject+s3_constants.VersionsFolder, versionFileName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
copyEntryToTarget(entry, dstEntry)
}, nil, nil, "")
} else {
@@ -839,27 +854,28 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
})
}
if err != nil {
return "", "", err
return "", "", 0, err
}
// Route the pointer flip to the owner filer when known (off the
// distributed lock); RECOMPUTE_LATEST picks the just-written version.
if owner != "" {
if code := s3a.routedVersionedFinalize(owner, dstBucket, normalizedObject, isNewFormatVersionId(versionId), nil, nil); code != s3err.ErrNone {
var code s3err.ErrorCode
if logTsNs, code = s3a.routedVersionedFinalize(owner, dstBucket, normalizedObject, isNewFormatVersionId(versionId), nil, nil); code != s3err.ErrNone {
if rollbackErr := s3a.rollbackCopyVersion(owner, dstBucket, normalizedObject, versionObjectPath); rollbackErr != nil {
glog.Errorf("CopyObjectHandler: failed to rollback version %s for %s/%s after routed finalize error: %v", versionId, dstBucket, normalizedObject, rollbackErr)
}
return "", "", fmt.Errorf("routed finalize for %s/%s: code %d", dstBucket, normalizedObject, code)
return "", "", 0, fmt.Errorf("routed finalize for %s/%s: code %d", dstBucket, normalizedObject, code)
}
} else if err = s3a.updateLatestVersionInDirectory(dstBucket, normalizedObject, versionId, versionFileName, dstEntry); err != nil {
if rollbackErr := s3a.rollbackCopyVersion("", dstBucket, normalizedObject, versionObjectPath); rollbackErr != nil {
glog.Errorf("CopyObjectHandler: failed to rollback version %s for %s/%s after latest pointer update error: %v", versionId, dstBucket, normalizedObject, rollbackErr)
}
glog.Errorf("CopyObjectHandler: failed to update latest version in directory: %v", err)
return "", "", fmt.Errorf("update latest version metadata: %w", err)
return "", "", 0, fmt.Errorf("update latest version metadata: %w", err)
}
return versionId, etag, nil
return versionId, etag, logTsNs, nil
case s3_constants.VersioningSuspended:
cleanupVersioningMetadata(dstEntry.Extended)
@@ -867,10 +883,10 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
dstEntry.Extended[s3_constants.ExtETagKey] = []byte(etag)
owner := s3a.objectWriteOwner(dstBucket, normalizedObject)
if err = s3a.writeMultipartObject(owner, s3a.objectRouteKey(dstBucket, normalizedObject), dstDir, dstName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
if logTsNs, err = s3a.writeMultipartObject(owner, s3a.objectRouteKey(dstBucket, normalizedObject), dstDir, dstName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
copyEntryToTarget(entry, dstEntry)
}, nil, nil, ""); err != nil {
return "", "", err
return "", "", 0, err
}
// The ownership check reads the entry back where the write committed.
@@ -878,7 +894,7 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
glog.Warningf("CopyObjectHandler: failed to retire the null delete marker for %s/%s: %v", dstBucket, normalizedObject, err)
}
return "", etag, nil
return "", etag, logTsNs, nil
default:
cleanupVersioningMetadata(dstEntry.Extended)
@@ -887,13 +903,13 @@ func (s3a *S3ApiServer) finalizeCopyDestination(dstBucket, dstObject, dstVersion
// Copy source reads resolve on the key's write owner, so a copy
// destination must commit there too — a destination written to the
// default filer is invisible to the next copy until replication.
if err = s3a.writeMultipartObject(s3a.objectWriteOwner(dstBucket, normalizedObject), s3a.objectRouteKey(dstBucket, normalizedObject), dstDir, dstName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
if logTsNs, err = s3a.writeMultipartObject(s3a.objectWriteOwner(dstBucket, normalizedObject), s3a.objectRouteKey(dstBucket, normalizedObject), dstDir, dstName, dstEntry.Chunks, func(entry *filer_pb.Entry) {
copyEntryToTarget(entry, dstEntry)
}, nil, nil, ""); err != nil {
return "", "", err
return "", "", 0, err
}
return "", etag, nil
return "", etag, logTsNs, nil
}
}
@@ -65,7 +65,7 @@ func TestRoutedSelfCopyBusinessErrors(t *testing.T) {
peerAddress := startFakeFiler(t, peer)
s3a := newPutTestServer(t, peerAddress)
current := &filer_pb.Entry{Name: "obj", Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode}}
err := s3a.routedSelfCopy(context.Background(), ownerAddress, "b", "obj", current, proto.Clone(current).(*filer_pb.Entry))
_, err := s3a.routedSelfCopy(context.Background(), ownerAddress, "b", "obj", current, proto.Clone(current).(*filer_pb.Entry))
require.Equal(t, code, status.Code(err), "a peer transport error must not mask the owner's business rejection")
require.Equal(t, int32(1), owner.calls.Load())
require.Zero(t, peer.calls.Load(), "rejected commits must not be replayed")
+28 -4
View File
@@ -11,6 +11,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -22,6 +23,17 @@ const (
type deleteMutationResult struct {
versionId string
deleteMarker bool
logTsNs int64 // the filer's stamp of the commit, 0 when the path returns none
}
// removedEvent is the event a delete that produced result publishes: a delete
// that left a marker in place of the key is DeleteMarkerCreated.
func removedEvent(bucket, object, requestedVersionId string, result deleteMutationResult) s3notification.Event {
name := s3notification.EventObjectRemovedDelete
if requestedVersionId == "" && result.deleteMarker {
name = s3notification.EventObjectRemovedDeleteMarkerCreated
}
return s3notification.Event{Name: name, Bucket: bucket, Key: object, VersionID: result.versionId, LogTsNs: result.logTsNs}
}
func deleteErrorFromCode(code s3err.ErrorCode, key, versionId string) DeleteError {
@@ -149,12 +161,13 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
return result, s3err.ErrNone
case versioningState == s3_constants.VersioningEnabled:
deleteMarkerVersionId, err := s3a.createDeleteMarker(bucket, object)
deleteMarkerVersionId, logTsNs, err := s3a.createDeleteMarker(bucket, object)
if err != nil {
glog.Errorf("deleteVersionedObject: failed to create delete marker for %s/%s: %v", bucket, object, err)
return result, s3err.ErrInternalError
}
result.versionId = deleteMarkerVersionId
result.logTsNs = logTsNs
result.deleteMarker = true
return result, s3err.ErrNone
@@ -172,12 +185,15 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
if owner := s3a.routableWriteOwner(bucket, object); owner != "" {
worm, lockErr := s3a.isObjectLockEnabled(bucket)
if lockErr == nil {
code, settled := s3a.routedDeleteNullVersion(owner, bucket, object, worm, worm && governanceBypassAllowed, false, nil)
logTsNs, code, settled := s3a.routedDeleteNullVersion(owner, bucket, object, worm, worm && governanceBypassAllowed, false, nil)
if settled {
if code != s3err.ErrNone {
return result, code
}
nullDeleted = true
// The marker written next goes to the default filer, whose clock
// is not the owner's; one key's sequencers come from its owner.
result.logTsNs = logTsNs
}
}
}
@@ -300,6 +316,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
glog.Warningf("DeleteObjectHandler: routed delete to %s returned %q for %s/%s, falling back to lock", owner, resp.Error, bucket, object)
default:
deleteCode, deleteHandled = s3err.ErrNone, true
deleteResult.logTsNs = resp.LogTsNs
}
}
}
@@ -336,11 +353,12 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
}
}
if versionId == "null" {
deleteCode, deleteHandled = s3a.routedDeleteNullVersion(owner, bucket, object, worm, bypass, false, ifMatch)
deleteResult.logTsNs, deleteCode, deleteHandled = s3a.routedDeleteNullVersion(owner, bucket, object, worm, bypass, false, ifMatch)
} else {
// A version id never changes kind, so a marker read here is
// the one deleted; markers carry no WORM guard.
deleteCode, deleteHandled = s3a.routedDeleteSpecificVersion(owner, bucket, object, versionId, worm && !deleteResult.deleteMarker, bypass, false, ifMatch), true
deleteResult.logTsNs, deleteCode = s3a.routedDeleteSpecificVersion(owner, bucket, object, versionId, worm && !deleteResult.deleteMarker, bypass, false, ifMatch)
deleteHandled = true
}
}
}
@@ -378,6 +396,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
s3err.WriteErrorResponse(w, r, deleteCode)
return
}
s3a.publishObjectEvent(r, removedEvent(bucket, object, versionId, deleteResult))
if deleteResult.versionId != "" {
w.Header().Set("x-amz-version-id", deleteResult.versionId)
@@ -501,6 +520,7 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
// picks how many keys there are, so the whole batch shares one allowance.
r = r.WithContext(withFilerRetryBudget(r.Context(), filerRetryRequestBudget))
var events []s3notification.Event
err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
// delete file entries
for _, object := range deleteObjects.Objects {
@@ -579,6 +599,7 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
}
deletedCount++
events = append(events, removedEvent(bucket, key, object.VersionId, deleteResult))
if !deleteObjects.Quiet {
deletedObject := ObjectIdentifier{
Key: object.Key,
@@ -610,6 +631,9 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
return
}
// One wait covers every key's events.
s3a.publishObjectEvent(r, events...)
deleteResp := DeleteObjectsResponse{}
if !deleteObjects.Quiet {
deleteResp.DeletedObjects = deletedObjects
@@ -21,6 +21,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -192,6 +193,7 @@ func (s3a *S3ApiServer) CompleteMultipartUploadHandler(w http.ResponseWriter, r
return
}
r, commit := withObjectCommit(r)
response, errCode := s3a.completeMultipartUpload(r, &s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucket),
Key: objectKey(aws.String(object)),
@@ -209,6 +211,15 @@ func (s3a *S3ApiServer) CompleteMultipartUploadHandler(w http.ResponseWriter, r
if response.VersionId != nil {
w.Header().Set("x-amz-version-id", *response.VersionId)
}
// A retry answered from the completion that already committed has its
// event behind it, as AWS sends one per completion that created the object.
if commit.committed() {
logTsNs, size := commit.noted()
s3a.publishObjectEvent(r, s3notification.Event{
Name: s3notification.EventObjectCreatedCompleteMultipartUpload, Bucket: bucket, Key: object,
Size: size, ETag: aws.StringValue(response.ETag), VersionID: aws.StringValue(response.VersionId), LogTsNs: logTsNs,
})
}
stats_collect.RecordBucketActiveTime(bucket)
stats_collect.S3UploadedObjectsCounter.WithLabelValues(bucket).Inc()
@@ -20,6 +20,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/policy"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
"golang.org/x/net/http/httpguts"
)
@@ -230,6 +231,7 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
var etag string
var versionId string
var sseMetadata SSEResponseMetadata
r, commit := withObjectCommit(r)
switch versioningState {
case s3_constants.VersioningEnabled:
versionId, etag, errCode, sseMetadata = s3a.putVersionedObject(r, bucket, object, fileBody, contentType)
@@ -249,6 +251,11 @@ func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.R
if versionId != "" {
w.Header().Set("x-amz-version-id", versionId)
}
logTsNs, size := commit.noted()
s3a.publishObjectEvent(r, s3notification.Event{
Name: s3notification.EventObjectCreatedPost, Bucket: bucket, Key: object,
Size: size, ETag: etag, VersionID: versionId, LogTsNs: logTsNs,
})
if successRedirect != "" {
// Replace raw query params..
+20 -2
View File
@@ -27,6 +27,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
"github.com/seaweedfs/seaweedfs/weed/security"
weed_server "github.com/seaweedfs/seaweedfs/weed/server"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
@@ -88,6 +89,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
// http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
bucket, object := s3_constants.GetBucketAndObject(r)
r, commit := withObjectCommit(r)
// A copy-source header that did not satisfy the CopyObject route is
// malformed (it needs a '/' separating source bucket from key), and a
@@ -189,6 +191,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
}
objectContentType := r.Header.Get("Content-Type")
var eventETag, eventVersionID string
isDirectoryMarker := strings.HasSuffix(object, "/")
if isDirectoryMarker && directoryMarkerBodySize(r) > maxDirectoryMarkerContentSize {
// Past what a marker holds, only a versioned write keeps the key whole.
@@ -282,6 +285,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
return
}
dirEtag := fmt.Sprintf("%x", dirMd5)
markerSize := int64(len(dirContent))
// SSE applies to marker content too — it is stored in entry.Content
sseResult, sseErrCode := s3a.handleAllSSEEncryption(r, bytes.NewReader(dirContent), 0)
@@ -360,6 +364,8 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
s3err.WriteErrorResponse(w, r, markerCode)
return
}
noteObjectCommit(r.Context(), 0, markerSize)
eventETag = dirEtag
sseRespMetadata := SSEResponseMetadata{SSEType: sseResult.SSEType}
if sseResult.SSEKMSKey != nil {
sseRespMetadata.KMSKeyID = sseResult.SSEKMSKey.KeyID
@@ -459,6 +465,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
// Set ETag in response
setEtag(w, etag)
eventETag, eventVersionID = etag, versionId
// Set SSE response headers for versioned objects
s3a.setSSEResponseHeaders(w, r, sseMetadata)
@@ -477,6 +484,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
// Set ETag in response
setEtag(w, etag)
eventETag = etag
// Set SSE response headers for suspended versioning
s3a.setSSEResponseHeaders(w, r, sseMetadata)
@@ -497,6 +505,7 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
// No version ID header for never-configured versioning
setEtag(w, etag)
eventETag = etag
// Set SSE response headers based on encryption type used
s3a.setSSEResponseHeaders(w, r, sseMetadata)
@@ -505,6 +514,11 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
stats_collect.RecordBucketActiveTime(bucket)
stats_collect.S3UploadedObjectsCounter.WithLabelValues(bucket).Inc()
logTsNs, size := commit.noted()
s3a.publishObjectEvent(r, s3notification.Event{
Name: s3notification.EventObjectCreatedPut, Bucket: bucket, Key: object,
Size: size, ETag: eventETag, VersionID: eventVersionID, LogTsNs: logTsNs,
})
writeSuccessResponseEmpty(w, r)
}
@@ -1119,6 +1133,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
var createCond *filer_pb.WriteCondition
var rollbackErr error
entryCreated := false
var commitLogTsNs int64
var owner pb.ServerAddress
preconditionFn := func() s3err.ErrorCode {
if object == "" {
@@ -1135,7 +1150,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
Condition: cond,
}
glog.V(3).Infof("putToFiler: Calling CreateEntry for %s", filePath)
err := filer_pb.CreateEntry(context.Background(), client, req)
resp, err := filer_pb.CreateEntryWithResponse(context.Background(), client, req)
// A verification key in a table bucket never becomes a prefix
// object: the directory it meets is a namespace, created after the
// handler looked.
@@ -1144,12 +1159,13 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
// Other keys are nested under this one. S3 keys are flat, so the key is
// stored on the directory they live under rather than refused.
entry.MarkPrefixObject()
err = filer_pb.CreateEntry(context.Background(), client, req)
resp, err = filer_pb.CreateEntryWithResponse(context.Background(), client, req)
}
if err != nil {
glog.Errorf("putToFiler: CreateEntry returned error: %v", err)
return err
}
commitLogTsNs = resp.LogTsNs
return nil
}
// A conditional create must not be replayed once possibly sent: a lost
@@ -1246,6 +1262,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
glog.Warningf("putToFiler: routed PUT to %s returned %q for %s, falling back to lock", owner, resp.Error, filePath)
default:
entryCreated, routed, createCode = true, true, s3err.ErrNone
commitLogTsNs = resp.LogTsNs
// Bundled mutations already finalized in the transaction above;
// a finalize with none (suspended versioning) runs off the lock.
if len(finalizeMutations) == 0 && finalize != nil && finalize.afterCreate != nil {
@@ -1313,6 +1330,7 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader
}
}
glog.V(3).Infof("putToFiler: CreateEntry SUCCESS for %s", filePath)
noteObjectCommit(r.Context(), commitLogTsNs, int64(filer.FileSize(entry)))
glog.V(2).Infof("putToFiler: Metadata saved SUCCESS - path=%s, etag(hex)=%s, size=%d, partNumber=%d",
filePath, etag, entry.Attributes.FileSize, partNumber)
@@ -0,0 +1,560 @@
package s3api
import (
"bytes"
"context"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"fmt"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/stretchr/testify/require"
)
// stampingFiler answers each commit with its log stamp, as a filer that
// returns log_ts_ns does.
type stampingFiler struct {
*ambiguousPutFiler
last atomic.Int64
skew time.Duration // how far this filer's clock runs behind
}
func newStampingFiler(t *testing.T) *stampingFiler {
t.Helper()
return &stampingFiler{ambiguousPutFiler: &ambiguousPutFiler{
volume: startFakeVolumeServer(t),
apply: true,
entries: map[string]*filer_pb.Entry{
"/buckets/b": {Name: "b", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
},
}}
}
func (f *stampingFiler) stamp() int64 {
return f.last.Add(1) + time.Date(2026, 11, 30, 0, 0, 0, 0, time.UTC).Add(-f.skew).UnixNano()
}
func (f *stampingFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
resp, err := f.ambiguousPutFiler.CreateEntry(ctx, req)
if resp != nil && resp.Error == "" {
resp.LogTsNs = f.stamp()
}
return resp, err
}
func (f *stampingFiler) ObjectTransaction(ctx context.Context, req *filer_pb.ObjectTransactionRequest) (*filer_pb.ObjectTransactionResponse, error) {
resp, err := f.ambiguousPutFiler.ObjectTransaction(ctx, req)
if resp != nil && resp.Error == "" {
resp.LogTsNs = f.stamp()
}
return resp, err
}
func (f *stampingFiler) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
resp, err := f.ambiguousPutFiler.UpdateEntry(ctx, req)
if resp != nil {
resp.LogTsNs = f.stamp()
}
return resp, err
}
func (f *stampingFiler) lastStamp() int64 {
return f.last.Load() + time.Date(2026, 11, 30, 0, 0, 0, 0, time.UTC).Add(-f.skew).UnixNano()
}
const testObjectNotificationXML = `<NotificationConfiguration>
<QueueConfiguration><Id>created-in</Id><Queue>arn:aws:sqs:::raw</Queue><Event>s3:ObjectCreated:*</Event>
<Filter><S3Key><FilterRule><Name>prefix</Name><Value>in/</Value></FilterRule></S3Key></Filter></QueueConfiguration>
<QueueConfiguration><Id>puts</Id><Queue>arn:aws:sqs:::orders</Queue><Event>s3:ObjectCreated:Put</Event>
<Filter><S3Key><FilterRule><Name>prefix</Name><Value>out/</Value></FilterRule></S3Key></Filter></QueueConfiguration>
<QueueConfiguration><Id>removed</Id><Queue>arn:aws:sqs:::raw</Queue><Event>s3:ObjectRemoved:*</Event></QueueConfiguration>
<QueueConfiguration><Id>stale</Id><Queue>arn:aws:sqs:::removed-target</Queue><Event>s3:ObjectCreated:*</Event>
<Filter><S3Key><FilterRule><Name>prefix</Name><Value>stale/</Value></FilterRule></S3Key></Filter></QueueConfiguration>
</NotificationConfiguration>`
// withNotifications gives s3a bucket b with testObjectNotificationXML, the
// test targets and a publisher that acks everything.
func withNotifications(t *testing.T, s3a *S3ApiServer, config *BucketConfig) *fakeNotificationPublisher {
t.Helper()
parsed, err := s3notification.ParseConfiguration([]byte(testObjectNotificationXML))
require.NoError(t, err)
config.Name, config.Owner, config.Notification = "b", "owner-id", parsed
if s3a.bucketConfigCache == nil {
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
}
s3a.bucketConfigCache.Set("b", config)
publisher := &fakeNotificationPublisher{}
s3a.notificationPublisher = publisher
require.NoError(t, s3a.loadNotificationTargetsFromBytes([]byte(testNotificationTargets)))
return publisher
}
// eventRecord is the columns of a published record the tests look at.
type eventRecord struct {
Target string
Name, Region, Principal, SourceIP, Owner string
Key, ETag, VersionID string
Size *int64
Sequencer int64
}
// publishedRecords reads each published record, keyed by configuration_id.
// Every record must also render as the JSON a destination receives.
func publishedRecords(t *testing.T, publisher *fakeNotificationPublisher) map[string]eventRecord {
t.Helper()
records := map[string]eventRecord{}
for _, m := range publisher.published() {
v := m.Value
str := func(column string) string { return v.Fields[column].GetStringValue() }
record := eventRecord{
Target: m.Target,
Name: str(s3notification.ColumnEventName), Region: str(s3notification.ColumnAwsRegion),
Principal: str(s3notification.ColumnPrincipalID), SourceIP: str(s3notification.ColumnSourceIP),
Owner: str(s3notification.ColumnBucketOwner), Key: str(s3notification.ColumnObjectKey),
ETag: str(s3notification.ColumnObjectETag), VersionID: str(s3notification.ColumnObjectVersionID),
Sequencer: v.Fields[s3notification.ColumnSequencer].GetInt64Value(),
}
if size, ok := v.Fields[s3notification.ColumnObjectSize]; ok {
n := size.GetInt64Value()
record.Size = &n
}
require.Equal(t, "b/"+record.Key, string(m.Key), "message key")
_, err := s3notification.Render(v)
require.NoError(t, err)
records[str(s3notification.ColumnConfigurationID)] = record
}
return records
}
func TestPublishObjectEventToTheRuleItMatches(t *testing.T) {
s3a := &S3ApiServer{option: &S3ApiServerOption{}}
publisher := withNotifications(t, s3a, &BucketConfig{})
r := httptest.NewRequest(http.MethodPut, "/b/in/x", nil)
r.RemoteAddr = "10.0.3.17:5555"
r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice"))
publish := func(name, key string, logTsNs int64) {
s3a.publishObjectEvent(r, s3notification.Event{Name: name, Bucket: "b", Key: key, Size: 5, ETag: "abc", LogTsNs: logTsNs})
}
publish(s3notification.EventObjectCreatedPut, "in/x", 42)
publish(s3notification.EventObjectCreatedPut, "out/x", 43)
publish(s3notification.EventObjectCreatedCopy, "out/y", 44) // the out/ rule takes only Put
publish(s3notification.EventObjectCreatedPut, "stale/x", 45) // its target no longer resolves
publish(s3notification.EventObjectRemovedDelete, "out/x", 46)
records := publishedRecords(t, publisher)
require.Len(t, records, 3)
for id, want := range map[string]struct {
target, name, key string
sequencer int64
}{
"created-in": {"raw", "ObjectCreated:Put", "in/x", 42},
"puts": {"orders", "ObjectCreated:Put", "out/x", 43},
"removed": {"raw", "ObjectRemoved:Delete", "out/x", 46},
} {
record := records[id]
require.Equal(t, want.target, record.Target, id)
require.Equal(t, want.name, record.Name, id)
require.Equal(t, want.key, record.Key, id)
require.Equal(t, want.sequencer, record.Sequencer, id)
require.Equal(t, "us-east-1", record.Region)
require.Equal(t, "alice", record.Principal)
require.Equal(t, "10.0.3.17", record.SourceIP)
require.Equal(t, "owner-id", record.Owner)
}
}
func TestPublishObjectEventIgnoresAClientSentAccountHeader(t *testing.T) {
s3a := &S3ApiServer{option: &S3ApiServerOption{}}
publisher := withNotifications(t, s3a, &BucketConfig{})
r := httptest.NewRequest(http.MethodPut, "/b/in/x", nil)
r.Header.Set(s3_constants.AmzAccountId, "someone-else")
s3a.publishObjectEvent(r, s3notification.Event{Name: s3notification.EventObjectCreatedPut, Bucket: "b", Key: "in/x", LogTsNs: 1})
require.Equal(t, "anonymous", publishedRecords(t, publisher)["created-in"].Principal)
}
func TestPublishObjectEventWithoutAStampUsesTheGatewayClock(t *testing.T) {
s3a := &S3ApiServer{option: &S3ApiServerOption{}}
publisher := withNotifications(t, s3a, &BucketConfig{})
before := time.Now().UnixNano()
s3a.publishObjectEvent(httptest.NewRequest(http.MethodDelete, "/b/k", nil), s3notification.Event{
Name: s3notification.EventObjectRemovedDelete, Bucket: "b", Key: "k",
})
record := publishedRecords(t, publisher)["removed"]
require.GreaterOrEqual(t, record.Sequencer, before)
}
func TestPublishObjectEventSkipsBucketsWithoutRules(t *testing.T) {
s3a := &S3ApiServer{option: &S3ApiServerOption{}, bucketConfigCache: NewBucketConfigCache(time.Minute)}
publisher := &fakeNotificationPublisher{}
s3a.notificationPublisher = publisher
s3a.bucketConfigCache.Set("plain", &BucketConfig{Name: "plain"})
s3a.publishObjectEvent(httptest.NewRequest(http.MethodPut, "/plain/k", nil), s3notification.Event{
Name: s3notification.EventObjectCreatedPut, Bucket: "plain", Key: "k",
})
require.Empty(t, publisher.published())
}
func TestNoteObjectCommitKeepsTheLatestStamp(t *testing.T) {
r, commit := withObjectCommit(httptest.NewRequest(http.MethodPut, "/b/k", nil))
noteObjectCommit(r.Context(), 20, 5)
noteObjectCommit(r.Context(), 10, 7)
logTsNs, size := commit.noted()
require.Equal(t, int64(20), logTsNs)
require.Equal(t, int64(7), size)
// A request that did not ask for it records nothing and does not panic.
noteObjectCommit(context.Background(), 1, 1)
}
func TestPutToFilerNotesTheCommitStamp(t *testing.T) {
util_http.InitGlobalHttpClient()
for _, routed := range []bool{false, true} {
filerImpl := newStampingFiler(t)
addr := startFakeFiler(t, filerImpl)
s3a := newPutTestServer(t, addr)
if routed {
s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, addr)
s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{addr}, 1)
}
r, commit := withObjectCommit(httptest.NewRequest(http.MethodPut, "/b/o", nil))
_, code, _ := s3a.putToFiler(r, "/buckets/b/o", strings.NewReader("hello world"), "b", "o", 1, 0, nil, false, "")
require.Equal(t, s3err.ErrNone, code)
logTsNs, size := commit.noted()
require.Equal(t, filerImpl.lastStamp(), logTsNs, "routed=%v", routed)
require.Equal(t, int64(len("hello world")), size)
}
}
func TestPutObjectHandlerPublishesObjectCreatedPut(t *testing.T) {
util_http.InitGlobalHttpClient()
filerImpl := newStampingFiler(t)
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
s3a.iam = &IdentityAccessManagement{}
publisher := withNotifications(t, s3a, &BucketConfig{})
r := httptest.NewRequest(http.MethodPut, "/b/in/red%20flower.jpg", strings.NewReader("hello"))
r = mux.SetURLVars(r, map[string]string{"bucket": "b", "object": "in/red flower.jpg"})
w := httptest.NewRecorder()
s3a.PutObjectHandler(w, r)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
records := publishedRecords(t, publisher)
require.Len(t, records, 1)
sum := md5.Sum([]byte("hello"))
object := records["created-in"]
require.Equal(t, "in/red flower.jpg", object.Key)
require.Equal(t, int64(5), *object.Size)
require.Equal(t, hex.EncodeToString(sum[:]), object.ETag)
require.Equal(t, filerImpl.lastStamp(), object.Sequencer)
require.Equal(t, "ObjectCreated:Put", records["created-in"].Name)
}
func TestPutObjectHandlerDoesNotPublishAFailedWrite(t *testing.T) {
util_http.InitGlobalHttpClient()
filerImpl := newStampingFiler(t)
filerImpl.respError = "disk full"
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
s3a.iam = &IdentityAccessManagement{}
publisher := withNotifications(t, s3a, &BucketConfig{})
r := httptest.NewRequest(http.MethodPut, "/b/in/x", strings.NewReader("hello"))
r = mux.SetURLVars(r, map[string]string{"bucket": "b", "object": "in/x"})
w := httptest.NewRecorder()
s3a.PutObjectHandler(w, r)
require.NotEqual(t, http.StatusOK, w.Code)
require.Empty(t, publisher.published())
}
// routedNotificationServer is a gateway whose writes to bucket b route to one
// stamping owner filer, with the test notification rules on b.
func routedNotificationServer(t *testing.T, versioning string) (*S3ApiServer, *stampingFiler, *fakeNotificationPublisher) {
t.Helper()
util_http.InitGlobalHttpClient()
filerImpl := newStampingFiler(t)
addr := startFakeFiler(t, filerImpl)
s3a := newPutTestServer(t, addr)
s3a.iam = &IdentityAccessManagement{}
s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, addr)
s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{addr}, 1)
publisher := withNotifications(t, s3a, &BucketConfig{Versioning: versioning, Ownership: s3_constants.OwnershipObjectWriter})
return s3a, filerImpl, publisher
}
// A suspended delete's marker is written to the gateway's default filer,
// whose clock here runs an hour behind the owner's. The delete's sequencer
// must still follow the PUT's, so it comes from the owner.
func TestSuspendedDeleteIsSequencedOnTheOwner(t *testing.T) {
util_http.InitGlobalHttpClient()
owner := newStampingFiler(t)
other := newStampingFiler(t)
other.volume = owner.volume
other.skew = time.Hour
ownerAddr := startFakeFiler(t, owner)
s3a := newPutTestServer(t, startFakeFiler(t, other))
s3a.iam = &IdentityAccessManagement{}
s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, ownerAddr)
s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{ownerAddr}, 1)
publisher := withNotifications(t, s3a, &BucketConfig{Versioning: s3_constants.VersioningSuspended, Ownership: s3_constants.OwnershipObjectWriter})
for _, f := range []*stampingFiler{owner, other} {
f.entries["/buckets/b/in/x"+s3_constants.VersionsFolder] = &filer_pb.Entry{
Name: "x" + s3_constants.VersionsFolder, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{},
}
}
w := httptest.NewRecorder()
s3a.PutObjectHandler(w, objectRequest(http.MethodPut, "in/x", "", "v1"))
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
deleteObject(t, s3a, "in/x", "")
records := publishedRecords(t, publisher)
put, del := records["created-in"], records["removed"]
require.Equal(t, "ObjectRemoved:DeleteMarkerCreated", del.Name)
require.Greater(t, del.Sequencer, put.Sequencer, "the delete sorts before the PUT it follows")
}
func objectRequest(method, object, query, body string) *http.Request {
target := "/b/" + object
if query != "" {
target += "?" + query
}
r := httptest.NewRequest(method, target, strings.NewReader(body))
return mux.SetURLVars(r, map[string]string{"bucket": "b", "object": object})
}
func TestCopyObjectHandlerPublishesObjectCreatedCopy(t *testing.T) {
for _, versioning := range []string{"", s3_constants.VersioningEnabled, s3_constants.VersioningSuspended} {
t.Run("versioning="+versioning, func(t *testing.T) {
s3a, filerImpl, publisher := routedNotificationServer(t, versioning)
s3a.bucketConfigCache.Set("src", &BucketConfig{Name: "src", Ownership: s3_constants.OwnershipObjectWriter})
filerImpl.entries["/buckets/src/obj"] = &filer_pb.Entry{
Name: "obj", Content: []byte("copied"),
Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: uint64(len("copied"))},
}
r := objectRequest(http.MethodPut, "in/dst", "", "")
r.Header.Set("X-Amz-Copy-Source", "/src/obj")
w := httptest.NewRecorder()
s3a.CopyObjectHandler(w, r)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
record, ok := publishedRecords(t, publisher)["created-in"]
require.True(t, ok, "no record for the copy")
require.Equal(t, "ObjectCreated:Copy", record.Name)
require.Equal(t, "in/dst", record.Key)
require.Equal(t, int64(len("copied")), *record.Size)
sum := md5.Sum([]byte("copied"))
require.Equal(t, hex.EncodeToString(sum[:]), record.ETag)
require.Equal(t, filerImpl.lastStamp(), record.Sequencer)
require.Equal(t, w.Header().Get("x-amz-version-id"), record.VersionID)
})
}
}
func TestSelfCopyPublishesObjectCreatedCopy(t *testing.T) {
s3a, filerImpl, publisher := routedNotificationServer(t, "")
filerImpl.entries["/buckets/b/in/obj"] = &filer_pb.Entry{
Name: "obj", Content: []byte("same"),
Attributes: &filer_pb.FuseAttributes{FileMode: defaultFileMode, FileSize: 4},
}
r := objectRequest(http.MethodPut, "in/obj", "", "")
r.Header.Set("X-Amz-Copy-Source", "/b/in/obj")
r.Header.Set(s3_constants.AmzUserMetaDirective, DirectiveReplace)
r.Header.Set("X-Amz-Meta-Color", "red")
w := httptest.NewRecorder()
s3a.CopyObjectHandler(w, r)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
record, ok := publishedRecords(t, publisher)["created-in"]
require.True(t, ok, "no record for the self-copy")
require.Equal(t, "ObjectCreated:Copy", record.Name)
require.Equal(t, int64(4), *record.Size)
require.Equal(t, filerImpl.lastStamp(), record.Sequencer)
}
func TestCompleteMultipartUploadHandlerPublishesObjectCreated(t *testing.T) {
for _, versioning := range []string{"", s3_constants.VersioningEnabled, s3_constants.VersioningSuspended} {
t.Run("versioning="+versioning, func(t *testing.T) {
s3a, filerImpl, publisher := routedNotificationServer(t, versioning)
out, code := s3a.createMultipartUpload(objectRequest(http.MethodPost, "in/mp", "uploads", ""),
&s3.CreateMultipartUploadInput{Bucket: aws.String("b"), Key: aws.String("in/mp")})
require.Equal(t, s3err.ErrNone, code)
w := httptest.NewRecorder()
s3a.PutObjectPartHandler(w, objectRequest(http.MethodPut, "in/mp", "partNumber=1&uploadId="+*out.UploadId, "multipart body"))
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.Len(t, w.Header()["ETag"], 1)
body := `<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>` + w.Header()["ETag"][0] + `</ETag></Part></CompleteMultipartUpload>`
complete := objectRequest(http.MethodPost, "in/mp", "uploadId="+*out.UploadId, body)
w = httptest.NewRecorder()
s3a.CompleteMultipartUploadHandler(w, complete)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
records := publishedRecords(t, publisher)
require.Len(t, records, 1, "only the ObjectCreated:* rule matches")
record := records["created-in"]
require.Equal(t, "ObjectCreated:CompleteMultipartUpload", record.Name)
require.Equal(t, int64(len("multipart body")), *record.Size)
require.True(t, strings.HasSuffix(record.ETag, "-1"), record.ETag)
require.Equal(t, filerImpl.lastStamp(), record.Sequencer)
require.Equal(t, w.Header().Get("x-amz-version-id"), record.VersionID)
// A retry answered from the committed object creates nothing new.
w = httptest.NewRecorder()
s3a.CompleteMultipartUploadHandler(w, objectRequest(http.MethodPost, "in/mp", "uploadId="+*out.UploadId, body))
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.Len(t, publisher.published(), 1, "a retried completion must not publish again")
})
}
}
func TestRemovedEventName(t *testing.T) {
marker := deleteMutationResult{versionId: "m1", deleteMarker: true, logTsNs: 7}
require.Equal(t, s3notification.EventObjectRemovedDeleteMarkerCreated, removedEvent("b", "k", "", marker).Name)
// Deleting a marker by its version id removes it rather than creating one.
require.Equal(t, s3notification.EventObjectRemovedDelete, removedEvent("b", "k", "m1", marker).Name)
require.Equal(t, s3notification.EventObjectRemovedDelete, removedEvent("b", "k", "", deleteMutationResult{}).Name)
event := removedEvent("b", "k", "", marker)
require.Equal(t, "m1", event.VersionID)
require.Equal(t, int64(7), event.LogTsNs)
}
func deleteObject(t *testing.T, s3a *S3ApiServer, object, versionId string) *httptest.ResponseRecorder {
t.Helper()
query := ""
if versionId != "" {
query = "versionId=" + versionId
}
w := httptest.NewRecorder()
s3a.DeleteObjectHandler(w, objectRequest(http.MethodDelete, object, query, ""))
require.Equal(t, http.StatusNoContent, w.Code, w.Body.String())
return w
}
func TestDeleteObjectHandlerPublishesObjectRemoved(t *testing.T) {
t.Run("unversioned", func(t *testing.T) {
s3a, filerImpl, publisher := routedNotificationServer(t, "")
deleteObject(t, s3a, "in/x", "")
record := publishedRecords(t, publisher)["removed"]
require.Equal(t, "ObjectRemoved:Delete", record.Name)
require.Equal(t, "in/x", record.Key)
require.Nil(t, record.Size)
require.Empty(t, record.VersionID)
require.Equal(t, filerImpl.lastStamp(), record.Sequencer)
})
t.Run("versioned, no version id", func(t *testing.T) {
s3a, filerImpl, publisher := routedNotificationServer(t, s3_constants.VersioningEnabled)
w := deleteObject(t, s3a, "in/x", "")
record := publishedRecords(t, publisher)["removed"]
require.Equal(t, "ObjectRemoved:DeleteMarkerCreated", record.Name)
require.NotEmpty(t, record.VersionID)
require.Equal(t, w.Header().Get("x-amz-version-id"), record.VersionID)
require.Equal(t, filerImpl.lastStamp(), record.Sequencer)
})
t.Run("versioned, one version", func(t *testing.T) {
s3a, filerImpl, publisher := routedNotificationServer(t, s3_constants.VersioningEnabled)
w := httptest.NewRecorder()
s3a.PutObjectHandler(w, objectRequest(http.MethodPut, "in/x", "", "v1"))
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
versionId := w.Header().Get("x-amz-version-id")
publisher.messages = nil
deleteObject(t, s3a, "in/x", versionId)
record := publishedRecords(t, publisher)["removed"]
require.Equal(t, "ObjectRemoved:Delete", record.Name)
require.Equal(t, versionId, record.VersionID)
require.Equal(t, filerImpl.lastStamp(), record.Sequencer)
})
t.Run("suspended, no version id", func(t *testing.T) {
s3a, filerImpl, publisher := routedNotificationServer(t, s3_constants.VersioningSuspended)
filerImpl.entries["/buckets/b/in/x"+s3_constants.VersionsFolder] = &filer_pb.Entry{
Name: "x" + s3_constants.VersionsFolder, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{},
}
deleteObject(t, s3a, "in/x", "")
record := publishedRecords(t, publisher)["removed"]
require.Equal(t, "ObjectRemoved:DeleteMarkerCreated", record.Name)
require.Equal(t, "null", record.VersionID)
})
}
func TestDeleteMultipleObjectsHandlerPublishesOneEventPerKey(t *testing.T) {
s3a, _, publisher := routedNotificationServer(t, "")
body := `<Delete><Object><Key>in/a</Key></Object><Object><Key>in/b c</Key></Object><Object><Key>bad/../x</Key></Object></Delete>`
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/b?delete", strings.NewReader(body))
sum := md5.Sum([]byte(body))
r.Header.Set("Content-Md5", base64.StdEncoding.EncodeToString(sum[:]))
s3a.DeleteMultipleObjectsHandler(w, mux.SetURLVars(r, map[string]string{"bucket": "b"}))
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var keys []string
for _, m := range publisher.published() {
keys = append(keys, string(m.Key))
}
require.ElementsMatch(t, []string{"b/in/a", "b/in/b c"}, keys, "a key that failed to delete publishes nothing")
require.Equal(t, 1, publisher.calls, "the keys' events share one wait")
}
func TestPostPolicyBucketHandlerPublishesObjectCreatedPost(t *testing.T) {
util_http.InitGlobalHttpClient()
filerImpl := newStampingFiler(t)
s3a := newPutTestServer(t, startFakeFiler(t, filerImpl))
s3a.iam = &IdentityAccessManagement{hashes: make(map[string]*sync.Pool), hashCounters: make(map[string]*int32)}
require.NoError(t, s3a.iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{}))
s3a.bucketRegistry = NewBucketRegistry(s3a)
s3a.bucketRegistry.setMetadataCache(&BucketMetaData{Name: "b"})
publisher := withNotifications(t, s3a, &BucketConfig{})
now := time.Now().UTC()
policy := fmt.Sprintf(`{"expiration":"%s","conditions":[["eq","$key","in/post.txt"]]}`, now.Add(time.Hour).Format("2006-01-02T15:04:05.000Z"))
var buf bytes.Buffer
form := multipart.NewWriter(&buf)
for name, value := range map[string]string{
"key": "in/post.txt",
"x-amz-credential": fmt.Sprintf("ANYKEY/%s/us-east-1/s3/aws4_request", now.Format(yyyymmdd)),
"x-amz-algorithm": "AWS4-HMAC-SHA256",
"x-amz-date": now.Format(iso8601Format),
"policy": base64.StdEncoding.EncodeToString([]byte(policy)),
"x-amz-signature": "00",
} {
require.NoError(t, form.WriteField(name, value))
}
file, err := form.CreateFormFile("file", "post.txt")
require.NoError(t, err)
_, err = file.Write([]byte("posted"))
require.NoError(t, err)
require.NoError(t, form.Close())
r := httptest.NewRequest(http.MethodPost, "/b", &buf)
r.Header.Set("Content-Type", form.FormDataContentType())
r = mux.SetURLVars(r, map[string]string{"bucket": "b"})
w := httptest.NewRecorder()
s3a.PostPolicyBucketHandler(w, r)
require.Equal(t, http.StatusNoContent, w.Code, w.Body.String())
records := publishedRecords(t, publisher)
require.Len(t, records, 1, "only the ObjectCreated:* rule matches a POST")
record := records["created-in"]
require.Equal(t, "ObjectCreated:Post", record.Name)
require.Equal(t, int64(len("posted")), *record.Size)
require.Equal(t, filerImpl.lastStamp(), record.Sequencer)
}
+20 -15
View File
@@ -237,8 +237,8 @@ func (s3a *S3ApiServer) routedPut(owner pb.ServerAddress, routeKey, lockKey, fil
// default filer (e.g. multipart completion of a non-versioned object). cond is
// the request's write condition, evaluated on the object under the transaction
// lock; condAltKey falls back to the .versions directory when the object slot
// is empty (suspended or versioned buckets).
func (s3a *S3ApiServer) routedMkFile(owner pb.ServerAddress, routeKey, parentDir, name string, chunks []*filer_pb.FileChunk, fn func(*filer_pb.Entry), removal *uploadRemovalTxn, cond *filer_pb.WriteCondition, condAltKey string) error {
// is empty (suspended or versioned buckets). It returns the commit's filer stamp.
func (s3a *S3ApiServer) routedMkFile(owner pb.ServerAddress, routeKey, parentDir, name string, chunks []*filer_pb.FileChunk, fn func(*filer_pb.Entry), removal *uploadRemovalTxn, cond *filer_pb.WriteCondition, condAltKey string) (int64, error) {
now := time.Now().Unix()
entry := &filer_pb.Entry{
Name: name,
@@ -264,7 +264,7 @@ func (s3a *S3ApiServer) routedMkFile(owner pb.ServerAddress, routeKey, parentDir
}
resp, err := s3a.routedPut(owner, routeKey, filePath, filePath, entry, cond, "", condAltKey, false, putCondition, putConditionKey, finalize)
if err != nil {
return err
return 0, err
}
if resp.ErrorCode == filer_pb.FilerError_EXISTING_IS_DIRECTORY && !isReservedDirectoryName(name) {
// Other keys are nested under this one, so the object goes onto the
@@ -272,19 +272,19 @@ func (s3a *S3ApiServer) routedMkFile(owner pb.ServerAddress, routeKey, parentDir
entry.MarkPrefixObject()
resp, err = s3a.routedPut(owner, routeKey, filePath, filePath, entry, cond, "", condAltKey, false, putCondition, putConditionKey, finalize)
if err != nil {
return err
return 0, err
}
}
if resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED {
if resp.FailedMutation == nil {
return errObjectPrecondition
return 0, errObjectPrecondition
}
return errUploadRemoved
return 0, errUploadRemoved
}
if resp.Error != "" {
return fmt.Errorf("routed mkfile %s/%s: %s", parentDir, name, resp.Error)
return 0, fmt.Errorf("routed mkfile %s/%s: %s", parentDir, name, resp.Error)
}
return nil
return resp.LogTsNs, nil
}
// errUploadRemoved is a routed commit rejected because the upload directory's
@@ -304,12 +304,12 @@ var errObjectPrecondition = errors.New("object precondition failed")
// selection and forwarding stay consistent. cond is the request's write
// condition, enforced on the owner under the transaction lock; condAltKey is
// the .versions directory a conditional check falls back to when the bucket
// tracks versions.
func (s3a *S3ApiServer) writeMultipartObject(owner pb.ServerAddress, routeKey, dir, name string, chunks []*filer_pb.FileChunk, fn func(*filer_pb.Entry), removal *uploadRemovalTxn, cond *filer_pb.WriteCondition, condAltKey string) error {
// tracks versions. It returns the commit's filer stamp, 0 off the owner.
func (s3a *S3ApiServer) writeMultipartObject(owner pb.ServerAddress, routeKey, dir, name string, chunks []*filer_pb.FileChunk, fn func(*filer_pb.Entry), removal *uploadRemovalTxn, cond *filer_pb.WriteCondition, condAltKey string) (int64, error) {
if owner != "" {
return s3a.routedMkFile(owner, routeKey, dir, name, chunks, fn, removal, cond, condAltKey)
}
return s3a.mkFile(dir, name, chunks, fn)
return 0, s3a.mkFile(dir, name, chunks, fn)
}
// uploadRemovalTxn carries the PUT precondition and mutation that drop a
@@ -370,7 +370,8 @@ func (s3a *S3ApiServer) routedDelete(owner pb.ServerAddress, bucket, object stri
// source snapshot. UpdateEntry routes conditional writes to the owner and checks
// the condition under its path lock, so concurrent content, ACL or retention
// updates cannot be overwritten by a stale self-copy. Chunks are reused in place.
func (s3a *S3ApiServer) routedSelfCopy(ctx context.Context, owner pb.ServerAddress, bucket, object string, current, updated *filer_pb.Entry) error {
// It returns the update's filer stamp.
func (s3a *S3ApiServer) routedSelfCopy(ctx context.Context, owner pb.ServerAddress, bucket, object string, current, updated *filer_pb.Entry) (int64, error) {
fullpath := util.NewFullPath(s3a.bucketDir(bucket), object)
dir, _ := fullpath.DirAndName()
req := &filer_pb.UpdateEntryRequest{
@@ -382,9 +383,13 @@ func (s3a *S3ApiServer) routedSelfCopy(ctx context.Context, owner pb.ServerAddre
}}},
}
var conditionErr error
var logTsNs int64
update := func(client filer_pb.SeaweedFilerClient) error {
err := filer_pb.UpdateEntry(ctx, client, req)
resp, err := filer_pb.UpdateEntryWithResponse(ctx, client, req)
switch status.Code(err) {
case codes.OK:
logTsNs = resp.LogTsNs
return nil
case codes.FailedPrecondition, codes.NotFound:
// These are authoritative replies from a healthy owner, not a
// transport failure. Do not replay them or mark the owner down.
@@ -401,7 +406,7 @@ func (s3a *S3ApiServer) routedSelfCopy(ctx context.Context, owner pb.ServerAddre
err = s3a.withFilerClientFailover(ctx, owner, false, false, update)
}
if err != nil {
return err
return 0, err
}
return conditionErr
return logTsNs, conditionErr
}
+16 -16
View File
@@ -360,7 +360,7 @@ func TestRoutedDeleteSpecificVersionUsesWormCondition(t *testing.T) {
},
}
if code := s3a.routedDeleteSpecificVersion(owner, "b", "obj", versionId, true, false, false, nil); code != s3err.ErrAccessDenied {
if _, code := s3a.routedDeleteSpecificVersion(owner, "b", "obj", versionId, true, false, false, nil); code != s3err.ErrAccessDenied {
t.Fatalf("locked version delete returned %v, want %v", code, s3err.ErrAccessDenied)
}
@@ -431,7 +431,7 @@ func TestRoutedDeleteSpecificVersionGuardsRepoint(t *testing.T) {
t.Run("one transaction behind the version's lock checks", func(t *testing.T) {
filer := &fakeTxnFiler{}
owner := startFakeFiler(t, filer)
if code := newS3a().routedDeleteSpecificVersion(owner, "b", "obj", versionId, false, false, false, nil); code != s3err.ErrNone {
if _, code := newS3a().routedDeleteSpecificVersion(owner, "b", "obj", versionId, false, false, false, nil); code != s3err.ErrNone {
t.Fatalf("delete returned %v, want %v", code, s3err.ErrNone)
}
if len(filer.reqs) != 1 {
@@ -452,7 +452,7 @@ func TestRoutedDeleteSpecificVersionGuardsRepoint(t *testing.T) {
t.Run("metadata-only delete keeps the data", func(t *testing.T) {
filer := &fakeTxnFiler{}
owner := startFakeFiler(t, filer)
if code := newS3a().routedDeleteSpecificVersion(owner, "b", "obj", versionId, false, false, true, nil); code != s3err.ErrNone {
if _, code := newS3a().routedDeleteSpecificVersion(owner, "b", "obj", versionId, false, false, true, nil); code != s3err.ErrNone {
t.Fatalf("delete returned %v, want %v", code, s3err.ErrNone)
}
if filer.lastReq.Mutations[1].IsDeleteData {
@@ -599,7 +599,7 @@ func TestRoutedMultipartFinalize(t *testing.T) {
}
chunks := []*filer_pb.FileChunk{{FileId: "1,01637037d6"}}
code := s3a.routedMultipartFinalize(owner, "b", "obj", false, "/buckets/b/obj.versions", "v_1", chunks, func(entry *filer_pb.Entry) {
_, code := s3a.routedMultipartFinalize(owner, "b", "obj", false, "/buckets/b/obj.versions", "v_1", chunks, func(entry *filer_pb.Entry) {
entry.Extended = map[string][]byte{s3_constants.SeaweedFSUploadId: []byte("up1")}
}, "up1", clause(filer_pb.WriteCondition_IF_NOT_EXISTS))
if code != s3err.ErrNone {
@@ -676,7 +676,7 @@ func TestWriteMultipartObjectRemovesUploadDir(t *testing.T) {
if err != nil {
t.Fatalf("routedUploadRemoval: %v", err)
}
if err := s3a.writeMultipartObject(owner, "s3.object.write:/buckets/b/o", "/buckets/b", "o", nil, nil, removal, nil, ""); err != nil {
if _, err := s3a.writeMultipartObject(owner, "s3.object.write:/buckets/b/o", "/buckets/b", "o", nil, nil, removal, nil, ""); err != nil {
t.Fatalf("writeMultipartObject: %v", err)
}
@@ -770,7 +770,7 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
t.Run("version/"+tc.name, func(t *testing.T) {
filer := &fakeTxnFiler{resp: tc.resp}
owner := startFakeFiler(t, filer)
if code := newS3a().routedDeleteSpecificVersion(owner, "b", "obj", versionId, true, false, false, ifMatch); code != tc.want {
if _, code := newS3a().routedDeleteSpecificVersion(owner, "b", "obj", versionId, true, false, false, ifMatch); code != tc.want {
t.Fatalf("delete returned %v, want %v", code, tc.want)
}
if filer.lastReq.Mutations[0].Type != filer_pb.ObjectMutation_RECOMPUTE_LATEST {
@@ -781,7 +781,7 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
t.Run("null/"+tc.name, func(t *testing.T) {
filer := &fakeTxnFiler{resp: tc.resp}
owner := startFakeFiler(t, filer)
code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", true, false, false, ifMatch)
_, code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", true, false, false, ifMatch)
if !settled || code != tc.want {
t.Fatalf("delete returned (%v, %v), want (%v, true)", code, settled, tc.want)
}
@@ -793,10 +793,10 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
t.Run("null/transport error", func(t *testing.T) {
filer := &fakeTxnFiler{err: status.Error(codes.Unavailable, "response lost")}
owner := startFakeFiler(t, filer)
if code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, ifMatch); !settled || code != s3err.ErrInternalError {
if _, code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, ifMatch); !settled || code != s3err.ErrInternalError {
t.Fatalf("conditional delete returned (%v, %v), want (%v, true)", code, settled, s3err.ErrInternalError)
}
if code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, nil); settled || code != s3err.ErrNone {
if _, code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, nil); settled || code != s3err.ErrNone {
t.Fatalf("unconditional delete returned (%v, %v), want a lock-path fallback", code, settled)
}
})
@@ -809,10 +809,10 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
} {
fake := &fakeTxnFiler{resp: &filer_pb.ObjectTransactionResponse{Error: msg, FailedMutation: &firstMutation}}
owner := startFakeFiler(t, fake)
if code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, ifMatch); !settled || code != s3err.ErrInternalError {
if _, code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, ifMatch); !settled || code != s3err.ErrInternalError {
t.Fatalf("%q: conditional delete returned (%v, %v), want (%v, true)", msg, code, settled, s3err.ErrInternalError)
}
if code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, nil); settled || code != s3err.ErrNone {
if _, code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, nil); settled || code != s3err.ErrNone {
t.Fatalf("%q: unconditional delete returned (%v, %v), want a lock-path fallback", msg, code, settled)
}
}
@@ -843,7 +843,7 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
} {
fake := &fakeNestedFiler{entry: tc.entry, demote: tc.demote}
owner := startFakeFiler(t, fake)
if code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", true, false, false, ifMatch); !settled || code != tc.want {
if _, code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", true, false, false, ifMatch); !settled || code != tc.want {
t.Fatalf("%s: delete returned (%v, %v), want (%v, true)", tc.name, code, settled, tc.want)
}
if len(fake.reqs) != tc.txns {
@@ -871,7 +871,7 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
}
fake := &fakeNestedFiler{entry: object}
owner := startFakeFiler(t, fake)
if code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, nil); settled || code != s3err.ErrNone || len(fake.reqs) != 1 {
if _, code, settled := newS3a().routedDeleteNullVersion(owner, "b", "obj", false, false, false, nil); settled || code != s3err.ErrNone || len(fake.reqs) != 1 {
t.Fatalf("unconditional delete returned (%v, %v) after %d transactions, want a lock-path fallback", code, settled, len(fake.reqs))
}
})
@@ -886,12 +886,12 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
}
}
del := &fakeTxnFiler{}
if code, settled := newS3a().routedDeleteNullVersion(startFakeFiler(t, del), "b", "obj", false, false, false, star); !settled || code != s3err.ErrNone {
if _, code, settled := newS3a().routedDeleteNullVersion(startFakeFiler(t, del), "b", "obj", false, false, false, star); !settled || code != s3err.ErrNone {
t.Fatalf("delete returned (%v, %v), want (%v, true)", code, settled, s3err.ErrNone)
}
objectKind(t, del.lastReq.Mutations[0])
nested := &fakeNestedFiler{entry: &filer_pb.Entry{Name: "obj", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "text/plain"}}}
if code, settled := newS3a().routedDeleteNullVersion(startFakeFiler(t, nested), "b", "obj", false, false, false, star); !settled || code != s3err.ErrNone || len(nested.reqs) != 2 {
if _, code, settled := newS3a().routedDeleteNullVersion(startFakeFiler(t, nested), "b", "obj", false, false, false, star); !settled || code != s3err.ErrNone || len(nested.reqs) != 2 {
t.Fatalf("nested delete returned (%v, %v) after %d transactions, want a demote", code, settled, len(nested.reqs))
}
objectKind(t, nested.reqs[0].Mutations[0])
@@ -914,7 +914,7 @@ func TestRoutedVersionDeleteCarriesIfMatch(t *testing.T) {
{"absent", nil, s3err.ErrPreconditionFailed, 0},
} {
old := &fakeNestedFiler{entry: tc.entry, first: guardFailed}
if code, settled := newS3a().routedDeleteNullVersion(startFakeFiler(t, old), "b", "obj", false, false, false, star); !settled || code != tc.want {
if _, code, settled := newS3a().routedDeleteNullVersion(startFakeFiler(t, old), "b", "obj", false, false, false, star); !settled || code != tc.want {
t.Fatalf("older filer, %s: delete returned (%v, %v), want (%v, true)", tc.name, code, settled, tc.want)
}
if tc.want != s3err.ErrNone {
+49 -43
View File
@@ -75,8 +75,9 @@ func (s3a *S3ApiServer) latestPointerRecompute(bucket, object string, useInverte
// into .versions in the same transaction, so the recompute's scan sees it even
// when the gateway's own filer is not the owner; otherwise the version file is
// already written on the owner. latestGuard, when set, must hold on the
// .versions directory entry under the same lock.
func (s3a *S3ApiServer) routedVersionedFinalize(owner pb.ServerAddress, bucket, object string, useInvertedFormat bool, versionEntry *filer_pb.Entry, latestGuard *filer_pb.WriteCondition) s3err.ErrorCode {
// .versions directory entry under the same lock. It returns the commit's
// filer stamp.
func (s3a *S3ApiServer) routedVersionedFinalize(owner pb.ServerAddress, bucket, object string, useInvertedFormat bool, versionEntry *filer_pb.Entry, latestGuard *filer_pb.WriteCondition) (int64, s3err.ErrorCode) {
mutations := []*filer_pb.ObjectMutation{s3a.latestPointerRecompute(bucket, object, useInvertedFormat, "", true)}
if versionEntry != nil {
mutations = append([]*filer_pb.ObjectMutation{{
@@ -98,14 +99,14 @@ func (s3a *S3ApiServer) routedVersionedFinalize(owner pb.ServerAddress, bucket,
switch {
case err != nil:
glog.Errorf("routedVersionedFinalize: %s/%s on %s: %v", bucket, object, owner, err)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
return s3err.ErrPreconditionFailed
return 0, s3err.ErrPreconditionFailed
case resp.Error != "":
glog.Errorf("routedVersionedFinalize: %s/%s: %s", bucket, object, resp.Error)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
default:
return s3err.ErrNone
return resp.LogTsNs, s3err.ErrNone
}
}
@@ -140,8 +141,9 @@ func uploadExistsCondition(uploadDirectory string) (string, *filer_pb.WriteCondi
// coexists with a leftover .uploads directory that s3.clean.uploads would purge
// with data. cond is the request's write condition, checked against the object
// (its latest version when the slot at the object path is empty) under the same
// lock; the upload directory rides the PUT as a mutation precondition.
func (s3a *S3ApiServer) routedMultipartFinalize(owner pb.ServerAddress, bucket, object string, useInvertedFormat bool, versionDir, versionFileName string, chunks []*filer_pb.FileChunk, decorate func(*filer_pb.Entry), uploadID string, cond *filer_pb.WriteCondition) s3err.ErrorCode {
// lock; the upload directory rides the PUT as a mutation precondition. It
// returns the commit's filer stamp.
func (s3a *S3ApiServer) routedMultipartFinalize(owner pb.ServerAddress, bucket, object string, useInvertedFormat bool, versionDir, versionFileName string, chunks []*filer_pb.FileChunk, decorate func(*filer_pb.Entry), uploadID string, cond *filer_pb.WriteCondition) (int64, s3err.ErrorCode) {
now := time.Now().Unix()
versionEntry := &filer_pb.Entry{
Name: versionFileName,
@@ -166,7 +168,7 @@ func (s3a *S3ApiServer) routedMultipartFinalize(owner pb.ServerAddress, bucket,
// putCondition, so on upgrade the guard degrades to this gateway-side
// check — the same window the pre-transaction code had.
if exists, err := s3a.uploadFiler(bucket, object).exists(s3a.genUploadsFolder(bucket), uploadID, true); err == nil && !exists {
return s3err.ErrNoSuchUpload
return 0, s3err.ErrNoSuchUpload
}
putConditionKey, putCondition := uploadExistsCondition(s3a.genUploadsFolder(bucket) + "/" + uploadID)
resp, err := s3a.routedPut(owner, routeKey, s3a.toFilerPath(bucket, object), versionDir+"/"+versionFileName, versionEntry, cond, "", versionDir, true, putCondition, putConditionKey, []*filer_pb.ObjectMutation{
@@ -176,17 +178,17 @@ func (s3a *S3ApiServer) routedMultipartFinalize(owner pb.ServerAddress, bucket,
switch {
case err != nil:
glog.Errorf("routedMultipartFinalize: %s/%s upload %s on %s: %v", bucket, object, uploadID, owner, err)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
if resp.FailedMutation == nil {
return s3err.ErrPreconditionFailed
return 0, s3err.ErrPreconditionFailed
}
return s3err.ErrNoSuchUpload
return 0, s3err.ErrNoSuchUpload
case resp.Error != "":
glog.Errorf("routedMultipartFinalize: %s/%s upload %s: %s", bucket, object, uploadID, resp.Error)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
default:
return s3err.ErrNone
return resp.LogTsNs, s3err.ErrNone
}
}
@@ -218,10 +220,10 @@ func wormDeleteCondition(worm, bypass bool) *filer_pb.WriteCondition {
// alone, since it can point at an older version than a re-derive would pick, or
// at nothing, as when a suspended bucket's null write cleared it while the null
// object stays current. ifMatch, when set, guards the version under the same
// lock and fails before anything applies.
func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, bucket, object, versionId string, worm, bypass, metadataOnly bool, ifMatch *filer_pb.WriteCondition) s3err.ErrorCode {
// lock and fails before anything applies. It returns the commit's filer stamp.
func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, bucket, object, versionId string, worm, bypass, metadataOnly bool, ifMatch *filer_pb.WriteCondition) (int64, s3err.ErrorCode) {
if !isValidVersionID(versionId) {
return s3err.ErrInvalidRequest
return 0, s3err.ErrInvalidRequest
}
versionFileName := s3a.getVersionFileName(versionId)
recompute := s3a.latestPointerRecompute(bucket, object, isNewFormatVersionId(versionId), versionFileName, false)
@@ -245,18 +247,18 @@ func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, buck
switch {
case err != nil:
glog.Errorf("routedDeleteSpecificVersion: %s/%s %s on %s: %v", bucket, object, versionId, owner, err)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
if resp.FailedMutation != nil {
return s3err.ErrPreconditionFailed
return 0, s3err.ErrPreconditionFailed
}
// Legal hold or retention in force on the version.
return s3err.ErrAccessDenied
return 0, s3err.ErrAccessDenied
case resp.Error != "":
glog.Errorf("routedDeleteSpecificVersion: %s/%s %s: %s", bucket, object, versionId, resp.Error)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
default:
return s3err.ErrNone
return resp.LogTsNs, s3err.ErrNone
}
}
@@ -269,8 +271,9 @@ func (s3a *S3ApiServer) routedDeleteSpecificVersion(owner pb.ServerAddress, buck
// ifMatch, when set, guards the delete itself and keeps the whole decision on
// the owner: the lock path does not exclude routed deletes, so a nested entry
// is stripped there under the same guard, and any other failure settles as
// one, since the transaction may have committed.
func (s3a *S3ApiServer) routedDeleteNullVersion(owner pb.ServerAddress, bucket, object string, worm, bypass, metadataOnly bool, ifMatch *filer_pb.WriteCondition) (s3err.ErrorCode, bool) {
// one, since the transaction may have committed. The first return is the
// commit's filer stamp.
func (s3a *S3ApiServer) routedDeleteNullVersion(owner pb.ServerAddress, bucket, object string, worm, bypass, metadataOnly bool, ifMatch *filer_pb.WriteCondition) (int64, s3err.ErrorCode, bool) {
fullpath := util.NewFullPath(s3a.bucketDir(bucket), object)
dir, name := fullpath.DirAndName()
guard, star := nullVersionCondition(ifMatch)
@@ -285,27 +288,29 @@ func (s3a *S3ApiServer) routedDeleteNullVersion(owner pb.ServerAddress, bucket,
switch {
case err != nil && ifMatch != nil:
glog.Errorf("routedDeleteNullVersion: %s/%s on %s: %v", bucket, object, owner, err)
return s3err.ErrInternalError, true
return 0, s3err.ErrInternalError, true
case err != nil:
glog.Warningf("routedDeleteNullVersion: %s/%s on %s, falling back to lock: %v", bucket, object, owner, err)
return s3err.ErrNone, false
return 0, s3err.ErrNone, false
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED && resp.FailedMutation == nil:
return s3err.ErrAccessDenied, true
return 0, s3err.ErrAccessDenied, true
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED && star:
// A filer that predates IF_OBJECT_EXISTS fails it closed.
return s3a.routedDemoteNullVersion(owner, bucket, object, worm, bypass, metadataOnly, ifMatch), true
logTsNs, code := s3a.routedDemoteNullVersion(owner, bucket, object, worm, bypass, metadataOnly, ifMatch)
return logTsNs, code, true
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
return s3err.ErrPreconditionFailed, true
return 0, s3err.ErrPreconditionFailed, true
case resp.Error != "" && ifMatch != nil && ownerRefusedNonEmpty(resp):
return s3a.routedDemoteNullVersion(owner, bucket, object, worm, bypass, metadataOnly, ifMatch), true
logTsNs, code := s3a.routedDemoteNullVersion(owner, bucket, object, worm, bypass, metadataOnly, ifMatch)
return logTsNs, code, true
case resp.Error != "" && ifMatch != nil:
glog.Errorf("routedDeleteNullVersion: %s/%s on %s returned %q", bucket, object, owner, resp.Error)
return s3err.ErrInternalError, true
return 0, s3err.ErrInternalError, true
case resp.Error != "":
glog.Warningf("routedDeleteNullVersion: %s/%s returned %q, falling back to lock", bucket, object, resp.Error)
return s3err.ErrNone, false
return 0, s3err.ErrNone, false
default:
return s3err.ErrNone, true
return resp.LogTsNs, s3err.ErrNone, true
}
}
@@ -313,19 +318,20 @@ func (s3a *S3ApiServer) routedDeleteNullVersion(owner pb.ServerAddress, bucket,
// the owner: a directory, which other keys may be nested under, is stripped as
// the lock path's demote does, and a file is deleted. The write is guarded by
// ifMatch and by the entry it was derived from, so once the last nested key is
// gone a concurrent routed delete cannot pass the same check.
func (s3a *S3ApiServer) routedDemoteNullVersion(owner pb.ServerAddress, bucket, object string, worm, bypass, metadataOnly bool, ifMatch *filer_pb.WriteCondition) s3err.ErrorCode {
// gone a concurrent routed delete cannot pass the same check. It returns the
// commit's filer stamp.
func (s3a *S3ApiServer) routedDemoteNullVersion(owner pb.ServerAddress, bucket, object string, worm, bypass, metadataOnly bool, ifMatch *filer_pb.WriteCondition) (int64, s3err.ErrorCode) {
fullpath := util.NewFullPath(s3a.bucketDir(bucket), object)
dir, name := fullpath.DirAndName()
entry, err := s3a.lookupEntryOnFiler(context.Background(), owner, dir, name)
switch {
case errors.Is(err, filer_pb.ErrNotFound):
return s3err.ErrPreconditionFailed
return 0, s3err.ErrPreconditionFailed
case err != nil:
glog.Errorf("routedDemoteNullVersion: %s/%s on %s: %v", bucket, object, owner, err)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
case entry.IsDirectory && !entry.IsDirectoryKeyObject():
return s3err.ErrPreconditionFailed
return 0, s3err.ErrPreconditionFailed
}
guard := &filer_pb.WriteCondition{Clauses: append(slices.Clone(ifMatch.GetClauses()),
&filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: proto.Clone(entry).(*filer_pb.Entry)})}
@@ -343,17 +349,17 @@ func (s3a *S3ApiServer) routedDemoteNullVersion(owner pb.ServerAddress, bucket,
switch {
case err != nil:
glog.Errorf("routedDemoteNullVersion: %s/%s on %s: %v", bucket, object, owner, err)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
if resp.FailedMutation != nil {
return s3err.ErrPreconditionFailed
return 0, s3err.ErrPreconditionFailed
}
return s3err.ErrAccessDenied
return 0, s3err.ErrAccessDenied
case resp.Error != "":
glog.Errorf("routedDemoteNullVersion: %s/%s on %s returned %q", bucket, object, owner, resp.Error)
return s3err.ErrInternalError
return 0, s3err.ErrInternalError
default:
return s3err.ErrNone
return resp.LogTsNs, s3err.ErrNone
}
}
@@ -70,7 +70,7 @@ func TestVersionedConditionalPutAfterLockWaitBecomesLatest(t *testing.T) {
s3a.newObjectWriteLock = func(bucket, object string) (objectWriteLock, error) {
if markerId == "" {
var err error
if markerId, err = s3a.createDeleteMarker(bucket, object); err != nil {
if markerId, _, err = s3a.createDeleteMarker(bucket, object); err != nil {
t.Fatalf("create delete marker: %v", err)
}
}
+12 -10
View File
@@ -205,15 +205,17 @@ type ObjectVersion struct {
// errLatestVersionChanged reports a delete marker refused by its latestGuard.
var errLatestVersionChanged = errors.New("latest version changed")
// createDeleteMarker creates a delete marker for versioned delete operations
func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, error) {
// createDeleteMarker creates a delete marker for versioned delete operations,
// returning its version id and the filer's stamp of the routed commit, 0 off
// the owner.
func (s3a *S3ApiServer) createDeleteMarker(bucket, object string) (string, int64, error) {
return s3a.createDeleteMarkerIf(bucket, object, nil)
}
// createDeleteMarkerIf is createDeleteMarker whose routed commit also requires
// latestGuard to hold on the .versions directory entry. The unrouted path
// has no transaction to check it in and writes unconditionally.
func (s3a *S3ApiServer) createDeleteMarkerIf(bucket, object string, latestGuard *filer_pb.WriteCondition) (string, error) {
func (s3a *S3ApiServer) createDeleteMarkerIf(bucket, object string, latestGuard *filer_pb.WriteCondition) (string, int64, error) {
// Clean up the object path first
cleanObject := strings.TrimPrefix(object, "/")
@@ -250,15 +252,15 @@ func (s3a *S3ApiServer) createDeleteMarkerIf(bucket, object string, latestGuard
},
Extended: deleteMarkerExtended,
}
code := s3a.routedVersionedFinalize(owner, bucket, cleanObject, useInvertedFormat, deleteMarkerEntry, latestGuard)
logTsNs, code := s3a.routedVersionedFinalize(owner, bucket, cleanObject, useInvertedFormat, deleteMarkerEntry, latestGuard)
if code == s3err.ErrPreconditionFailed {
return "", errLatestVersionChanged
return "", 0, errLatestVersionChanged
}
if code != s3err.ErrNone {
return "", fmt.Errorf("createDeleteMarker: routed finalize failed for %s/%s: code %d", bucket, object, code)
return "", 0, fmt.Errorf("createDeleteMarker: routed finalize failed for %s/%s: code %d", bucket, object, code)
}
glog.V(2).Infof("createDeleteMarker: successfully created delete marker %s for %s/%s", versionId, bucket, object)
return versionId, nil
return versionId, logTsNs, nil
}
err := s3a.mkFile(versionsDir, versionFileName, nil, func(entry *filer_pb.Entry) {
@@ -275,7 +277,7 @@ func (s3a *S3ApiServer) createDeleteMarkerIf(bucket, object string, latestGuard
}
})
if err != nil {
return "", fmt.Errorf("failed to create delete marker in .versions directory: %w", err)
return "", 0, fmt.Errorf("failed to create delete marker in .versions directory: %w", err)
}
// Update the .versions directory metadata to indicate this delete marker is the latest version
@@ -290,11 +292,11 @@ func (s3a *S3ApiServer) createDeleteMarkerIf(bucket, object string, latestGuard
}
if err = s3a.updateLatestVersionInDirectory(bucket, cleanObject, versionId, versionFileName, deleteMarkerEntry); err != nil {
glog.Errorf("createDeleteMarker: failed to update latest version in directory: %v", err)
return "", fmt.Errorf("failed to update latest version in directory: %w", err)
return "", 0, fmt.Errorf("failed to update latest version in directory: %w", err)
}
glog.V(2).Infof("createDeleteMarker: successfully created delete marker %s for %s/%s", versionId, bucket, object)
return versionId, nil
return versionId, 0, nil
}
// createNullDeleteMarker records a suspended-versioning delete as a single "null"
+9 -1
View File
@@ -105,6 +105,9 @@ type S3ApiServerOption struct {
// VolumeLookupTimeout bounds each filer's answer to a volume location
// lookup before the next filer is asked. 0 uses the FilerClient default.
VolumeLookupTimeout time.Duration
// MqBroker is the message queue broker running beside this gateway, the
// first one bucket events are published through; empty when none runs.
MqBroker pb.ServerAddress
}
// s3ChunkCacheChunkSizeMB is the assumed chunk size (in MiB) used to convert
@@ -166,7 +169,8 @@ type S3ApiServer struct {
versionsHealQueue *versionsHealQueue
versionsReconcilerStop func()
notificationTargets atomic.Pointer[s3notification.Registry]
notificationTargets atomic.Pointer[s3notification.Registry]
notificationPublisher notificationPublisher
}
type objectWriteLock interface {
@@ -583,6 +587,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
if dir := s3ApiServer.roleStoreDir(); !slices.Contains(watched, dir) {
watched = append(watched, dir)
}
s3ApiServer.notificationPublisher = s3ApiServer.newNotificationPublisher()
s3ApiServer.loadNotificationTargets()
go s3ApiServer.subscribeMetaEvents("s3", startTsNs, filer.DirectoryEtcRoot, watched)
@@ -626,6 +631,9 @@ func (s3a *S3ApiServer) Shutdown() {
if s3a.iam != nil {
s3a.iam.Shutdown()
}
if s3a.notificationPublisher != nil {
s3a.notificationPublisher.Close()
}
}
// getFilerAddress returns the current active filer address
+440
View File
@@ -0,0 +1,440 @@
package s3notification
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/client/pub_client"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"google.golang.org/grpc"
)
const (
TopicPartitionCount = 4
TopicRetention = 7 * 24 * time.Hour
// AckWait bounds how long a request waits for its records to be acked
// before it answers anyway; the records stay queued and are still sent.
AckWait = 2 * time.Second
// QueueSize bounds the records per target not yet handed to the MQ
// publisher, which itself holds up to 1024 unacked per partition. A record
// arriving at a full queue is dropped and counted.
QueueSize = 10000
setupMinBackoff = 500 * time.Millisecond
// A broker that just started holds topic operations for about 20s while
// it takes the balancer lock; setup keeps retrying through that.
setupMaxBackoff = 10 * time.Second
// configureTimeout bounds one broker's ConfigureTopic, so a broker that
// accepts the call and hangs passes setup on to the next.
configureTimeout = 10 * time.Second
dropLogInterval = 10 * time.Second
)
// Message is one record for one target's topic.
type Message struct {
Target string
Key []byte
Value *schema_pb.RecordValue
}
// topicPublisher is what Publisher needs from pub_client.TopicPublisher.
type topicPublisher interface {
PublishRecord(key []byte, value *schema_pb.RecordValue) (<-chan struct{}, error)
Shutdown() error
}
// Publisher sends bucket event records to the MQ topic of each target, one
// worker per target. A target's topic is created when the target appears and
// left alone when it goes: retention ages it out, and a forwarder may still be
// draining it.
type Publisher struct {
brokers func() []string
grpcDialOption grpc.DialOption
ackWait time.Duration
queueSize int
configureTimeout time.Duration
configureTopic func(ctx context.Context, t topic.Topic) error
newTopicPublisher func(ctx context.Context, t topic.Topic) (topicPublisher, error)
mu sync.Mutex
targets map[string]*targetWorker
closed bool
}
type targetWorker struct {
name string
topic topic.Topic
queue chan *pendingRecord
cancel context.CancelFunc
done chan struct{}
lastDropLog atomic.Int64
mu sync.Mutex
stopped bool
publisher topicPublisher
afterDropSettled func() // test hook between a drop's count and its done
}
// A record's terminal outcome, set once by its ack or its drop, whichever
// comes first, and counted by that one alone.
const (
recordPending int32 = iota
recordAcked
recordDropped
)
var recordOutcomeLabels = [...]string{recordAcked: "acked", recordDropped: "dropped"}
type pendingRecord struct {
target string
key []byte
value *schema_pb.RecordValue
done chan struct{} // closed once the record is acked or dropped
outcome atomic.Int32
late atomic.Bool
}
// settle sets the record's terminal outcome and counts it, unless one was set first.
func (r *pendingRecord) settle(outcome int32) bool {
if !r.outcome.CompareAndSwap(recordPending, outcome) {
return false
}
stats.S3NotificationRecordsCounter.WithLabelValues(r.target, recordOutcomeLabels[outcome]).Inc()
return true
}
// answered is called when the record's request stops waiting. A record not
// yet acked or dropped is counted late, once; it is still counted again when
// it is acked or dropped. It reports whether the record was acked.
func (r *pendingRecord) answered() bool {
switch r.outcome.Load() {
case recordAcked:
return true
case recordPending:
if r.late.CompareAndSwap(false, true) {
stats.S3NotificationRecordsLateCounter.WithLabelValues(r.target).Inc()
}
}
return false
}
// NewPublisher returns a publisher that reaches the brokers listed by brokers,
// called on every setup attempt so a broker that appears later is found.
func NewPublisher(brokers func() []string, grpcDialOption grpc.DialOption) *Publisher {
p := &Publisher{
brokers: brokers,
grpcDialOption: grpcDialOption,
ackWait: AckWait,
queueSize: QueueSize,
configureTimeout: configureTimeout,
targets: map[string]*targetWorker{},
}
p.configureTopic = p.configureTopicOnBroker
p.newTopicPublisher = func(ctx context.Context, t topic.Topic) (topicPublisher, error) {
return pub_client.NewTopicPublisher(ctx, &pub_client.PublisherConfiguration{
Topic: t,
PartitionCount: TopicPartitionCount,
Brokers: p.brokers(),
PublisherName: "s3-notification",
RecordType: EventRecordType(),
GrpcDialOption: p.grpcDialOption,
})
}
return p
}
// Sync starts a worker for every enabled target in reg and stops the workers
// of targets that are gone or disabled.
func (p *Publisher) Sync(reg *Registry) {
want := map[string]*Target{}
for _, name := range reg.Names() {
if t, ok := reg.Lookup(name); ok && t.Enabled {
want[name] = t
}
}
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return
}
for name, w := range p.targets {
if want[name] == nil {
w.stop()
delete(p.targets, name)
}
}
for name, t := range want {
if _, ok := p.targets[name]; !ok {
p.targets[name] = p.startWorker(t)
}
}
}
// Publish queues every message and waits, at most ackWait or until ctx ends,
// for all of them to be acked. It reports whether they were. A message that
// is not acked in time stays queued; one whose target has no worker or whose
// queue is full is dropped and counted.
func (p *Publisher) Publish(ctx context.Context, messages []Message) bool {
if len(messages) == 0 {
return true
}
start := time.Now()
allQueued := true
pending := make([]*pendingRecord, 0, len(messages))
p.mu.Lock()
for _, m := range messages {
w := p.targets[m.Target]
if w == nil {
allQueued = false
stats.S3NotificationRecordsCounter.WithLabelValues(m.Target, "dropped").Inc()
glog.V(1).Infof("notification target %s has no publisher, dropping a record", m.Target)
continue
}
record := &pendingRecord{target: w.name, key: m.Key, value: m.Value, done: make(chan struct{})}
select {
case w.queue <- record:
stats.S3NotificationQueueDepthGauge.WithLabelValues(w.name).Set(float64(len(w.queue)))
pending = append(pending, record)
default:
allQueued = false
w.countDrop("queue full")
}
}
p.mu.Unlock()
timer := time.NewTimer(p.ackWait)
defer timer.Stop()
waiting := true
allAcked := allQueued
for _, record := range pending {
if waiting {
select {
case <-record.done:
case <-timer.C:
waiting = false
case <-ctx.Done():
waiting = false
}
}
if !record.answered() {
allAcked = false
}
}
stats.S3NotificationPublishWaitHistogram.Observe(time.Since(start).Seconds())
return allAcked
}
// Close stops every worker. Records not yet acked are lost with the gateway,
// the window the design accepts; Close does not wait for them.
func (p *Publisher) Close() {
p.mu.Lock()
defer p.mu.Unlock()
p.closed = true
for name, w := range p.targets {
w.stop()
delete(p.targets, name)
}
}
// stop ends the worker and its MQ publisher without waiting for either. The
// publisher is shut down here, not by the worker, because the worker can be
// blocked inside PublishRecord while the broker is away; shutting the
// publisher down is what releases it.
func (w *targetWorker) stop() {
w.mu.Lock()
w.stopped = true
publisher := w.publisher
w.mu.Unlock()
w.cancel()
if publisher != nil {
go w.shutdown(publisher)
}
}
// adopt hands the worker its MQ publisher, or reports false after a stop,
// having shut the publisher down.
func (w *targetWorker) adopt(publisher topicPublisher) bool {
w.mu.Lock()
stopped := w.stopped
if !stopped {
w.publisher = publisher
}
w.mu.Unlock()
if stopped {
go w.shutdown(publisher)
}
return !stopped
}
func (w *targetWorker) shutdown(publisher topicPublisher) {
if err := publisher.Shutdown(); err != nil {
glog.Warningf("notification target %s: %v", w.name, err)
}
}
func (p *Publisher) startWorker(t *Target) *targetWorker {
ctx, cancel := context.WithCancel(context.Background())
w := &targetWorker{
name: t.Name,
topic: topic.NewTopic(TopicNamespace, t.TopicName()),
queue: make(chan *pendingRecord, p.queueSize),
cancel: cancel,
done: make(chan struct{}),
}
go p.runWorker(ctx, w)
return w
}
func (p *Publisher) runWorker(ctx context.Context, w *targetWorker) {
defer close(w.done)
defer stats.S3NotificationQueueDepthGauge.DeleteLabelValues(w.name)
publisher := p.setUp(ctx, w)
if publisher == nil || !w.adopt(publisher) {
w.dropQueued()
return
}
for {
select {
case <-ctx.Done():
w.dropQueued()
return
case record := <-w.queue:
stats.S3NotificationQueueDepthGauge.WithLabelValues(w.name).Set(float64(len(w.queue)))
if ctx.Err() != nil {
w.drop(record, "target stopped")
w.dropQueued()
return
}
acked, err := publisher.PublishRecord(record.key, record.value)
if err != nil {
w.drop(record, err.Error())
continue
}
go func() {
select {
case <-acked:
record.settle(recordAcked)
close(record.done)
case <-ctx.Done():
}
}()
}
}
}
// setUp creates the target's topic and its MQ publisher, retrying until both
// work or ctx ends, so a broker that is down or still starting delays the
// records instead of losing them.
func (p *Publisher) setUp(ctx context.Context, w *targetWorker) topicPublisher {
var backoff time.Duration
for attempt := 0; ; attempt++ {
if backoff > 0 {
select {
case <-time.After(backoff):
case <-ctx.Done():
return nil
}
}
backoff = min(max(2*backoff, setupMinBackoff), setupMaxBackoff)
err := p.configureTopic(ctx, w.topic)
var publisher topicPublisher
if err == nil {
publisher, err = p.newTopicPublisher(ctx, w.topic)
}
if err == nil {
glog.V(0).Infof("notification target %s publishes to topic %s", w.name, w.topic)
return publisher
}
if attempt == 0 || backoff == setupMaxBackoff {
glog.Warningf("notification target %s: set up topic %s: %v", w.name, w.topic, err)
}
if ctx.Err() != nil {
return nil
}
}
}
// configureTopicOnBroker creates the topic with the event record type, or
// updates its schema and retention when it exists; the call is idempotent, so
// every gateway makes it. The schema format is left empty, as for the other
// schematized topics: records are native RecordValues.
func (p *Publisher) configureTopicOnBroker(ctx context.Context, t topic.Topic) error {
brokers := p.brokers()
if len(brokers) == 0 {
return errors.New("no message queue broker found")
}
var lastErr error
for _, broker := range brokers {
if ctx.Err() != nil {
return ctx.Err()
}
lastErr = pb.WithBrokerGrpcClient(false, broker, p.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error {
callCtx, cancel := context.WithTimeout(ctx, p.configureTimeout)
defer cancel()
_, err := client.ConfigureTopic(callCtx, &mq_pb.ConfigureTopicRequest{
Topic: t.ToPbTopic(),
PartitionCount: TopicPartitionCount,
MessageRecordType: EventRecordType(),
KeyColumns: EventKeyColumns,
Retention: &mq_pb.TopicRetention{
RetentionSeconds: int64(TopicRetention / time.Second),
Enabled: true,
},
})
return err
})
if lastErr == nil {
return nil
}
lastErr = fmt.Errorf("%s: %w", broker, lastErr)
}
return lastErr
}
// countDrop counts a record dropped before it was queued.
func (w *targetWorker) countDrop(reason string) {
stats.S3NotificationRecordsCounter.WithLabelValues(w.name, "dropped").Inc()
w.logDrop(reason)
}
func (w *targetWorker) logDrop(reason string) {
now := time.Now().UnixNano()
if last := w.lastDropLog.Load(); now-last >= int64(dropLogInterval) && w.lastDropLog.CompareAndSwap(last, now) {
glog.Warningf("notification target %s: dropping records: %s", w.name, reason)
}
}
// drop settles a queued record as dropped and ends its request's wait.
func (w *targetWorker) drop(record *pendingRecord, reason string) {
if record.settle(recordDropped) {
w.logDrop(reason)
}
if w.afterDropSettled != nil {
w.afterDropSettled()
}
close(record.done)
}
func (w *targetWorker) dropQueued() {
for {
select {
case record := <-w.queue:
w.drop(record, "target stopped")
default:
return
}
}
}
+674
View File
@@ -0,0 +1,674 @@
package s3notification
import (
"context"
"errors"
"fmt"
"io"
"net"
"slices"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
type fakeTopicPublisher struct {
mu sync.Mutex
stall bool
keys []string
stalled []chan struct{}
shutdowns int
}
func (f *fakeTopicPublisher) PublishRecord(key []byte, value *schema_pb.RecordValue) (<-chan struct{}, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.keys = append(f.keys, string(key))
acked := make(chan struct{})
if f.stall {
f.stalled = append(f.stalled, acked)
} else {
close(acked)
}
return acked, nil
}
func (f *fakeTopicPublisher) Shutdown() error {
f.mu.Lock()
f.shutdowns++
f.mu.Unlock()
return nil
}
func (f *fakeTopicPublisher) ackStalled() {
f.mu.Lock()
defer f.mu.Unlock()
f.stall = false
for _, acked := range f.stalled {
close(acked)
}
f.stalled = nil
}
func (f *fakeTopicPublisher) published() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.keys...)
}
// testPublisher has one fake MQ publisher per topic; setUp fails while failSetup is set.
type testPublisher struct {
*Publisher
mu sync.Mutex
topics map[string]*fakeTopicPublisher
stall bool
failSetup atomic.Bool
setupCalls atomic.Int32
}
func newTestPublisher(t *testing.T, targets ...string) *testPublisher {
t.Helper()
tp := &testPublisher{topics: map[string]*fakeTopicPublisher{}}
tp.Publisher = NewPublisher(func() []string { return nil }, nil)
tp.ackWait = 100 * time.Millisecond
tp.configureTopic = func(ctx context.Context, tt topic.Topic) error {
tp.setupCalls.Add(1)
if tp.failSetup.Load() {
return errors.New("balancer not ready")
}
return nil
}
tp.newTopicPublisher = func(ctx context.Context, tt topic.Topic) (topicPublisher, error) {
tp.mu.Lock()
defer tp.mu.Unlock()
f := &fakeTopicPublisher{stall: tp.stall}
tp.topics[tt.Name] = f
return f, nil
}
t.Cleanup(tp.Close)
if len(targets) > 0 {
tp.Sync(registryOf(t, targets...))
}
return tp
}
func (tp *testPublisher) topic(name string) *fakeTopicPublisher {
tp.mu.Lock()
defer tp.mu.Unlock()
return tp.topics["notify-"+name]
}
func registryOf(t *testing.T, names ...string) *Registry {
t.Helper()
content := `{"targets":[`
for i, name := range names {
if i > 0 {
content += ","
}
content += fmt.Sprintf(`{"name":%q,"type":"topic","enabled":true,"allowed_buckets":["*"]}`, name)
}
reg, err := ParseTargets([]byte(content + `]}`))
if err != nil {
t.Fatal(err)
}
return reg
}
func waitUntil(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(5 * time.Millisecond)
}
}
func testRecord() *schema_pb.RecordValue {
return (&Event{Name: EventObjectCreatedPut, Bucket: "photos", Key: "k", LogTsNs: 1}).RecordValue("id")
}
func dropped(target string) float64 {
return testutil.ToFloat64(stats.S3NotificationRecordsCounter.WithLabelValues(target, "dropped"))
}
func TestPublishFansOutToEachTargetAndWaitsForAcks(t *testing.T) {
tp := newTestPublisher(t, "orders", "audit")
acked := tp.Publish(context.Background(), []Message{
{Target: "orders", Key: []byte("b/k1"), Value: testRecord()},
{Target: "audit", Key: []byte("b/k1"), Value: testRecord()},
{Target: "orders", Key: []byte("b/k2"), Value: testRecord()},
})
if !acked {
t.Fatal("records not acked")
}
if got := tp.topic("orders").published(); len(got) != 2 || got[0] != "b/k1" || got[1] != "b/k2" {
t.Fatalf("orders topic got %v", got)
}
if got := tp.topic("audit").published(); len(got) != 1 {
t.Fatalf("audit topic got %v", got)
}
}
func TestPublishGivesUpWaitingButKeepsTheRecord(t *testing.T) {
tp := newTestPublisher(t)
tp.stall = true
tp.Sync(registryOf(t, "slow"))
start := time.Now()
if tp.Publish(context.Background(), []Message{{Target: "slow", Key: []byte("b/k"), Value: testRecord()}}) {
t.Fatal("a stalled record reported acked")
}
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 })
if d := dropped("slow"); d != 0 {
t.Fatalf("a late record was counted dropped %v times", d)
}
}
func TestPublishStopsWaitingWhenTheRequestEnds(t *testing.T) {
tp := newTestPublisher(t)
tp.stall = true
tp.ackWait = time.Minute
tp.Sync(registryOf(t, "slow"))
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(50*time.Millisecond, cancel)
done := make(chan bool)
go func() { done <- tp.Publish(ctx, []Message{{Target: "slow", Key: []byte("b/k")}}) }()
select {
case acked := <-done:
if acked {
t.Fatal("reported acked")
}
case <-time.After(10 * time.Second):
t.Fatal("Publish kept waiting after the request ended")
}
}
func TestPublishQueuesThroughABrokerColdStart(t *testing.T) {
tp := newTestPublisher(t)
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "orders"))
if tp.Publish(context.Background(), []Message{{Target: "orders", Key: []byte("b/early")}}) {
t.Fatal("acked before the topic exists")
}
waitUntil(t, "setup retries", func() bool { return tp.setupCalls.Load() >= 2 })
tp.failSetup.Store(false)
waitUntil(t, "the queued record to be published", func() bool {
f := tp.topic("orders")
return f != nil && len(f.published()) == 1
})
if !tp.Publish(context.Background(), []Message{{Target: "orders", Key: []byte("b/late")}}) {
t.Fatal("record after setup not acked")
}
}
func TestPublishDropsWhenTheQueueIsFull(t *testing.T) {
tp := newTestPublisher(t)
tp.queueSize = 2
tp.ackWait = 10 * time.Millisecond
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "full"))
before := dropped("full")
messages := []Message{{Target: "full", Key: []byte("b/1")}, {Target: "full", Key: []byte("b/2")}, {Target: "full", Key: []byte("b/3")}}
if tp.Publish(context.Background(), messages) {
t.Fatal("acked with the broker down")
}
if got := dropped("full") - before; got != 1 {
t.Fatalf("dropped %v records, want 1", got)
}
tp.failSetup.Store(false)
waitUntil(t, "the queued records", func() bool {
f := tp.topic("full")
return f != nil && len(f.published()) == 2
})
}
func TestPublishDropsForATargetWithoutAWorker(t *testing.T) {
tp := newTestPublisher(t, "orders")
before := dropped("gone")
if tp.Publish(context.Background(), []Message{{Target: "gone", Key: []byte("b/k")}}) {
t.Fatal("acked a record for an unknown target")
}
if got := dropped("gone") - before; got != 1 {
t.Fatalf("dropped %v, want 1", got)
}
}
func TestSyncStopsRemovedAndDisabledTargets(t *testing.T) {
tp := newTestPublisher(t, "keep", "remove", "disable")
for _, name := range []string{"keep", "remove", "disable"} {
name := name
waitUntil(t, name+" set up", func() bool { return tp.topic(name) != nil })
}
reg, err := ParseTargets([]byte(`{"targets":[
{"name":"keep","type":"topic","enabled":true,"allowed_buckets":["*"]},
{"name":"disable","type":"topic","enabled":false,"allowed_buckets":["*"]}]}`))
if err != nil {
t.Fatal(err)
}
tp.Sync(reg)
for _, name := range []string{"remove", "disable"} {
f := tp.topic(name)
waitUntil(t, name+" shut down", func() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.shutdowns == 1 })
}
if f := tp.topic("keep"); f.shutdowns != 0 {
t.Fatal("a kept target was shut down")
}
if tp.Publish(context.Background(), []Message{{Target: "remove", Key: []byte("b/k")}}) {
t.Fatal("a removed target still takes records")
}
}
type failingTopicPublisher struct{}
func (failingTopicPublisher) PublishRecord([]byte, *schema_pb.RecordValue) (<-chan struct{}, error) {
return nil, errors.New("publisher is closed")
}
func (failingTopicPublisher) Shutdown() error { return nil }
func late(target string) float64 {
return testutil.ToFloat64(stats.S3NotificationRecordsLateCounter.WithLabelValues(target))
}
func TestADroppedRecordEndsTheWaitAndIsCountedOnce(t *testing.T) {
t.Run("publish error", func(t *testing.T) {
tp := newTestPublisher(t)
tp.ackWait = time.Minute
tp.newTopicPublisher = func(context.Context, topic.Topic) (topicPublisher, error) { return failingTopicPublisher{}, nil }
tp.Sync(registryOf(t, "failing"))
droppedBefore, lateBefore := dropped("failing"), late("failing")
start := time.Now()
if tp.Publish(context.Background(), []Message{{Target: "failing", Key: []byte("b/k")}}) {
t.Fatal("a record the publisher refused reported acked")
}
if waited := time.Since(start); waited > 5*time.Second {
t.Fatalf("waited %v for a record already dropped", waited)
}
if d, l := dropped("failing")-droppedBefore, late("failing")-lateBefore; d != 1 || l != 0 {
t.Fatalf("counted dropped %v, late %v; want 1 and 0", d, l)
}
})
t.Run("target removed", func(t *testing.T) {
tp := newTestPublisher(t)
tp.ackWait = time.Minute
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "removed"))
droppedBefore, lateBefore := dropped("removed"), late("removed")
result := make(chan bool)
go func() { result <- tp.Publish(context.Background(), []Message{{Target: "removed", Key: []byte("b/k")}}) }()
waitUntil(t, "the record to be queued", func() bool {
tp.mu.Lock()
defer tp.mu.Unlock()
return len(tp.targets["removed"].queue) == 1
})
tp.Sync(registryOf(t))
select {
case acked := <-result:
if acked {
t.Fatal("a dropped record reported acked")
}
case <-time.After(5 * time.Second):
t.Fatal("Publish kept waiting for a record its removed target dropped")
}
if d, l := dropped("removed")-droppedBefore, late("removed")-lateBefore; d != 1 || l != 0 {
t.Fatalf("counted dropped %v, late %v; want 1 and 0", d, l)
}
})
}
func TestStoppedTargetDropsItsQueue(t *testing.T) {
tp := newTestPublisher(t)
tp.ackWait = 10 * time.Millisecond
tp.failSetup.Store(true)
tp.Sync(registryOf(t, "stuck"))
tp.mu.Lock()
worker := tp.targets["stuck"]
tp.mu.Unlock()
droppedBefore, lateBefore := dropped("stuck"), late("stuck")
tp.Publish(context.Background(), []Message{{Target: "stuck", Key: []byte("b/k")}})
tp.Sync(registryOf(t))
<-worker.done
if n := len(worker.queue); n != 0 {
t.Fatalf("%d records left queued", n)
}
// late when its request answered, then dropped when its target stopped
if d, l := dropped("stuck")-droppedBefore, late("stuck")-lateBefore; d != 1 || l != 1 {
t.Fatalf("counted dropped %v, late %v; want 1 and 1", d, l)
}
}
func acked(target string) float64 {
return testutil.ToFloat64(stats.S3NotificationRecordsCounter.WithLabelValues(target, "acked"))
}
func TestARecordIsCountedOnceAsAckedOrDroppedAndLateSeparately(t *testing.T) {
for _, tc := range []struct {
name string
run func(w *targetWorker, r *pendingRecord)
acked, dropped, late float64
}{
{"timeout between a drop's count and its done", func(w *targetWorker, r *pendingRecord) {
w.afterDropSettled = func() { r.answered() }
w.drop(r, "test")
}, 0, 1, 0},
{"late, then dropped", func(w *targetWorker, r *pendingRecord) {
r.answered()
w.drop(r, "test")
}, 0, 1, 1},
{"late, then acked", func(w *targetWorker, r *pendingRecord) {
r.answered()
r.settle(recordAcked)
}, 1, 0, 1},
{"dropped, then a stray ack", func(w *targetWorker, r *pendingRecord) {
w.drop(r, "test")
r.settle(recordAcked)
}, 0, 1, 0},
{"answered twice", func(w *targetWorker, r *pendingRecord) {
r.answered()
r.answered()
w.drop(r, "test")
}, 0, 1, 1},
} {
t.Run(tc.name, func(t *testing.T) {
target := "count-" + tc.name
record := &pendingRecord{target: target, done: make(chan struct{})}
a, d, l := acked(target), dropped(target), late(target)
tc.run(&targetWorker{name: target}, record)
if got := [3]float64{acked(target) - a, dropped(target) - d, late(target) - l}; got != [3]float64{tc.acked, tc.dropped, tc.late} {
t.Fatalf("acked, dropped, late = %v, want %v", got, [3]float64{tc.acked, tc.dropped, tc.late})
}
})
}
}
// fullTopicPublisher is an MQ publisher whose partition buffer is full while
// the broker is away: PublishRecord blocks until Shutdown closes its input,
// and Shutdown then waits for acks that never come.
type fullTopicPublisher struct {
closed chan struct{}
closeOnce sync.Once
neverAcked chan struct{}
published atomic.Int32
}
func (f *fullTopicPublisher) PublishRecord(key []byte, value *schema_pb.RecordValue) (<-chan struct{}, error) {
f.published.Add(1)
<-f.closed
return nil, errors.New("publisher is closed")
}
func (f *fullTopicPublisher) Shutdown() error {
f.closeOnce.Do(func() { close(f.closed) })
<-f.neverAcked
return nil
}
func TestStoppingATargetReleasesAPublisherBlockedOnAFullBuffer(t *testing.T) {
for _, stop := range []string{"removed", "closed"} {
t.Run(stop, func(t *testing.T) {
full := &fullTopicPublisher{closed: make(chan struct{}), neverAcked: make(chan struct{})}
t.Cleanup(func() { close(full.neverAcked) })
tp := newTestPublisher(t)
tp.newTopicPublisher = func(context.Context, topic.Topic) (topicPublisher, error) { return full, nil }
tp.ackWait = 10 * time.Millisecond
tp.Sync(registryOf(t, "down"))
tp.mu.Lock()
worker := tp.targets["down"]
tp.mu.Unlock()
tp.Publish(context.Background(), []Message{{Target: "down", Key: []byte("b/k1")}, {Target: "down", Key: []byte("b/k2")}})
waitUntil(t, "the worker to block in PublishRecord", func() bool { return full.published.Load() == 1 })
returned := make(chan struct{})
go func() {
if stop == "removed" {
tp.Sync(registryOf(t))
} else {
tp.Close()
}
close(returned)
}()
select {
case <-returned:
case <-time.After(5 * time.Second):
t.Fatal("stopping the target waited for the publisher to flush")
}
select {
case <-worker.done:
case <-time.After(5 * time.Second):
t.Fatal("the worker is still blocked in PublishRecord")
}
if n := full.published.Load(); n != 1 {
t.Fatalf("the stopped target published %d records, want only the one in flight", n)
}
})
}
}
// fakeBroker is an in-process broker that refuses topic configuration while
// it is "starting", then leads every partition and acks each message.
type fakeBroker struct {
mq_pb.UnimplementedSeaweedMessagingServer
addr string
refuseFirst int32
failLookups bool // the partitions never get a leader
lookups atomic.Int32
hang bool // ConfigureTopic accepts the call and never answers
mu sync.Mutex
configures int32
configured *mq_pb.ConfigureTopicRequest
recordType []*schema_pb.RecordType // every record type a ConfigureTopic carried
stored map[string][]string
values [][]byte
}
func (b *fakeBroker) ConfigureTopic(ctx context.Context, req *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
if b.hang {
<-ctx.Done()
return nil, ctx.Err()
}
b.mu.Lock()
defer b.mu.Unlock()
b.configures++
if b.configures <= b.refuseFirst {
return nil, status.Error(codes.Unavailable, "no balancer")
}
if req.Retention != nil {
b.configured = req
}
b.recordType = append(b.recordType, req.MessageRecordType)
return &mq_pb.ConfigureTopicResponse{}, nil
}
func (b *fakeBroker) LookupTopicBrokers(ctx context.Context, req *mq_pb.LookupTopicBrokersRequest) (*mq_pb.LookupTopicBrokersResponse, error) {
b.lookups.Add(1)
if b.failLookups {
return nil, status.Error(codes.Unavailable, "no broker available")
}
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
}
resp.BrokerPartitionAssignments = append(resp.BrokerPartitionAssignments, &mq_pb.BrokerPartitionAssignment{
Partition: &schema_pb.Partition{RingSize: pub_balancer.MaxPartitionCount, RangeStart: i * width, RangeStop: stop},
LeaderBroker: b.addr,
})
}
return resp, nil
}
func (b *fakeBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
init, err := stream.Recv()
if err != nil {
return err
}
partition := fmt.Sprint(init.GetInit().GetPartition().GetRangeStart())
if err := stream.Send(&mq_pb.PublishMessageResponse{}); err != nil {
return err
}
for {
req, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
data := req.GetData()
if data == nil || data.Ctrl != nil {
continue
}
b.mu.Lock()
b.stored[partition] = append(b.stored[partition], string(data.Key))
b.values = append(b.values, data.Value)
b.mu.Unlock()
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs}); err != nil {
return err
}
}
}
func startFakeBroker(t *testing.T, broker *fakeBroker) *fakeBroker {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
broker.addr = listener.Addr().String()
broker.stored = map[string][]string{}
server := grpc.NewServer()
mq_pb.RegisterSeaweedMessagingServer(server, broker)
go server.Serve(listener)
t.Cleanup(server.Stop)
return broker
}
func TestConfigureTopicMovesPastAHangingBroker(t *testing.T) {
hanging := startFakeBroker(t, &fakeBroker{hang: true})
healthy := startFakeBroker(t, &fakeBroker{})
p := NewPublisher(func() []string { return []string{hanging.addr, healthy.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()))
p.configureTimeout = 200 * time.Millisecond
result := make(chan error, 1)
go func() {
result <- p.configureTopicOnBroker(context.Background(), topic.NewTopic(TopicNamespace, "notify-t"))
}()
select {
case err := <-result:
if err != nil {
t.Fatalf("configure topic: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("setup is stuck on a broker that never answers")
}
healthy.mu.Lock()
defer healthy.mu.Unlock()
if healthy.configured == nil {
t.Fatal("the next broker was not asked")
}
}
func TestRemovingATargetStopsItsPublisherStillStarting(t *testing.T) {
broker := startFakeBroker(t, &fakeBroker{failLookups: true})
p := NewPublisher(func() []string { return []string{broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()))
t.Cleanup(p.Close)
p.Sync(registryOf(t, "orphan"))
p.mu.Lock()
worker := p.targets["orphan"]
p.mu.Unlock()
waitUntil(t, "partition lookups to be retried", func() bool { return broker.lookups.Load() >= 2 })
p.Sync(registryOf(t))
select {
case <-worker.done:
case <-time.After(10 * time.Second):
t.Fatal("the removed target's publisher is still starting")
}
lookups := broker.lookups.Load()
time.Sleep(6 * time.Second) // past the MQ publisher's longest lookup backoff
if after := broker.lookups.Load(); after != lookups {
t.Fatalf("lookups went on after the target was removed: %d then %d", lookups, after)
}
}
func TestPublisherCreatesTheTopicAndPublishesThroughABroker(t *testing.T) {
broker := startFakeBroker(t, &fakeBroker{refuseFirst: 2})
p := NewPublisher(func() []string { return []string{broker.addr} }, grpc.WithTransportCredentials(insecure.NewCredentials()))
t.Cleanup(p.Close)
p.Sync(registryOf(t, "orders"))
var messages []Message
for i := 0; i < 20; i++ {
messages = append(messages, Message{Target: "orders", Key: MessageKey("photos", fmt.Sprintf("k%d", i)), Value: testRecord()})
}
// The first attempts meet a broker still taking the balancer lock.
waitUntil(t, "records acked", func() bool { return p.Publish(context.Background(), messages[:1]) })
if !p.Publish(context.Background(), messages) {
t.Fatal("records not acked")
}
broker.mu.Lock()
defer broker.mu.Unlock()
if broker.configures <= broker.refuseFirst {
t.Fatalf("topic configured %d times, want retries past %d refusals", broker.configures, broker.refuseFirst)
}
req := broker.configured
if req == nil || req.Topic.Namespace != "s3" || req.Topic.Name != "notify-orders" || req.PartitionCount != 4 ||
!req.Retention.Enabled || req.Retention.RetentionSeconds != 7*24*3600 ||
!slices.Equal(req.KeyColumns, []string{"bucket_name", "object_key"}) || req.SchemaFormat != "" {
t.Fatalf("topic configured as %v", req)
}
// the MQ publisher configures the topic too; neither may change its schema
for _, recordType := range broker.recordType {
if !proto.Equal(recordType, EventRecordType()) {
t.Fatalf("topic configured with record type %v", recordType)
}
}
for _, value := range broker.values {
stored := &schema_pb.RecordValue{}
if err := proto.Unmarshal(value, stored); err != nil || !proto.Equal(stored, testRecord()) {
t.Fatalf("stored value %v (%v), want the published record", stored, err)
}
}
// every copy of one key landed in one partition
partitionOf := map[string]string{}
for partition, keys := range broker.stored {
for _, key := range keys {
if other, ok := partitionOf[key]; ok && other != partition {
t.Fatalf("key %s in partitions %s and %s", key, other, partition)
}
partitionOf[key] = partition
}
}
if len(partitionOf) != 20 {
t.Fatalf("stored %d distinct keys, want 20", len(partitionOf))
}
}
+319
View File
@@ -0,0 +1,319 @@
package s3notification
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
const (
EventObjectCreatedPut = "s3:ObjectCreated:Put"
EventObjectCreatedPost = "s3:ObjectCreated:Post"
EventObjectCreatedCopy = "s3:ObjectCreated:Copy"
EventObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload"
EventObjectRemovedDelete = "s3:ObjectRemoved:Delete"
EventObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated"
EventTest = "s3:TestEvent"
recordEventVersion = "2.7"
recordEventSource = "aws:s3"
recordSchema = "1.0"
eventTimeLayout = "2006-01-02T15:04:05.000Z"
)
// Columns of a notification topic's records.
const (
ColumnEventVersion = "event_version"
ColumnEventSource = "event_source"
ColumnAwsRegion = "aws_region"
ColumnEventTime = "event_time"
ColumnEventName = "event_name"
ColumnPrincipalID = "principal_id"
ColumnSourceIP = "source_ip"
ColumnRequestID = "request_id"
ColumnHostID = "host_id"
ColumnConfigurationID = "configuration_id"
ColumnBucketName = "bucket_name"
ColumnBucketOwner = "bucket_owner"
ColumnBucketARN = "bucket_arn"
ColumnObjectKey = "object_key"
ColumnObjectSize = "object_size"
ColumnObjectETag = "object_etag"
ColumnObjectVersionID = "object_version_id"
ColumnSequencer = "sequencer"
ColumnUploadID = "upload_id"
ColumnPartNumber = "part_number"
ColumnPartSize = "part_size"
ColumnPartETag = "part_etag"
)
// EventKeyColumns are the record type's key columns: one object's events.
var EventKeyColumns = []string{ColumnBucketName, ColumnObjectKey}
// EventRecordType is the record type of every notification topic. Changes
// must be additive: append columns, never rename, retype or reorder them.
func EventRecordType() *schema_pb.RecordType {
columns := []struct {
name string
kind schema_pb.ScalarType
required bool
}{
{ColumnEventVersion, schema_pb.ScalarType_STRING, false},
{ColumnEventSource, schema_pb.ScalarType_STRING, false},
{ColumnAwsRegion, schema_pb.ScalarType_STRING, false},
{ColumnEventTime, schema_pb.ScalarType_TIMESTAMP, true},
{ColumnEventName, schema_pb.ScalarType_STRING, true},
{ColumnPrincipalID, schema_pb.ScalarType_STRING, false},
{ColumnSourceIP, schema_pb.ScalarType_STRING, false},
{ColumnRequestID, schema_pb.ScalarType_STRING, false},
{ColumnHostID, schema_pb.ScalarType_STRING, false},
{ColumnConfigurationID, schema_pb.ScalarType_STRING, false},
{ColumnBucketName, schema_pb.ScalarType_STRING, true},
{ColumnBucketOwner, schema_pb.ScalarType_STRING, false},
{ColumnBucketARN, schema_pb.ScalarType_STRING, false},
{ColumnObjectKey, schema_pb.ScalarType_STRING, false},
{ColumnObjectSize, schema_pb.ScalarType_INT64, false},
{ColumnObjectETag, schema_pb.ScalarType_STRING, false},
{ColumnObjectVersionID, schema_pb.ScalarType_STRING, false},
{ColumnSequencer, schema_pb.ScalarType_INT64, false},
{ColumnUploadID, schema_pb.ScalarType_STRING, false},
{ColumnPartNumber, schema_pb.ScalarType_INT32, false},
{ColumnPartSize, schema_pb.ScalarType_INT64, false},
{ColumnPartETag, schema_pb.ScalarType_STRING, false},
}
recordType := &schema_pb.RecordType{Fields: make([]*schema_pb.Field, len(columns))}
for i, c := range columns {
recordType.Fields[i] = &schema_pb.Field{
Name: c.name,
FieldIndex: int32(i),
Type: &schema_pb.Type{Kind: &schema_pb.Type_ScalarType{ScalarType: c.kind}},
IsRequired: c.required,
}
}
return recordType
}
// Event is what one S3 operation did to one object, the input to its records.
type Event struct {
Name string // with the s3: prefix, as configurations list it
Region string
Bucket string
BucketOwner string
Key string
Size int64
ETag string
VersionID string
Principal string
SourceIP string
RequestID string
// LogTsNs is the filer's stamp of the commit; it orders one key's events.
LogTsNs int64
}
// RecordValue is the event's record for the rule configurationID. Unknown
// values are left out, so they read as null.
func (e *Event) RecordValue(configurationID string) *schema_pb.RecordValue {
r := &schema_pb.RecordValue{Fields: map[string]*schema_pb.Value{}}
setString(r, ColumnEventVersion, recordEventVersion)
setString(r, ColumnEventSource, recordEventSource)
setString(r, ColumnAwsRegion, e.Region)
setTime(r, e.LogTsNs)
setString(r, ColumnEventName, strings.TrimPrefix(e.Name, "s3:"))
setString(r, ColumnPrincipalID, e.Principal)
setString(r, ColumnSourceIP, e.SourceIP)
setString(r, ColumnRequestID, e.RequestID)
setString(r, ColumnConfigurationID, configurationID)
setString(r, ColumnBucketName, e.Bucket)
setString(r, ColumnBucketOwner, e.BucketOwner)
setString(r, ColumnBucketARN, "arn:aws:s3:::"+e.Bucket)
setString(r, ColumnObjectKey, e.Key)
if !strings.HasPrefix(e.Name, "s3:ObjectRemoved:") {
r.Fields[ColumnObjectSize] = &schema_pb.Value{Kind: &schema_pb.Value_Int64Value{Int64Value: e.Size}}
setString(r, ColumnObjectETag, strings.Trim(e.ETag, `"`))
}
setString(r, ColumnObjectVersionID, e.VersionID)
r.Fields[ColumnSequencer] = &schema_pb.Value{Kind: &schema_pb.Value_Int64Value{Int64Value: e.LogTsNs}}
return r
}
// TestEventRecord is the s3:TestEvent a destination receives when a
// configuration naming it is stored.
func TestEventRecord(bucket, requestID string, tsNs int64) *schema_pb.RecordValue {
r := &schema_pb.RecordValue{Fields: map[string]*schema_pb.Value{}}
setTime(r, tsNs)
setString(r, ColumnEventName, EventTest)
setString(r, ColumnBucketName, bucket)
setString(r, ColumnRequestID, requestID)
return r
}
// MessageKey keys an object's records so its events share one partition.
func MessageKey(bucket, key string) []byte {
return []byte(bucket + "/" + key)
}
func setString(r *schema_pb.RecordValue, column, value string) {
if value != "" {
r.Fields[column] = &schema_pb.Value{Kind: &schema_pb.Value_StringValue{StringValue: value}}
}
}
func setTime(r *schema_pb.RecordValue, tsNs int64) {
r.Fields[ColumnEventTime] = &schema_pb.Value{Kind: &schema_pb.Value_TimestampValue{
TimestampValue: &schema_pb.TimestampValue{TimestampMicros: tsNs / int64(time.Microsecond), IsUtc: true},
}}
}
// The rendering below is the AWS JSON a destination receives.
type Identity struct {
PrincipalID string `json:"principalId"`
}
type Record struct {
EventVersion string `json:"eventVersion"`
EventSource string `json:"eventSource"`
AwsRegion string `json:"awsRegion"`
EventTime string `json:"eventTime"`
EventName string `json:"eventName"`
UserIdentity Identity `json:"userIdentity"`
RequestParameters map[string]string `json:"requestParameters"`
ResponseElements map[string]string `json:"responseElements"`
S3 RecordS3 `json:"s3"`
}
type RecordS3 struct {
SchemaVersion string `json:"s3SchemaVersion"`
ConfigurationID string `json:"configurationId"`
Bucket RecordBucket `json:"bucket"`
Object RecordObject `json:"object"`
}
type RecordBucket struct {
Name string `json:"name"`
OwnerIdentity Identity `json:"ownerIdentity"`
ARN string `json:"arn"`
}
type RecordObject struct {
Key string `json:"key"`
Size *int64 `json:"size,omitempty"`
ETag string `json:"eTag,omitempty"`
VersionID string `json:"versionId,omitempty"`
Sequencer string `json:"sequencer"`
}
// Records is the envelope AWS delivers records in.
type Records struct {
Records []Record `json:"Records"`
}
type TestEvent struct {
Service string `json:"Service"`
Event string `json:"Event"`
Time string `json:"Time"`
Bucket string `json:"Bucket"`
RequestID string `json:"RequestId"`
HostID string `json:"HostId"`
}
var errTestEventInBatch = errors.New("an s3:TestEvent renders alone")
// IsTestEvent reports whether a record is an s3:TestEvent.
func IsTestEvent(r *schema_pb.RecordValue) bool {
return stringField(r, ColumnEventName) == EventTest
}
// Render turns records into the JSON body a destination receives: the
// {"Records":[...]} envelope, or the test event message for a single
// s3:TestEvent, which never shares a body with other records.
func Render(records ...*schema_pb.RecordValue) ([]byte, error) {
if len(records) == 1 && IsTestEvent(records[0]) {
r := records[0]
return json.Marshal(TestEvent{
Service: "Amazon S3",
Event: EventTest,
Time: eventTime(r),
Bucket: stringField(r, ColumnBucketName),
RequestID: stringField(r, ColumnRequestID),
HostID: stringField(r, ColumnHostID),
})
}
body := Records{Records: make([]Record, 0, len(records))}
for _, r := range records {
if IsTestEvent(r) {
return nil, errTestEventInBatch
}
body.Records = append(body.Records, renderRecord(r))
}
return json.Marshal(body)
}
func renderRecord(r *schema_pb.RecordValue) Record {
object := RecordObject{
Key: EncodeKey(stringField(r, ColumnObjectKey)),
ETag: stringField(r, ColumnObjectETag),
VersionID: stringField(r, ColumnObjectVersionID),
Sequencer: Sequencer(r.Fields[ColumnSequencer].GetInt64Value()),
}
if size, ok := r.Fields[ColumnObjectSize]; ok {
v := size.GetInt64Value()
object.Size = &v
}
responseElements := map[string]string{}
if id := stringField(r, ColumnRequestID); id != "" {
responseElements["x-amz-request-id"] = id
}
if id := stringField(r, ColumnHostID); id != "" {
responseElements["x-amz-id-2"] = id
}
return Record{
EventVersion: stringField(r, ColumnEventVersion),
EventSource: stringField(r, ColumnEventSource),
AwsRegion: stringField(r, ColumnAwsRegion),
EventTime: eventTime(r),
EventName: stringField(r, ColumnEventName),
UserIdentity: Identity{PrincipalID: stringField(r, ColumnPrincipalID)},
RequestParameters: map[string]string{"sourceIPAddress": stringField(r, ColumnSourceIP)},
ResponseElements: responseElements,
S3: RecordS3{
SchemaVersion: recordSchema,
ConfigurationID: stringField(r, ColumnConfigurationID),
Bucket: RecordBucket{
Name: stringField(r, ColumnBucketName),
OwnerIdentity: Identity{PrincipalID: stringField(r, ColumnBucketOwner)},
ARN: stringField(r, ColumnBucketARN),
},
Object: object,
},
}
}
func stringField(r *schema_pb.RecordValue, column string) string {
return r.GetFields()[column].GetStringValue()
}
func eventTime(r *schema_pb.RecordValue) string {
micros := r.GetFields()[ColumnEventTime].GetTimestampValue().GetTimestampMicros()
return time.UnixMicro(micros).UTC().Format(eventTimeLayout)
}
// Sequencer renders a commit stamp as fixed-width hex, so sequencers compare as strings.
func Sequencer(tsNs int64) string {
return fmt.Sprintf("%016X", uint64(tsNs))
}
// EncodeKey form-encodes each path segment of an object key, as AWS records
// carry it: a space becomes '+', the '/' separators stay.
func EncodeKey(key string) string {
segments := strings.Split(key, "/")
for i, segment := range segments {
segments[i] = url.QueryEscape(segment)
}
return strings.Join(segments, "/")
}
+220
View File
@@ -0,0 +1,220 @@
package s3notification
import (
"encoding/json"
"sort"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/protobuf/proto"
)
var goldenStamp = time.Date(2026, 11, 30, 19, 29, 36, 483_900_000, time.UTC).UnixNano()
func goldenCreated() *Event {
return &Event{
Name: EventObjectCreatedPut, Region: "us-east-1", Bucket: "orders", BucketOwner: "owner-id",
Key: "2026/11/red flower.jpg", Size: 1024, ETag: `"d41d8cd98f00b204e9800998ecf8427e"`, VersionID: "v1",
Principal: "alice", SourceIP: "10.0.3.17", RequestID: "REQ1", LogTsNs: goldenStamp,
}
}
func TestEventRecordTypeColumns(t *testing.T) {
recordType := EventRecordType()
want := []struct {
name string
kind schema_pb.ScalarType
required bool
}{
{"event_version", schema_pb.ScalarType_STRING, false},
{"event_source", schema_pb.ScalarType_STRING, false},
{"aws_region", schema_pb.ScalarType_STRING, false},
{"event_time", schema_pb.ScalarType_TIMESTAMP, true},
{"event_name", schema_pb.ScalarType_STRING, true},
{"principal_id", schema_pb.ScalarType_STRING, false},
{"source_ip", schema_pb.ScalarType_STRING, false},
{"request_id", schema_pb.ScalarType_STRING, false},
{"host_id", schema_pb.ScalarType_STRING, false},
{"configuration_id", schema_pb.ScalarType_STRING, false},
{"bucket_name", schema_pb.ScalarType_STRING, true},
{"bucket_owner", schema_pb.ScalarType_STRING, false},
{"bucket_arn", schema_pb.ScalarType_STRING, false},
{"object_key", schema_pb.ScalarType_STRING, false},
{"object_size", schema_pb.ScalarType_INT64, false},
{"object_etag", schema_pb.ScalarType_STRING, false},
{"object_version_id", schema_pb.ScalarType_STRING, false},
{"sequencer", schema_pb.ScalarType_INT64, false},
{"upload_id", schema_pb.ScalarType_STRING, false},
{"part_number", schema_pb.ScalarType_INT32, false},
{"part_size", schema_pb.ScalarType_INT64, false},
{"part_etag", schema_pb.ScalarType_STRING, false},
}
if len(recordType.Fields) != len(want) {
t.Fatalf("%d columns, want %d", len(recordType.Fields), len(want))
}
for i, w := range want {
f := recordType.Fields[i]
if f.Name != w.name || f.FieldIndex != int32(i) || f.Type.GetScalarType() != w.kind || f.IsRequired != w.required || f.IsRepeated {
t.Errorf("column %d = %v, want %+v", i, f, w)
}
}
if err := schema.ValidateKeyColumns(recordType, EventKeyColumns); err != nil {
t.Fatal(err)
}
if !proto.Equal(recordType, EventRecordType()) {
t.Fatal("the record type is not stable across calls")
}
}
func TestEventRecordValue(t *testing.T) {
r := goldenCreated().RecordValue("orders-created")
strings := map[string]string{
"event_version": "2.7", "event_source": "aws:s3", "aws_region": "us-east-1", "event_name": "ObjectCreated:Put",
"principal_id": "alice", "source_ip": "10.0.3.17", "request_id": "REQ1", "configuration_id": "orders-created",
"bucket_name": "orders", "bucket_owner": "owner-id", "bucket_arn": "arn:aws:s3:::orders",
"object_key": "2026/11/red flower.jpg", "object_etag": "d41d8cd98f00b204e9800998ecf8427e", "object_version_id": "v1",
}
for column, want := range strings {
if got := r.Fields[column].GetStringValue(); got != want {
t.Errorf("%s = %q, want %q", column, got, want)
}
}
if got := r.Fields["event_time"].GetTimestampValue(); got.GetTimestampMicros() != goldenStamp/1000 || !got.GetIsUtc() {
t.Errorf("event_time = %v", got)
}
if r.Fields["object_size"].GetInt64Value() != 1024 || r.Fields["sequencer"].GetInt64Value() != goldenStamp {
t.Errorf("object_size %v, sequencer %v", r.Fields["object_size"], r.Fields["sequencer"])
}
for _, null := range []string{"host_id", "upload_id", "part_number", "part_size", "part_etag"} {
if _, ok := r.Fields[null]; ok {
t.Errorf("%s set, want null", null)
}
}
for column := range r.Fields {
found := false
for _, f := range EventRecordType().Fields {
found = found || f.Name == column
}
if !found {
t.Errorf("column %s is not in the record type", column)
}
}
}
func TestRemovalRecordValueLeavesSizeAndETagNull(t *testing.T) {
for _, name := range []string{EventObjectRemovedDelete, EventObjectRemovedDeleteMarkerCreated} {
r := (&Event{Name: name, Bucket: "b", Key: "k", Size: 7, ETag: "abc", LogTsNs: 1}).RecordValue("id")
for _, null := range []string{"object_size", "object_etag", "object_version_id"} {
if _, ok := r.Fields[null]; ok {
t.Errorf("%s: %s set, want null", name, null)
}
}
}
r := (&Event{Name: EventObjectCreatedPut, Bucket: "b", Key: "empty", LogTsNs: 1}).RecordValue("id")
if size, ok := r.Fields["object_size"]; !ok || size.GetInt64Value() != 0 {
t.Fatalf("a created empty object has size %v, want 0", size)
}
}
func TestRenderMatchesTheAwsShape(t *testing.T) {
removed := &Event{Name: EventObjectRemovedDelete, Region: "us-east-1", Bucket: "orders", Key: "a+b/c", Principal: "anonymous", SourceIP: "127.0.0.1", LogTsNs: goldenStamp}
for _, tc := range []struct {
name string
record *schema_pb.RecordValue
want string
}{
{"created", goldenCreated().RecordValue("orders-created"),
`{"Records":[{"eventVersion":"2.7","eventSource":"aws:s3","awsRegion":"us-east-1","eventTime":"2026-11-30T19:29:36.483Z","eventName":"ObjectCreated:Put","userIdentity":{"principalId":"alice"},"requestParameters":{"sourceIPAddress":"10.0.3.17"},"responseElements":{"x-amz-request-id":"REQ1"},"s3":{"s3SchemaVersion":"1.0","configurationId":"orders-created","bucket":{"name":"orders","ownerIdentity":{"principalId":"owner-id"},"arn":"arn:aws:s3:::orders"},"object":{"key":"2026/11/red+flower.jpg","size":1024,"eTag":"d41d8cd98f00b204e9800998ecf8427e","versionId":"v1","sequencer":"18ECE9662E21FA60"}}}]}`},
{"removed", removed.RecordValue("gone"),
`{"Records":[{"eventVersion":"2.7","eventSource":"aws:s3","awsRegion":"us-east-1","eventTime":"2026-11-30T19:29:36.483Z","eventName":"ObjectRemoved:Delete","userIdentity":{"principalId":"anonymous"},"requestParameters":{"sourceIPAddress":"127.0.0.1"},"responseElements":{},"s3":{"s3SchemaVersion":"1.0","configurationId":"gone","bucket":{"name":"orders","ownerIdentity":{"principalId":""},"arn":"arn:aws:s3:::orders"},"object":{"key":"a%2Bb/c","sequencer":"18ECE9662E21FA60"}}}]}`},
{"test event", TestEventRecord("orders", "REQ", goldenStamp),
`{"Service":"Amazon S3","Event":"s3:TestEvent","Time":"2026-11-30T19:29:36.483Z","Bucket":"orders","RequestId":"REQ","HostId":""}`},
} {
// a record read back from the topic is the marshalled one
data, err := proto.Marshal(tc.record)
if err != nil {
t.Fatal(err)
}
readBack := &schema_pb.RecordValue{}
if err := proto.Unmarshal(data, readBack); err != nil {
t.Fatal(err)
}
got, err := Render(readBack)
if err != nil {
t.Fatalf("%s: %v", tc.name, err)
}
if string(got) != tc.want {
t.Errorf("%s:\n got %s\nwant %s", tc.name, got, tc.want)
}
}
}
func TestRenderBatch(t *testing.T) {
a := (&Event{Name: EventObjectCreatedPut, Bucket: "b", Key: "a", LogTsNs: 1}).RecordValue("r")
b := (&Event{Name: EventObjectRemovedDelete, Bucket: "b", Key: "a", LogTsNs: 2}).RecordValue("r")
body, err := Render(a, b)
if err != nil {
t.Fatal(err)
}
var got Records
if err := json.Unmarshal(body, &got); err != nil {
t.Fatal(err)
}
if len(got.Records) != 2 || got.Records[0].EventName != "ObjectCreated:Put" || got.Records[1].EventName != "ObjectRemoved:Delete" {
t.Fatalf("batch = %+v", got.Records)
}
if _, err := Render(a, TestEventRecord("b", "", 3)); err == nil {
t.Fatal("a test event rendered inside a batch")
}
}
func TestEncodeKey(t *testing.T) {
for key, want := range map[string]string{
"plain.txt": "plain.txt",
"dir/red flower.jpg": "dir/red+flower.jpg",
"a+b/c=d&e": "a%2Bb/c%3Dd%26e",
"dir/": "dir/",
"café/über~": "caf%C3%A9/%C3%BCber~",
"100%": "100%25",
} {
if got := EncodeKey(key); got != want {
t.Errorf("EncodeKey(%q) = %q, want %q", key, got, want)
}
}
}
func TestSequencerIsFixedWidthAndSortsByStamp(t *testing.T) {
stamps := []int64{1, 255, 1 << 40, time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC).UnixNano(), time.Date(2099, 1, 1, 0, 0, 0, 0, time.UTC).UnixNano()}
var sequencers []string
for _, s := range stamps {
seq := Sequencer(s)
if len(seq) != 16 {
t.Fatalf("Sequencer(%d) = %q, want 16 digits", s, seq)
}
sequencers = append(sequencers, seq)
}
if !sort.StringsAreSorted(sequencers) {
t.Fatalf("sequencers %v do not sort as their stamps do", sequencers)
}
if got := Sequencer(0x187C2A9F3B5E4D10); got != "187C2A9F3B5E4D10" {
t.Fatalf("Sequencer = %q", got)
}
}
func TestMessageKeyGroupsAnObjectsEvents(t *testing.T) {
if got := string(MessageKey("orders", "2026/a.jpg")); got != "orders/2026/a.jpg" {
t.Fatalf("MessageKey = %q", got)
}
}
func TestTestEventRecord(t *testing.T) {
r := TestEventRecord("orders", "REQ", goldenStamp)
if !IsTestEvent(r) || r.Fields["bucket_name"].GetStringValue() != "orders" || r.Fields["request_id"].GetStringValue() != "REQ" {
t.Fatalf("test event = %v", r)
}
if IsTestEvent(goldenCreated().RecordValue("id")) {
t.Fatal("an object event read as a test event")
}
}
+37
View File
@@ -897,6 +897,39 @@ var (
Help: "Number of objects uploaded in each bucket.",
}, []string{"bucket"})
S3NotificationRecordsCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_records_total",
Help: "Bucket event records per target, counted once when acked by the broker or dropped.",
}, []string{"target", "result"})
S3NotificationRecordsLateCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_records_late_total",
Help: "Bucket event records per target still neither acked nor dropped when their request answered.",
}, []string{"target"})
S3NotificationQueueDepthGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_queue_depth",
Help: "Bucket event records waiting to reach a target's topic.",
}, []string{"target"})
S3NotificationPublishWaitHistogram = prometheus.NewHistogram(
prometheus.HistogramOpts{
Namespace: Namespace,
Subsystem: subsystemS3,
Name: "notification_publish_wait_seconds",
Help: "Time a request waited for its bucket event records to be acked.",
Buckets: prometheus.ExponentialBuckets(0.001, 2, 12),
})
S3BucketSizeBytesGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: Namespace,
@@ -1259,6 +1292,10 @@ func init() {
Gather.MustRegister(S3BucketTrafficSentBytesCounter)
Gather.MustRegister(S3DeletedObjectsCounter)
Gather.MustRegister(S3UploadedObjectsCounter)
Gather.MustRegister(S3NotificationRecordsCounter)
Gather.MustRegister(S3NotificationRecordsLateCounter)
Gather.MustRegister(S3NotificationQueueDepthGauge)
Gather.MustRegister(S3NotificationPublishWaitHistogram)
Gather.MustRegister(S3BucketSizeBytesGauge)
Gather.MustRegister(S3BucketPhysicalSizeBytesGauge)
Gather.MustRegister(S3BucketObjectCountGauge)