Files
seaweedfs/weed/s3api/s3api_object_routed_write_test.go
T
Chris LuandDevin 74f196ceab s3: route regular copy source reads to the write owner (#12173)
* s3: read regular copy sources from their write owner

* filer: report mutation sentinel codes in ObjectTransaction responses

A failed mutation only surfaced resp.Error text, so routed writers could
not distinguish an existing-directory conflict from a generic failure and
could not apply the prefix-object retry the plain CreateEntry path has.

* s3api: retry a routed mkfile as a prefix object over a directory

mkFile retries ErrExistingIsDirectory by marking the entry a prefix
object; the routed path returned the conflict instead, so a routed write
to a key that is also a prefix failed where the lock path succeeds. The
filer now reports the code on the transaction response, making the retry
recognizable.

* s3api: commit copy destinations on the key's write owner

An owner-routed source read still left the destination on the gateway's
default filer, so a second copy resolved the first copy's destination on
the owner, found nothing, and returned NoSuchKey. Write unversioned and
suspended destinations through routedMkFile, and write the version file
on the owner the finalize recomputes on.

* s3api: cache remote objects on the filer that served the entry

An owner-routed lookup can return a remote-only entry that has not
replicated to the gateway's default filer; the cache RPC then cannot
find it and the copy or read degrades to a 503. Ask the entry's write
owner to cache it first, falling back to the default filer.

* s3: read versioned object state from the key's write owner

CopyObject destinations now commit version files and the .versions
pointer on the owner's object-scope ring key, so versioned reads through
the default filer could miss them until replication. Generalize the
routed read to dir/name lookups and paginated lists scoped to the
object's owner, and point the versioned read paths at it:
getSpecificObjectVersion, doGetLatestObjectVersion, the .versions
quick-checks in Get/Head/attributes, the self-heal rescans, tagging,
delete conditionals, directory-marker history checks, rename
destination, multipart completion checks, and the version-id format
probe. Reads fall back to the default filer when no ring owner is
resolvable, preserving single-filer deployments.

* test(s3api): fake RECOMPUTE_LATEST/DELETE and cover versioned copy reads

The ambiguous-PUT fake filer now creates parent directories on PUT
(mirroring InsertEntry), applies DELETE mutations, and re-derives the
.versions pointer for RECOMPUTE_LATEST the way applyRecomputeLatest
does, so owner-vs-replica tests can exercise versioned writes.

TestVersionedCopyDestinationReadsOnOwner copies into a versioned bucket
whose writes commit on the owner while the gateway's default filer is a
replica with no replication, then asserts reads by versionId,
latest-version resolution, and a copy chained off the new version all
resolve on the owner.

* test(s3api): gofmt the versioned-copy coverage

* s3: only swap in a cache fill of the resolved remote generation

A cache response can come back from a filer holding an older generation
of the key. Replacing the authorized source or swapping its chunks under
a size and range computed for the resolved entry serves the wrong object
or truncates the response. Match RemoteEntry identity and size before
using a cached entry, in both the copy and streaming paths.

* filer: keep directory attributes when an object lands as prefix object

The object-onto-directory retry replaced the existing directory's mode,
owner, and extended attributes with the object's. Preserve the directory
identity; merge directory-held extended keys only when the old entry
never held an object, so a prior generation's object metadata is not
carried forward.

* s3: keep marker lock checks on the filer that replaces the marker

The object-lock precondition read the key's write owner while mkdir
still replaces the marker on the default filer, so a locked marker not
yet replicated to the owner could be overwritten. Read the entry where
the replacement lands, in both PutObjectHandler and zip extraction.

Also hash a trailing-slash marker key to the same route key as the
object it names, so marker and object share one owner and one write
lock.

* s3: route tag writes to the owner tag reads resolve

GetObjectTagging reads the key's write owner, but PutObjectTagging and
DeleteObjectTagging still wrote through the default filer, so a
successful change returned the owner's stale tags until replication.
setTags, rmTags, and the versioned tag updates now write on the owner
first, falling back to the default filer when no owner resolves.

* s3: keep rename lookups on the filer that performs the move

AtomicRenameEntry and the retry token it carries both execute on the
default filer, but the source and destination reads went to the write
owner — a completed rename's token was invisible to its own retry, and
a source that only exists on the default filer looked absent. Read
both ends on the default filer.

* s3: send the .versions pointer repair with the object's route key

The heal reads the .versions entry on the object's owner, but the
conditional UpdateEntry is routed by the .versions path's own ring key,
which can hash to a different filer — leaving the pointer the routed
reads consult unchanged. Ship the CAS repair as a PATCH_EXTENDED
ObjectTransaction on the object's route key instead.

* filer: preserve only directory identity on a prefix-object write

Merging the old directory's extended attributes could carry a marker's
encryption, version, or etag fields onto the new plaintext object, since
a directory's own keys cannot be told apart from the object it held.
Keep only mode, uid, gid, user name and group names.

* s3: also require matching size when a cache fill replaces the source

The remote-generation check covers identity; size equality is the cheap
guard that keeps the streamed or copied range consistent with what was
resolved.

* s3: lock the object path for a routed .versions pointer repair

conditionalUpdateEntryRouted held the lock on the .versions path while
version writes and deletes serialize on the object path, so a repair
could pass IF_ENTRY_EQUAL and then apply over a pointer a writer had
advanced in between. Lock the object path like the writers and keep the
condition on the .versions entry via condition_key.

* s3: do not replay an owner-side tag mutation on another filer

withWriteOwnerFilerClient re-ran fn on the default filer after any owner
error, so an authoritative not-found could update a stale replica entry
and still report success, and a post-apply transport error could apply
the mutation twice. The failover walk now ends on any error fn returns;
only a channel that never came up moves to another filer.

* filer: keep a directory's xattrs when a prefix object replaces it

The prefix-object branch preserves the directory's identity but dropped
its Extended map wholesale; FUSE xattrs live there under the xattr-
prefix and belong to the directory, not to the object the marker held.

* s3: delete null and specific versions on the filer that serves them

On the default filer an absent entry deletes as success, so a version
that only reached the write owner survived a reported success while
owner-routed reads kept serving it. The suspended-versioning and
lifecycle deletes now go through routedDeleteNullVersion and
routedDeleteSpecificVersion when an owner resolves; an unsettled
attempt keeps the lock path.

* s3: route a lifecycle null-version delete to the object entry

The "null" version is the regular object entry, not a .versions file,
so it goes through routedDeleteNullVersion; only a real version id takes
the .versions-file delete.

* s3: repoint .versions only while it still names the deleted version

routedDeleteSpecificVersion recomputed the latest pointer on every
version delete, so removing a noncurrent version re-derived the pointer
to the newest remaining file — resurrecting an older version over a
cleared pointer (a suspended bucket's null write keeps it clear while
the null object stays current) or over a pointer that moved on. The
pointer is now read on the owner and repointed under an IF_ENTRY_EQUAL
guard only while it still names the deleted version; a contested pointer
is left for the self-heal path rather than overwritten by a stale scan.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: let lifecycle expiry keep its metadata-only deletes on routed paths

The routed lifecycle deletes hardcoded IsDeleteData, so expiring an entry
with a volume TTL queued per-chunk deletions instead of leaving the data
for the volume to reclaim — extra work on the owner for deletes
recordMetadataOnlyIf still counts as metadata-only. Pass the caller's
cleanup choice through routedDeleteNullVersion and
routedDeleteSpecificVersion; the interactive DELETE path keeps deleting
data.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: let RECOMPUTE_LATEST skip a pointer that moved on

A version delete repoints .versions only while the pointer still names the
deleted version, but the gateway cannot carry the pointer's current state
into the transaction's condition — the condition slot is already spent on
the version's WORM guards. only_if_current_name moves the check under the
transaction lock: the filer compares the pointer's name_to_key value before
scanning and skips the recompute when it moved (or was cleared by a
suspended bucket's null write), so a noncurrent delete cannot resurrect an
older version.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: repoint inside the version's locked delete

repointLatestBeforeVersionDelete ran in its own transaction ahead of the
delete, so a version delete denied by retention or legal hold still moved
the latest pointer — GET and HEAD went on serving the older version it
rolled to. The repoint and the delete now ride one transaction behind the
version's WORM guards, atomically gated by the new only_if_current_name
recompute guard instead of a stale-read IF_ENTRY_EQUAL.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-28 14:35:39 -07:00

638 lines
22 KiB
Go

package s3api
import (
"context"
"fmt"
"net"
"net/http"
"sync/atomic"
"testing"
"time"
"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/wdclient"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
func reqWith(headers map[string]string) *http.Request {
r, _ := http.NewRequest(http.MethodPut, "/b/o", nil)
for k, v := range headers {
r.Header.Set(k, v)
}
return r
}
// oneClause returns the single clause of cond, failing if it does not hold
// exactly one.
func oneClause(t *testing.T, cond *filer_pb.WriteCondition) *filer_pb.WriteCondition_Clause {
t.Helper()
if cond == nil {
t.Fatal("expected a condition, got nil")
}
if len(cond.Clauses) != 1 {
t.Fatalf("expected 1 clause, got %d", len(cond.Clauses))
}
return cond.Clauses[0]
}
func TestBuildWriteCondition(t *testing.T) {
t.Run("no headers is unconditional", func(t *testing.T) {
cond, ok := buildWriteCondition(reqWith(nil))
if !ok || cond != nil {
t.Fatalf("want (nil, true), got (%v, %v)", cond, ok)
}
})
t.Run("If-None-Match * to IF_NOT_EXISTS", func(t *testing.T) {
cond, ok := buildWriteCondition(reqWith(map[string]string{s3_constants.IfNoneMatch: "*"}))
if !ok {
t.Fatal("want ok")
}
if c := oneClause(t, cond); c.Kind != filer_pb.WriteCondition_IF_NOT_EXISTS {
t.Fatalf("kind = %v", c.Kind)
}
})
t.Run("If-Match * to IF_EXISTS", func(t *testing.T) {
cond, ok := buildWriteCondition(reqWith(map[string]string{s3_constants.IfMatch: "*"}))
if !ok {
t.Fatal("want ok")
}
if c := oneClause(t, cond); c.Kind != filer_pb.WriteCondition_IF_EXISTS {
t.Fatalf("kind = %v", c.Kind)
}
})
t.Run("If-Match strong etag to IF_ETAG_MATCH", func(t *testing.T) {
cond, ok := buildWriteCondition(reqWith(map[string]string{s3_constants.IfMatch: `"abc123"`}))
if !ok {
t.Fatal("want ok")
}
c := oneClause(t, cond)
if c.Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || len(c.Etags) != 1 || c.Etags[0] != "abc123" {
t.Fatalf("clause = %+v", c)
}
})
t.Run("If-None-Match strong etag to IF_ETAG_NOT_MATCH", func(t *testing.T) {
cond, ok := buildWriteCondition(reqWith(map[string]string{s3_constants.IfNoneMatch: `"abc123"`}))
if !ok {
t.Fatal("want ok")
}
c := oneClause(t, cond)
if c.Kind != filer_pb.WriteCondition_IF_ETAG_NOT_MATCH || len(c.Etags) != 1 || c.Etags[0] != "abc123" {
t.Fatalf("clause = %+v", c)
}
})
t.Run("weak etag falls back", func(t *testing.T) {
if _, ok := buildWriteCondition(reqWith(map[string]string{s3_constants.IfMatch: `W/"abc"`})); ok {
t.Fatal("weak etag must not take the fast path")
}
})
t.Run("etag list falls back", func(t *testing.T) {
if _, ok := buildWriteCondition(reqWith(map[string]string{s3_constants.IfMatch: `"a","b"`})); ok {
t.Fatal("etag list must not take the fast path")
}
})
t.Run("both match and none-match falls back", func(t *testing.T) {
if _, ok := buildWriteCondition(reqWith(map[string]string{
s3_constants.IfMatch: "*",
s3_constants.IfNoneMatch: "*",
})); ok {
t.Fatal("ambiguous combination must not take the fast path")
}
})
t.Run("time-based falls back", func(t *testing.T) {
if _, ok := buildWriteCondition(reqWith(map[string]string{
"If-Unmodified-Since": "Wed, 21 Oct 2015 07:28:00 GMT",
})); ok {
t.Fatal("time condition must not take the fast path")
}
})
}
func TestParseConditionalHeadersAcceptsHTTPDateFormats(t *testing.T) {
testCases := []struct {
name string
header string
value string
expected time.Time
}{
{
name: "If-Modified-Since RFC850",
header: s3_constants.IfModifiedSince,
value: "Sunday, 06-Nov-94 08:49:37 GMT",
expected: time.Date(1994, time.November, 6, 8, 49, 37, 0, time.UTC),
},
{
name: "If-Unmodified-Since ANSIC",
header: s3_constants.IfUnmodifiedSince,
value: "Sun Nov 6 08:49:37 1994",
expected: time.Date(1994, time.November, 6, 8, 49, 37, 0, time.UTC),
},
{
// Go clients build this with t.UTC().Format(time.RFC1123); the "UTC"
// zone is rejected by http.ParseTime but was accepted before, so the
// RFC1123 fallback must keep it working.
name: "If-Modified-Since RFC1123 UTC zone",
header: s3_constants.IfModifiedSince,
value: "Wed, 21 Oct 2015 07:28:00 UTC",
expected: time.Date(2015, time.October, 21, 7, 28, 0, 0, time.UTC),
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
r := reqWith(map[string]string{testCase.header: testCase.value})
headers, errCode := parseConditionalHeaders(r)
if errCode != s3err.ErrNone {
t.Fatalf("expected %s to be accepted, got %v", testCase.header, errCode)
}
if !headers.isSet {
t.Fatal("expected conditional headers to be marked set")
}
parsed := headers.ifModifiedSince
if testCase.header == s3_constants.IfUnmodifiedSince {
parsed = headers.ifUnmodifiedSince
}
if !parsed.Equal(testCase.expected) {
t.Fatalf("expected parsed time %v, got %v", testCase.expected, parsed)
}
})
}
}
func TestValidateConditionalCopyHeadersAcceptsHTTPDateFormats(t *testing.T) {
testCases := []struct {
name string
header string
value string
mtime int64 // source mtime chosen so the condition passes
}{
{
name: "X-Amz-Copy-Source-If-Modified-Since RFC850",
header: s3_constants.AmzCopySourceIfModifiedSince,
value: "Sunday, 06-Nov-94 08:49:37 GMT",
mtime: 1577836800, // 2020-01-01, modified after the 1994 header
},
{
name: "X-Amz-Copy-Source-If-Unmodified-Since ANSIC",
header: s3_constants.AmzCopySourceIfUnmodifiedSince,
value: "Sun Nov 6 08:49:37 1994",
mtime: 631152000, // 1990-01-01, not modified after the 1994 header
},
}
var s3a *S3ApiServer // method does not use the receiver
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
r := reqWith(map[string]string{testCase.header: testCase.value})
entry := &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{Mtime: testCase.mtime}}
if errCode := s3a.validateConditionalCopyHeaders(r, entry); errCode != s3err.ErrNone {
t.Fatalf("expected %s to be accepted, got %v", testCase.header, errCode)
}
})
}
}
func TestBuildDeleteCondition(t *testing.T) {
t.Run("no If-Match is unconditional", func(t *testing.T) {
cond, ok := buildDeleteCondition(reqWith(nil))
if !ok || cond != nil {
t.Fatalf("want (nil, true), got (%v, %v)", cond, ok)
}
})
t.Run("If-Match * to IF_EXISTS", func(t *testing.T) {
cond, ok := buildDeleteCondition(reqWith(map[string]string{s3_constants.IfMatch: "*"}))
if !ok {
t.Fatal("want ok")
}
if c := oneClause(t, cond); c.Kind != filer_pb.WriteCondition_IF_EXISTS {
t.Fatalf("kind = %v", c.Kind)
}
})
t.Run("If-Match etag to IF_ETAG_MATCH", func(t *testing.T) {
cond, ok := buildDeleteCondition(reqWith(map[string]string{s3_constants.IfMatch: `"e"`}))
if !ok {
t.Fatal("want ok")
}
if c := oneClause(t, cond); c.Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || c.Etags[0] != "e" {
t.Fatalf("clause = %+v", c)
}
})
t.Run("weak etag falls back", func(t *testing.T) {
if _, ok := buildDeleteCondition(reqWith(map[string]string{s3_constants.IfMatch: `W/"e"`})); ok {
t.Fatal("weak etag must not take the fast path")
}
})
}
func TestSingleStrongETag(t *testing.T) {
cases := []struct {
in string
want string
single bool
}{
{`"abc"`, "abc", true},
{` "abc" `, "abc", true},
{`abc`, "abc", true},
{`W/"abc"`, "", false},
{`w/"abc"`, "", false},
{`"a","b"`, "", false},
}
for _, c := range cases {
got, single := singleStrongETag(c.in)
if single != c.single || (single && got != c.want) {
t.Errorf("singleStrongETag(%q) = (%q, %v), want (%q, %v)", c.in, got, single, c.want, c.single)
}
}
}
// fakeTxnFiler is a minimal SeaweedFiler gRPC server that records ObjectTransaction
// calls, standing in for a live filer that a routed write fails over to.
type fakeTxnFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
calls int32
lastReq *filer_pb.ObjectTransactionRequest
reqs []*filer_pb.ObjectTransactionRequest
resp *filer_pb.ObjectTransactionResponse
err error
}
func (f *fakeTxnFiler) ObjectTransaction(ctx context.Context, req *filer_pb.ObjectTransactionRequest) (*filer_pb.ObjectTransactionResponse, error) {
atomic.AddInt32(&f.calls, 1)
f.lastReq = req
f.reqs = append(f.reqs, req)
if f.resp != nil || f.err != nil {
return f.resp, f.err
}
return &filer_pb.ObjectTransactionResponse{}, nil
}
// startFakeFiler serves impl on a random localhost port and returns the S3-style
// filer address whose ToGrpcAddress resolves back to that port.
func startFakeFiler(t *testing.T, impl filer_pb.SeaweedFilerServer) pb.ServerAddress {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(srv, impl)
go srv.Serve(lis)
t.Cleanup(srv.Stop)
port := lis.Addr().(*net.TCPAddr).Port
return pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", port))
}
func TestRoutedDeleteSpecificVersionUsesWormCondition(t *testing.T) {
versionId := "672a75d526ef29c79fe6b5680cad4a0d"
versionFile := "v_" + versionId
filer := &fakeTxnFiler{
resp: &filer_pb.ObjectTransactionResponse{
Error: "precondition failed",
ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED,
},
}
owner := startFakeFiler(t, filer)
s3a := &S3ApiServer{
option: &S3ApiServerOption{
BucketsPath: "/buckets",
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
},
}
if code := s3a.routedDeleteSpecificVersion(owner, "b", "obj", versionId, true, false, false); code != s3err.ErrAccessDenied {
t.Fatalf("locked version delete returned %v, want %v", code, s3err.ErrAccessDenied)
}
req := filer.lastReq
if req == nil {
t.Fatal("expected an ObjectTransaction request")
}
if req.LockKey != "/buckets/b/obj" {
t.Fatalf("LockKey = %q", req.LockKey)
}
if req.ConditionKey != "/buckets/b/obj.versions/"+versionFile {
t.Fatalf("ConditionKey = %q", req.ConditionKey)
}
if req.RouteKey != "s3.object.write:/buckets/b/obj" {
t.Fatalf("RouteKey = %q", req.RouteKey)
}
if len(req.Condition.GetClauses()) != 2 {
t.Fatalf("condition clauses = %d, want 2", len(req.Condition.GetClauses()))
}
hold := req.Condition.GetClauses()[0]
if hold.Kind != filer_pb.WriteCondition_IF_EXTENDED_NOT_EQUAL ||
hold.ExtKey != s3_constants.ExtLegalHoldKey ||
hold.ExtValue != s3_constants.LegalHoldOn {
t.Fatalf("legal hold clause = %+v", hold)
}
retain := req.Condition.GetClauses()[1]
if retain.Kind != filer_pb.WriteCondition_IF_EXTENDED_TIME_ELAPSED ||
retain.ExtKey != s3_constants.ExtRetentionUntilDateKey ||
retain.GateKey != "" {
t.Fatalf("retention clause = %+v", retain)
}
if len(req.Mutations) != 2 {
t.Fatalf("mutations = %d, want 2", len(req.Mutations))
}
recompute := req.Mutations[0]
if recompute.Type != filer_pb.ObjectMutation_RECOMPUTE_LATEST ||
recompute.GetRecompute().GetExcludeName() != versionFile ||
recompute.GetRecompute().GetOnlyIfCurrentName() != versionFile {
t.Fatalf("recompute mutation = %+v", recompute)
}
deleteVersion := req.Mutations[1]
if deleteVersion.Type != filer_pb.ObjectMutation_DELETE ||
deleteVersion.Directory != "/buckets/b/obj.versions" ||
deleteVersion.Name != versionFile ||
!deleteVersion.IsDeleteData ||
!deleteVersion.RemoveEmptyParent {
t.Fatalf("delete mutation = %+v", deleteVersion)
}
}
// TestRoutedDeleteSpecificVersionGuardsRepoint checks that the repoint rides in
// the version's own delete transaction, so the WORM guards gate both, and that
// the recompute carries an only-while-current guard — the filer applies it only
// while the pointer still names the deleted version, so a noncurrent delete
// leaves a cleared (suspended) or moved pointer alone.
func TestRoutedDeleteSpecificVersionGuardsRepoint(t *testing.T) {
versionId := "672a75d526ef29c79fe6b5680cad4a0d"
versionFile := "v_" + versionId
newS3a := func() *S3ApiServer {
return &S3ApiServer{option: &S3ApiServerOption{
BucketsPath: "/buckets",
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}}
}
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); code != s3err.ErrNone {
t.Fatalf("delete returned %v, want %v", code, s3err.ErrNone)
}
if len(filer.reqs) != 1 {
t.Fatalf("transactions = %d, want 1", len(filer.reqs))
}
req := filer.reqs[0]
if req.ConditionKey != "/buckets/b/obj.versions/"+versionFile {
t.Fatalf("ConditionKey = %q", req.ConditionKey)
}
if len(req.Mutations) != 2 ||
req.Mutations[0].Type != filer_pb.ObjectMutation_RECOMPUTE_LATEST ||
req.Mutations[0].GetRecompute().GetOnlyIfCurrentName() != versionFile ||
req.Mutations[1].Type != filer_pb.ObjectMutation_DELETE {
t.Fatalf("mutations = %+v, want guarded recompute + delete", req.Mutations)
}
})
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); code != s3err.ErrNone {
t.Fatalf("delete returned %v, want %v", code, s3err.ErrNone)
}
if filer.lastReq.Mutations[1].IsDeleteData {
t.Fatal("metadata-only delete set IsDeleteData")
}
})
}
func TestWormDeleteConditionForGovernanceBypass(t *testing.T) {
cond := wormDeleteCondition(true, true)
if len(cond.GetClauses()) != 2 {
t.Fatalf("condition clauses = %d, want 2", len(cond.GetClauses()))
}
retain := cond.GetClauses()[1]
if retain.Kind != filer_pb.WriteCondition_IF_EXTENDED_TIME_ELAPSED ||
retain.ExtKey != s3_constants.ExtRetentionUntilDateKey ||
retain.GateKey != s3_constants.ExtObjectLockModeKey ||
retain.GateValue != s3_constants.RetentionModeCompliance {
t.Fatalf("retention clause = %+v", retain)
}
}
// closedFilerAddress returns an address whose gRPC port has nothing listening,
// modeling a filer whose ring address is stale after a pod restart.
func closedFilerAddress(t *testing.T) pb.ServerAddress {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := lis.Addr().(*net.TCPAddr).Port
lis.Close()
return pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", port))
}
// A routed write whose owner address is dead fails over to a live filer (which
// forwards to the real owner by route_key) instead of hanging on the dead owner,
// so an object write survives a filer pod IP change without an S3 gateway restart.
func TestObjectTxnFailsOverStaleOwner(t *testing.T) {
live := &fakeTxnFiler{}
liveAddr := startFakeFiler(t, live)
deadOwner := closedFilerAddress(t)
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
s3a := &S3ApiServer{
option: &S3ApiServerOption{GrpcDialOption: dialOption},
filerClient: wdclient.NewFilerClient([]pb.ServerAddress{liveAddr}, dialOption, ""),
}
req := &filer_pb.ObjectTransactionRequest{LockKey: "/buckets/b/o", RouteKey: "s3.object.write:/buckets/b/o"}
// Owner not yet flagged: the first attempt dials it, fails fast, then fails
// over to the live filer and flags the owner unreachable.
resp, err := s3a.objectTxnOnFiler(deadOwner, req)
if err != nil {
t.Fatalf("expected failover success, got %v", err)
}
if resp == nil || resp.Error != "" {
t.Fatalf("unexpected response %+v", resp)
}
if got := atomic.LoadInt32(&live.calls); got != 1 {
t.Fatalf("live filer calls = %d, want 1", got)
}
if !s3a.ownerRecentlyUnreachable(deadOwner) {
t.Fatal("dead owner should be flagged unreachable after the failed dial")
}
// Once flagged, the owner is skipped entirely and the write still lands.
if _, err := s3a.objectTxnOnFiler(deadOwner, req); err != nil {
t.Fatalf("expected success while owner flagged, got %v", err)
}
if got := atomic.LoadInt32(&live.calls); got != 2 {
t.Fatalf("live filer calls = %d, want 2", got)
}
}
// Issue 11631: a transaction the owner may have applied must not be re-sent to
// another filer — a lost response is indistinguishable from a commit. Failover
// is only for channels that never came up, which provably sent nothing.
func TestObjectTxnNoReplayAfterSend(t *testing.T) {
owner := &fakeTxnFiler{err: status.Error(codes.Unavailable, "response lost")}
ownerAddr := startFakeFiler(t, owner)
backup := &fakeTxnFiler{}
backupAddr := startFakeFiler(t, backup)
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
s3a := &S3ApiServer{
option: &S3ApiServerOption{GrpcDialOption: dialOption},
filerClient: wdclient.NewFilerClient([]pb.ServerAddress{ownerAddr, backupAddr}, dialOption, ""),
}
req := &filer_pb.ObjectTransactionRequest{LockKey: "/buckets/b/o", RouteKey: "s3.object.write:/buckets/b/o"}
if _, err := s3a.objectTxnOnFiler(ownerAddr, req); err == nil {
t.Fatal("expected the lost response to surface as an error")
}
if got := atomic.LoadInt32(&backup.calls); got != 0 {
t.Fatalf("backup filer calls = %d — replayed a possibly-committed transaction", got)
}
}
// A completed multipart upload commits in one transaction: the version file's
// PUT, the metadata-only removal of .uploads/<id> (its chunks are the object's
// chunks), and the latest-pointer recompute, in that order.
func TestRoutedMultipartFinalize(t *testing.T) {
filer := &fakeTxnFiler{}
owner := startFakeFiler(t, filer)
s3a := &S3ApiServer{
option: &S3ApiServerOption{
BucketsPath: "/buckets",
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
},
}
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) {
entry.Extended = map[string][]byte{s3_constants.SeaweedFSUploadId: []byte("up1")}
}, "up1")
if code != s3err.ErrNone {
t.Fatalf("routedMultipartFinalize = %v", code)
}
req := filer.lastReq
if req == nil {
t.Fatal("expected an ObjectTransaction request")
}
if req.LockKey != "/buckets/b/obj" {
t.Fatalf("LockKey = %q", req.LockKey)
}
if req.RouteKey != "s3.object.write:/buckets/b/obj" {
t.Fatalf("RouteKey = %q", req.RouteKey)
}
if req.ConditionKey != "/buckets/b/.uploads/up1" {
t.Fatalf("ConditionKey = %q", req.ConditionKey)
}
if req.Condition == nil || len(req.Condition.Clauses) != 1 || req.Condition.Clauses[0].Kind != filer_pb.WriteCondition_IF_EXISTS {
t.Fatalf("Condition = %+v", req.Condition)
}
if len(req.Mutations) != 3 {
t.Fatalf("mutations = %d, want 3", len(req.Mutations))
}
put := req.Mutations[0]
if put.Type != filer_pb.ObjectMutation_PUT ||
put.Directory != "/buckets/b/obj.versions" ||
put.Entry == nil ||
put.Entry.Name != "v_1" ||
len(put.Entry.Chunks) != 1 ||
string(put.Entry.Extended[s3_constants.SeaweedFSUploadId]) != "up1" {
t.Fatalf("put mutation = %+v", put)
}
removeUpload := req.Mutations[1]
if removeUpload.Type != filer_pb.ObjectMutation_DELETE ||
removeUpload.Directory != "/buckets/b/.uploads" ||
removeUpload.Name != "up1" ||
!removeUpload.IsRecursive ||
removeUpload.IsDeleteData {
t.Fatalf("remove upload mutation = %+v", removeUpload)
}
if req.Mutations[2].Type != filer_pb.ObjectMutation_RECOMPUTE_LATEST {
t.Fatalf("recompute mutation = %+v", req.Mutations[2])
}
}
// A non-versioned multipart completion removes .uploads/<id> metadata-only in
// the same transaction as the object's PUT.
func TestWriteMultipartObjectRemovesUploadDir(t *testing.T) {
filer := &fakeTxnFiler{}
owner := startFakeFiler(t, filer)
s3a := &S3ApiServer{
option: &S3ApiServerOption{
BucketsPath: "/buckets",
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
},
}
if removal, err := s3a.routedUploadRemoval(context.Background(), "", "/buckets/b/.uploads/up1", "b", "up1", &multipartCompletionState{}); removal != nil || err != nil {
t.Fatalf("unrouted write should not carry the removal, got %+v, %v", removal, err)
}
removal, err := s3a.routedUploadRemoval(context.Background(), owner, "/buckets/b/.uploads/up1", "b", "up1", &multipartCompletionState{})
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); err != nil {
t.Fatalf("writeMultipartObject: %v", err)
}
req := filer.lastReq
if req == nil {
t.Fatal("expected an ObjectTransaction request")
}
if req.LockKey != "/buckets/b/o" {
t.Fatalf("LockKey = %q", req.LockKey)
}
if req.ConditionKey != "/buckets/b/.uploads/up1" {
t.Fatalf("ConditionKey = %q", req.ConditionKey)
}
if req.Condition == nil || len(req.Condition.Clauses) != 1 || req.Condition.Clauses[0].Kind != filer_pb.WriteCondition_IF_EXISTS {
t.Fatalf("Condition = %+v", req.Condition)
}
if len(req.Mutations) != 2 {
t.Fatalf("mutations = %d, want 2", len(req.Mutations))
}
put := req.Mutations[0]
if put.Type != filer_pb.ObjectMutation_PUT || put.Directory != "/buckets/b" || put.Entry == nil || put.Entry.Name != "o" {
t.Fatalf("put mutation = %+v", put)
}
removeUpload := req.Mutations[1]
if removeUpload.Type != filer_pb.ObjectMutation_DELETE ||
removeUpload.Directory != "/buckets/b/.uploads" ||
removeUpload.Name != "up1" ||
!removeUpload.IsRecursive ||
removeUpload.IsDeleteData {
t.Fatalf("remove upload mutation = %+v", removeUpload)
}
}
func TestRouteWriteCondition(t *testing.T) {
// Unconditional routes either way.
if c, ok := routeWriteCondition(reqWith(nil), false); !ok || c != nil {
t.Fatalf("overwrite unconditional: got (%v,%v)", c, ok)
}
if c, ok := routeWriteCondition(reqWith(nil), true); !ok || c != nil {
t.Fatalf("unique unconditional: got (%v,%v)", c, ok)
}
// An overwrite carries a reducible condition.
if c, ok := routeWriteCondition(reqWith(map[string]string{s3_constants.IfMatch: `"e"`}), false); !ok || c == nil {
t.Fatalf("overwrite conditional should route: got (%v,%v)", c, ok)
}
// A conditional unique (versioned) write bails to the lock path.
if _, ok := routeWriteCondition(reqWith(map[string]string{s3_constants.IfMatch: `"e"`}), true); ok {
t.Fatal("conditional unique write must not route")
}
// A non-reducible condition bails regardless.
if _, ok := routeWriteCondition(reqWith(map[string]string{s3_constants.IfMatch: `W/"e"`}), false); ok {
t.Fatal("weak etag must not route")
}
}