Files
seaweedfs/weed/s3api/s3api_object_versioned_finalize.go
T
Chris LuandClaude Opus 5.5 3f2f625822 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>
2026-12-01 19:53:18 -08:00

449 lines
21 KiB
Go

package s3api
import (
"context"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"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/util"
"google.golang.org/protobuf/proto"
)
// objectWriteOwner resolves the filer that owns all of an object's writes,
// regardless of versioning state, or "" when no ring view is available. Normal,
// suspended, and versioned writes to the same object hash to one owner and
// serialize on its per-path lock.
func (s3a *S3ApiServer) objectWriteOwner(bucket, object string) pb.ServerAddress {
if s3a.objectWriteLockClient == nil {
return ""
}
return s3a.objectWriteLockClient.PrimaryForKey(s3a.objectRouteKey(bucket, object))
}
// latestPointerRecompute builds the RECOMPUTE_LATEST mutation that re-derives an
// object's .versions pointer. excludeName, when set, omits a version about to be
// deleted (so the pointer is repointed before the blob is removed); demote, when
// set, stamps the displaced prior latest with NoncurrentSinceNs.
func (s3a *S3ApiServer) latestPointerRecompute(bucket, object string, useInvertedFormat bool, excludeName string, demote bool) *filer_pb.ObjectMutation {
versionsPath := s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder)
vdir, vname := util.FullPath(versionsPath).DirAndName()
rc := &filer_pb.Recompute{
ScanDir: versionsPath,
// Inverted ids sort newest-first, so the newest is the first ascending
// entry; legacy ids sort oldest-first (scan to the last).
Descending: !useInvertedFormat,
NameToKey: s3_constants.ExtLatestVersionFileNameKey,
SizeToKey: s3_constants.ExtLatestVersionSizeKey,
MtimeToKey: s3_constants.ExtLatestVersionMtimeKey,
CopyExtended: map[string]string{
s3_constants.ExtLatestVersionIdKey: s3_constants.ExtVersionIdKey,
s3_constants.ExtLatestVersionETagKey: s3_constants.ExtETagKey,
s3_constants.ExtLatestVersionOwnerKey: s3_constants.ExtAmzOwnerKey,
s3_constants.ExtLatestVersionIsDeleteMarker: s3_constants.ExtDeleteMarkerKey,
s3_constants.ExtLatestVersionStorageClassKey: s3_constants.AmzStorageClass,
// Version files never carry the null-current signal, so this mapping
// deletes a stale one from the pointer whenever it recomputes.
s3_constants.ExtNullVersionIsLatestKey: s3_constants.ExtNullVersionIsLatestKey,
},
ExcludeName: excludeName,
}
if demote {
rc.DemoteKey = s3_constants.ExtNoncurrentSinceNsKey
rc.DemoteValue = []byte(strconv.FormatInt(time.Now().UnixNano(), 10))
}
return &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_RECOMPUTE_LATEST,
Directory: vdir,
Name: vname,
Recompute: rc,
}
}
// routedVersionedFinalize flips the .versions pointer to the newest version and
// demotes the prior latest, atomically under the object's per-path lock on the
// owner filer, via a single RECOMPUTE_LATEST. versionEntry, when set, is PUT
// 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. 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{{
Type: filer_pb.ObjectMutation_PUT,
Directory: s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder),
Entry: versionEntry,
}}, mutations...)
}
req := &filer_pb.ObjectTransactionRequest{
LockKey: s3a.toFilerPath(bucket, object),
RouteKey: s3a.objectRouteKey(bucket, object),
Mutations: mutations,
}
if latestGuard != nil {
req.Condition = latestGuard
req.ConditionKey = s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder)
}
resp, err := s3a.objectTxnOnFiler(owner, req)
switch {
case err != nil:
glog.Errorf("routedVersionedFinalize: %s/%s on %s: %v", bucket, object, owner, err)
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
return 0, s3err.ErrPreconditionFailed
case resp.Error != "":
glog.Errorf("routedVersionedFinalize: %s/%s: %s", bucket, object, resp.Error)
return 0, s3err.ErrInternalError
default:
return resp.LogTsNs, s3err.ErrNone
}
}
// removeUploadDirMutation deletes a completed upload's directory metadata-only:
// the finished object's chunks are the part chunks, so freeing their data would
// destroy the object.
func (s3a *S3ApiServer) removeUploadDirMutation(bucket, uploadID string) *filer_pb.ObjectMutation {
return &filer_pb.ObjectMutation{
Type: filer_pb.ObjectMutation_DELETE,
Directory: s3a.genUploadsFolder(bucket),
Name: uploadID,
IsRecursive: true,
}
}
// uploadExistsCondition requires the upload directory to still exist when the
// commit transaction runs, so a delete that does not take the object lock
// (abort, lifecycle, s3.clean.uploads) fails the commit instead of letting it
// publish the object over freed chunks.
func uploadExistsCondition(uploadDirectory string) (string, *filer_pb.WriteCondition) {
return uploadDirectory, &filer_pb.WriteCondition{
Clauses: []*filer_pb.WriteCondition_Clause{{Kind: filer_pb.WriteCondition_IF_EXISTS}},
}
}
// routedMultipartFinalize commits a completed multipart upload in one
// ObjectTransaction on the owner filer: PUT the version file, remove the upload
// directory, recompute the latest pointer. The transaction applies mutations in
// order with no rollback, so the order picks which partial states are
// reachable: PUT first keeps the chunks referenced at all times, and removing
// the upload directory before the recompute means a published object never
// 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. 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,
Attributes: &filer_pb.FuseAttributes{
Mtime: now,
Crtime: now,
FileMode: uint32(0770),
Uid: filer_pb.OS_UID,
Gid: filer_pb.OS_GID,
},
Chunks: chunks,
}
if decorate != nil {
decorate(versionEntry)
}
routeKey := ""
if owner != "" {
routeKey = s3a.objectRouteKey(bucket, object)
}
// A filer older than the mutation-condition support silently ignores
// 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 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{
s3a.removeUploadDirMutation(bucket, uploadID),
s3a.latestPointerRecompute(bucket, object, useInvertedFormat, "", true),
})
switch {
case err != nil:
glog.Errorf("routedMultipartFinalize: %s/%s upload %s on %s: %v", bucket, object, uploadID, owner, err)
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
if resp.FailedMutation == nil {
return 0, s3err.ErrPreconditionFailed
}
return 0, s3err.ErrNoSuchUpload
case resp.Error != "":
glog.Errorf("routedMultipartFinalize: %s/%s upload %s: %s", bucket, object, uploadID, resp.Error)
return 0, s3err.ErrInternalError
default:
return resp.LogTsNs, s3err.ErrNone
}
}
// wormDeleteCondition returns the object-lock guards for a delete, or nil when
// the bucket has no object lock. Governance bypass gates the retention check to
// COMPLIANCE mode so the filer still protects compliance versions under lock.
func wormDeleteCondition(worm, bypass bool) *filer_pb.WriteCondition {
if !worm {
return nil
}
retention := &filer_pb.WriteCondition_Clause{
Kind: filer_pb.WriteCondition_IF_EXTENDED_TIME_ELAPSED,
ExtKey: s3_constants.ExtRetentionUntilDateKey,
}
if bypass {
retention.GateKey = s3_constants.ExtObjectLockModeKey
retention.GateValue = s3_constants.RetentionModeCompliance
}
return &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
{Kind: filer_pb.WriteCondition_IF_EXTENDED_NOT_EQUAL, ExtKey: s3_constants.ExtLegalHoldKey, ExtValue: s3_constants.LegalHoldOn},
retention,
}}
}
// routedDeleteSpecificVersion removes one version under the owner filer's
// object lock. The repoint and the delete ride one transaction so the version's
// WORM guards gate both; the recompute is itself guarded to fire only while the
// pointer still names the deleted version — a noncurrent delete must leave it
// 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. 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 0, s3err.ErrInvalidRequest
}
versionFileName := s3a.getVersionFileName(versionId)
recompute := s3a.latestPointerRecompute(bucket, object, isNewFormatVersionId(versionId), versionFileName, false)
recompute.GetRecompute().OnlyIfCurrentName = versionFileName
versionsPath := s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder)
if ifMatch != nil {
recompute.Condition, recompute.ConditionKey = ifMatch, versionsPath+"/"+versionFileName
}
cond := wormDeleteCondition(worm, bypass)
req := &filer_pb.ObjectTransactionRequest{
LockKey: s3a.toFilerPath(bucket, object),
RouteKey: s3a.objectRouteKey(bucket, object),
ConditionKey: versionsPath + "/" + versionFileName,
Condition: cond,
Mutations: []*filer_pb.ObjectMutation{
recompute,
{Type: filer_pb.ObjectMutation_DELETE, Directory: versionsPath, Name: versionFileName, IsDeleteData: !metadataOnly, RemoveEmptyParent: true},
},
}
resp, err := s3a.objectTxnOnFiler(owner, req)
switch {
case err != nil:
glog.Errorf("routedDeleteSpecificVersion: %s/%s %s on %s: %v", bucket, object, versionId, owner, err)
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
if resp.FailedMutation != nil {
return 0, s3err.ErrPreconditionFailed
}
// Legal hold or retention in force on the version.
return 0, s3err.ErrAccessDenied
case resp.Error != "":
glog.Errorf("routedDeleteSpecificVersion: %s/%s %s: %s", bucket, object, versionId, resp.Error)
return 0, s3err.ErrInternalError
default:
return resp.LogTsNs, s3err.ErrNone
}
}
// routedDeleteNullVersion deletes the null version (the regular object entry, not
// a .versions file) off the distributed lock. There is no pointer to recompute;
// the WORM guards, when present, gate the delete on the object entry itself
// (condition defaults to lock_key). The second return reports whether the delete
// was settled here: the raw delete cannot remove an entry other keys are nested
// under, which the lock path handles by stripping the object off it instead.
// 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. 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)
resp, err := s3a.objectTxnOnFiler(owner, &filer_pb.ObjectTransactionRequest{
LockKey: string(fullpath),
RouteKey: s3a.objectRouteKey(bucket, object),
Condition: wormDeleteCondition(worm, bypass),
Mutations: []*filer_pb.ObjectMutation{
{Type: filer_pb.ObjectMutation_DELETE, Directory: dir, Name: name, IsDeleteData: !metadataOnly, Condition: guard},
},
})
switch {
case err != nil && ifMatch != nil:
glog.Errorf("routedDeleteNullVersion: %s/%s on %s: %v", bucket, object, owner, err)
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 0, s3err.ErrNone, false
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED && resp.FailedMutation == nil:
return 0, s3err.ErrAccessDenied, true
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED && star:
// A filer that predates IF_OBJECT_EXISTS fails it closed.
logTsNs, code := s3a.routedDemoteNullVersion(owner, bucket, object, worm, bypass, metadataOnly, ifMatch)
return logTsNs, code, true
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
return 0, s3err.ErrPreconditionFailed, true
case resp.Error != "" && ifMatch != nil && ownerRefusedNonEmpty(resp):
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 0, s3err.ErrInternalError, true
case resp.Error != "":
glog.Warningf("routedDeleteNullVersion: %s/%s returned %q, falling back to lock", bucket, object, resp.Error)
return 0, s3err.ErrNone, false
default:
return resp.LogTsNs, s3err.ErrNone, true
}
}
// routedDemoteNullVersion removes the null version from the entry as read on
// 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. 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 0, s3err.ErrPreconditionFailed
case err != nil:
glog.Errorf("routedDemoteNullVersion: %s/%s on %s: %v", bucket, object, owner, err)
return 0, s3err.ErrInternalError
case entry.IsDirectory && !entry.IsDirectoryKeyObject():
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)})}
mutation := &filer_pb.ObjectMutation{Type: filer_pb.ObjectMutation_DELETE, Directory: dir, Name: name, IsDeleteData: !metadataOnly, Condition: guard}
if entry.IsDirectory {
clearDirectoryMarkerMetadata(entry)
mutation = &filer_pb.ObjectMutation{Type: filer_pb.ObjectMutation_PUT, Directory: dir, Entry: entry, Condition: guard}
}
resp, err := s3a.objectTxnOnFiler(owner, &filer_pb.ObjectTransactionRequest{
LockKey: string(fullpath),
RouteKey: s3a.objectRouteKey(bucket, object),
Condition: wormDeleteCondition(worm, bypass),
Mutations: []*filer_pb.ObjectMutation{mutation},
})
switch {
case err != nil:
glog.Errorf("routedDemoteNullVersion: %s/%s on %s: %v", bucket, object, owner, err)
return 0, s3err.ErrInternalError
case resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED:
if resp.FailedMutation != nil {
return 0, s3err.ErrPreconditionFailed
}
return 0, s3err.ErrAccessDenied
case resp.Error != "":
glog.Errorf("routedDemoteNullVersion: %s/%s on %s returned %q", bucket, object, owner, resp.Error)
return 0, s3err.ErrInternalError
default:
return resp.LogTsNs, s3err.ErrNone
}
}
// nullVersionCondition narrows If-Match: * to an entry that carries an
// object, reporting whether it did: a nested entry stripped of its null
// version stays behind as a plain directory, which IF_EXISTS still matches.
func nullVersionCondition(ifMatch *filer_pb.WriteCondition) (*filer_pb.WriteCondition, bool) {
if ifMatch == nil {
return nil, false
}
cond, narrowed := proto.Clone(ifMatch).(*filer_pb.WriteCondition), false
for _, c := range cond.Clauses {
if c.Kind == filer_pb.WriteCondition_IF_EXISTS {
c.Kind, narrowed = filer_pb.WriteCondition_IF_OBJECT_EXISTS, true
}
}
return cond, narrowed
}
// ownerRefusedNonEmpty reports a transaction whose delete mutation the owner
// refused because other keys are nested under the entry, before applying it.
func ownerRefusedNonEmpty(resp *filer_pb.ObjectTransactionResponse) bool {
if resp.FailedMutation == nil {
return false
}
msg := strings.TrimPrefix(resp.Error, fmt.Sprintf("mutation %d: ", *resp.FailedMutation))
return errors.Is(filer.DeleteEntryError(msg), filer.ErrNonEmptyFolder)
}
// versionedFinalize flips the .versions latest pointer for a versioned PutObject:
// on the routed path RECOMPUTE_LATEST rides in the version file's PUT transaction,
// committing atomically under the object's per-path lock; off the ring
// updateLatestVersionInDirectory does it under the object write lock.
func (s3a *S3ApiServer) versionedFinalize(bucket, object string, versionId *string, useInvertedFormat bool) *putFinalize {
return &putFinalize{
lockKey: s3a.toFilerPath(bucket, object),
mutations: []*filer_pb.ObjectMutation{s3a.latestPointerRecompute(bucket, object, useInvertedFormat, "", true)},
newVersion: func(entry *filer_pb.Entry) string {
*versionId = generateVersionId(useInvertedFormat)
entry.Name = s3a.getVersionFileName(*versionId)
entry.Extended[s3_constants.ExtVersionIdKey] = []byte(*versionId)
return s3a.toFilerPath(bucket, object+s3_constants.VersionsFolder+"/"+entry.Name)
},
afterCreate: func(versionEntry *filer_pb.Entry) s3err.ErrorCode {
if err := s3a.updateLatestVersionInDirectory(bucket, object, *versionId, s3a.getVersionFileName(*versionId), versionEntry); err != nil {
glog.Errorf("putVersionedObject: failed to update latest version in directory: %v", err)
return s3err.ErrInternalError
}
return s3err.ErrNone
},
}
}
// finalizeSuspendedNullWrite retires the null delete marker a suspended DELETE left
// in .versions, so reads resolve the null version the caller just wrote at the
// regular path. Pointer first: clearing the marker while the pointer still names it
// makes reads rescan .versions and promote an older version. Call only once the
// write has committed — retiring the marker for a write that then fails republishes
// the deleted key.
//
// identityKey/identityValue name the extended attribute that marks the entry as the
// caller's write (an upload id, an etag). The cleanup rewrites shared .versions state
// off the object write lock, so it is skipped unless the regular path still holds that
// write: a DELETE that landed in between owns the null slot, and retiring its marker
// would resurrect an older version under a key that was deleted. Narrows that race,
// does not close it. owner, when set, is the filer the write went to, so the check
// reads its own write back rather than a peer that may be behind.
func (s3a *S3ApiServer) finalizeSuspendedNullWrite(owner pb.ServerAddress, bucket, object, identityKey, identityValue string) error {
dir, name := util.FullPath(s3a.toFilerPath(bucket, object)).DirAndName()
current, err := s3a.lookupEntryPreferringOwner(owner, dir, name)
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return fmt.Errorf("re-read %s/%s: %w", bucket, object, err)
}
if current == nil || string(current.Extended[identityKey]) != identityValue {
glog.V(2).Infof("finalizeSuspendedNullWrite: %s/%s superseded by a concurrent write", bucket, object)
return nil
}
if err := s3a.updateIsLatestFlagsForSuspendedVersioning(bucket, object); err != nil {
return err
}
// Best-effort: with the pointer gone the regular-path object already owns the
// null slot, so a surviving marker is neither read nor listed.
s3a.removeNullVersionFile(bucket, object)
return nil
}