From 3aadc0fc466d76fdad9902436a3cefac10ee8ece Mon Sep 17 00:00:00 2001 From: Alexander Berkov Date: Fri, 20 Nov 2026 21:52:30 +0100 Subject: [PATCH] s3api: bound route-by-key lookups at an unreachable owner filer (#12827) * s3api: bound route-by-key lookups at an unreachable owner filer A route-by-key read (getObjectEntryRoutedByKey and the scoped .versions listing) asks the key's owner filer first, on context.Background(). When that owner sits behind a network partition that drops packets instead of refusing them, the lookup waits out gRPC's 20 s connect timeout before the failover walk asks the next filer. The owner is then skipped for only 2 s, so the next read of any key it owns dials it again and waits another 20 s. With the ring spread over two data centers, about half the keys stall every ~22 s for as long as the partition lasts (#12826). - The owner's attempt in the walk now gets a deadline, -s3.routedLookupTimeout (default 1s), when the owner is not the gateway's current filer. Past it the walk moves on to the next filer, as for any transport error, and flags the owner unreachable. The current filer and every later attempt stay unbounded, so a slow but reachable local filer still answers; 0 restores the unbounded lookup. The prior- owner probe during a ring rebalance gets the same bound. - The skip time of a failed owner is now -s3.unreachableOwnerTTL (default 2s, unchanged). Deployments that can see dropped-packet partitions can raise it so each owner is retried less often. - The S3 gateway's volume location lookups take -s3.volumeLookupTimeout per filer (default 5s, the FilerClient default, unchanged), so a vidMap miss need not wait 5 s per unreachable filer. The flags exist on weed s3 (without the s3. prefix), weed filer, weed server and weed mini. Tests (s3api_object_routed_read_deadline_test.go): an owner that never answers costs a read the deadline and is skipped by the next read (hangs without the change); with the deadline 0 a slow owner is still waited for; an owner that is the current filer is not timed out; a slow filer later in the walk is waited for; the scoped listing fails over at the deadline; the skip TTL honours the option and the default. * s3api: bound a routed listing only until the owner's first message The routed-lookup deadline covered the whole .versions stream at a remote owner. A reachable owner whose listing keeps streaming past it (a store scan trailing its first rows) was cut off mid-stream, and the failover walk refuses to replay a stream that already delivered entries, while listRetry does not retry DeadlineExceeded, so the listing failed outright where it used to succeed. Lift the deadline once the stream delivers its first message; an owner that never answers still fails over at it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Chris Lu Co-authored-by: Claude Opus 5.5 --- weed/command/filer.go | 18 ++ weed/command/mini.go | 3 + weed/command/s3.go | 9 + weed/command/server.go | 3 + weed/s3api/s3api_object_routed_read.go | 96 ++++++- .../s3api_object_routed_read_deadline_test.go | 246 ++++++++++++++++++ weed/s3api/s3api_server.go | 14 +- 7 files changed, 380 insertions(+), 9 deletions(-) create mode 100644 weed/s3api/s3api_object_routed_read_deadline_test.go diff --git a/weed/command/filer.go b/weed/command/filer.go index e6f0d573c5..c1c588ad8a 100644 --- a/weed/command/filer.go +++ b/weed/command/filer.go @@ -61,6 +61,21 @@ const s3PreStopSecondsUsage = "seconds to keep serving after SIGTERM, with /stat // key still collapses: a filer entry name cannot contain an empty segment. const allowBackslashInKeyUsage = "treat backslash as a regular object-key character instead of converting it to '/' (aws-compatible; '//' still collapses)" +// The S3 gateway's filer timeouts, shared by every command that runs it. They +// decide how long a read waits on a filer it cannot reach, e.g. one across a +// network partition that drops packets instead of refusing connections. +const ( + s3RoutedLookupTimeoutUsage = "deadline for an object's metadata lookup at the key's owner filer when that owner is not the gateway's current filer; past it the read asks the next filer. 0 means no deadline" + s3UnreachableOwnerTTLUsage = "how long an owner filer whose read just failed is skipped by owner-first reads. Raise it (e.g. 30s) where a partition can drop packets to filers, so each owner is retried less often" + s3VolumeLookupTimeoutUsage = "deadline for each filer's answer to a volume location lookup before the next filer is asked" +) + +const ( + defaultS3RoutedLookupTimeout = time.Second + defaultS3UnreachableOwnerTTL = 2 * time.Second + defaultS3VolumeLookupTimeout = 5 * time.Second +) + type FilerOptions struct { masters *pb.ServerDiscovery mastersString *string @@ -200,6 +215,9 @@ func init() { filerS3Options.allowUntrustedRemoteEndpoints = cmdFiler.Flag.Bool("s3.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage) filerS3Options.allowBackslashInKey = cmdFiler.Flag.Bool("s3.allowBackslashInKey", false, allowBackslashInKeyUsage) filerS3Options.iamSelfServiceRequiresGrant = cmdFiler.Flag.Bool("s3.iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage) + filerS3Options.routedLookupTimeout = cmdFiler.Flag.Duration("s3.routedLookupTimeout", defaultS3RoutedLookupTimeout, s3RoutedLookupTimeoutUsage) + filerS3Options.unreachableOwnerTTL = cmdFiler.Flag.Duration("s3.unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage) + filerS3Options.volumeLookupTimeout = cmdFiler.Flag.Duration("s3.volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage) filerS3Options.preStopSeconds = cmdFiler.Flag.Int("s3.preStopSeconds", 0, s3PreStopSecondsUsage) // start webdav on filer diff --git a/weed/command/mini.go b/weed/command/mini.go index 7081d4c057..f7a28e3f82 100644 --- a/weed/command/mini.go +++ b/weed/command/mini.go @@ -572,6 +572,9 @@ func initMiniS3Flags() { miniS3Options.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("s3.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage) miniS3Options.allowBackslashInKey = cmdMini.Flag.Bool("s3.allowBackslashInKey", false, allowBackslashInKeyUsage) miniS3Options.iamSelfServiceRequiresGrant = cmdMini.Flag.Bool("s3.iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage) + miniS3Options.routedLookupTimeout = cmdMini.Flag.Duration("s3.routedLookupTimeout", defaultS3RoutedLookupTimeout, s3RoutedLookupTimeoutUsage) + miniS3Options.unreachableOwnerTTL = cmdMini.Flag.Duration("s3.unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage) + miniS3Options.volumeLookupTimeout = cmdMini.Flag.Duration("s3.volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage) miniS3Options.preStopSeconds = cmdMini.Flag.Int("s3.preStopSeconds", 0, s3PreStopSecondsUsage) // In mini mode, S3 uses the shared debug server started at line 681, not its own separate debug server miniS3Options.debug = new(bool) // explicitly false diff --git a/weed/command/s3.go b/weed/command/s3.go index 5cccdbabfb..67be9fb77e 100644 --- a/weed/command/s3.go +++ b/weed/command/s3.go @@ -91,6 +91,9 @@ type S3Options struct { allowBackslashInKey *bool iamSelfServiceRequiresGrant *bool preStopSeconds *int + routedLookupTimeout *time.Duration + unreachableOwnerTTL *time.Duration + volumeLookupTimeout *time.Duration // shutdownCtx, when non-nil, tells startS3Server to gracefully shut down // its HTTP/gRPC servers once the ctx is cancelled, in addition to on // interrupt. Used by weed mini to orchestrate an ordered shutdown. @@ -152,6 +155,9 @@ func init() { s3StandaloneOptions.allowBackslashInKey = cmdS3.Flag.Bool("allowBackslashInKey", false, allowBackslashInKeyUsage) s3StandaloneOptions.iamSelfServiceRequiresGrant = cmdS3.Flag.Bool("iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage) s3StandaloneOptions.preStopSeconds = cmdS3.Flag.Int("preStopSeconds", 0, s3PreStopSecondsUsage) + s3StandaloneOptions.routedLookupTimeout = cmdS3.Flag.Duration("routedLookupTimeout", defaultS3RoutedLookupTimeout, s3RoutedLookupTimeoutUsage) + s3StandaloneOptions.unreachableOwnerTTL = cmdS3.Flag.Duration("unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage) + s3StandaloneOptions.volumeLookupTimeout = cmdS3.Flag.Duration("volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage) } var cmdS3 = &Command{ @@ -425,6 +431,9 @@ func (s3opt *S3Options) startS3Server() bool { AllowUntrustedRemoteEndpoints: *s3opt.allowUntrustedRemoteEndpoints, AllowBackslashInKey: *s3opt.allowBackslashInKey, IamSelfServiceRequiresGrant: *s3opt.iamSelfServiceRequiresGrant, + RoutedLookupTimeout: *s3opt.routedLookupTimeout, + UnreachableOwnerTTL: *s3opt.unreachableOwnerTTL, + VolumeLookupTimeout: *s3opt.volumeLookupTimeout, }) if s3ApiServer_err != nil { glog.Fatalf("S3 API Server startup error: %v", s3ApiServer_err) diff --git a/weed/command/server.go b/weed/command/server.go index f5b5fca474..ec29f5e0b6 100644 --- a/weed/command/server.go +++ b/weed/command/server.go @@ -212,6 +212,9 @@ func init() { s3Options.readerCacheSizeMB = cmdServer.Flag.Int64("s3.readerCacheSizeMB", 0, "memory budget in MiB for downloaded and in-flight reader buffers across all S3 GETs (0 means unlimited)") s3Options.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("s3.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage) s3Options.iamSelfServiceRequiresGrant = cmdServer.Flag.Bool("s3.iam.selfServiceRequiresGrant", false, iamSelfServiceRequiresGrantUsage) + s3Options.routedLookupTimeout = cmdServer.Flag.Duration("s3.routedLookupTimeout", defaultS3RoutedLookupTimeout, s3RoutedLookupTimeoutUsage) + s3Options.unreachableOwnerTTL = cmdServer.Flag.Duration("s3.unreachableOwnerTTL", defaultS3UnreachableOwnerTTL, s3UnreachableOwnerTTLUsage) + s3Options.volumeLookupTimeout = cmdServer.Flag.Duration("s3.volumeLookupTimeout", defaultS3VolumeLookupTimeout, s3VolumeLookupTimeoutUsage) s3Options.preStopSeconds = cmdServer.Flag.Int("s3.preStopSeconds", 0, s3PreStopSecondsUsage) sftpOptions.port = cmdServer.Flag.Int("sftp.port", 2022, "SFTP server listen port") diff --git a/weed/s3api/s3api_object_routed_read.go b/weed/s3api/s3api_object_routed_read.go index ae2c4dd74a..9e633e815a 100644 --- a/weed/s3api/s3api_object_routed_read.go +++ b/weed/s3api/s3api_object_routed_read.go @@ -8,12 +8,55 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc" ) -// unreachableOwnerTTL is how long a route-by-key owner that just failed a read is -// skipped before being retried — long enough to spare a dead owner per-request -// dials, short enough to resume owner-first reads soon after it (or the ring) recovers. -const unreachableOwnerTTL = 2 * time.Second +// defaultUnreachableOwnerTTL is how long a route-by-key owner that just failed a +// read is skipped before being retried — long enough to spare a dead owner +// per-request dials, short enough to resume owner-first reads soon after it (or +// the ring) recovers. The unreachableOwnerTTL flag overrides it: where an owner can +// sit behind a partition that drops packets rather than refusing them, each +// retry costs a read the full routed-lookup deadline, so a longer skip helps. +const defaultUnreachableOwnerTTL = 2 * time.Second + +func (s3a *S3ApiServer) unreachableOwnerTTL() time.Duration { + if s3a.option != nil && s3a.option.UnreachableOwnerTTL > 0 { + return s3a.option.UnreachableOwnerTTL + } + return defaultUnreachableOwnerTTL +} + +// routedLookupContext returns the context for one attempt of a route-by-key +// lookup's failover walk. The walk tries preferred first; when that owner is +// another filer than the current one, its attempt gets the RoutedLookupTimeout +// deadline, so an owner that cannot answer (a dropped SYN waits out gRPC's 20 s +// connect timeout) costs the read that long before the walk asks the next +// filer, any of which reads the same entry. The current filer and every later +// attempt run unbounded, as before. The deadline covers the wait for the +// owner's first response only: answered lifts it, so a stream that has started +// answering runs to its end (the walk cannot replay it past that point). +// +// The returned function must be called once per attempt, in walk order. +func (s3a *S3ApiServer) routedLookupContext(preferred pb.ServerAddress) func() (ctx context.Context, answered func(), cancel context.CancelFunc) { + bounded := preferred != "" && s3a.option != nil && s3a.option.RoutedLookupTimeout > 0 && + preferred != s3a.filerClient.GetCurrentFiler() + return func() (context.Context, func(), context.CancelFunc) { + if !bounded { + return context.Background(), func() {}, func() {} + } + bounded = false + ctx, cancel := context.WithCancelCause(context.Background()) + timer := time.AfterFunc(s3a.option.RoutedLookupTimeout, func() { cancel(context.DeadlineExceeded) }) + return ctx, func() { timer.Stop() }, func() { timer.Stop(); cancel(nil) } + } +} + +// routedProbeContext bounds a single-filer probe of a key's prior owner the way +// routedLookupContext bounds the walk's first attempt. +func (s3a *S3ApiServer) routedProbeContext(filer pb.ServerAddress) (context.Context, context.CancelFunc) { + ctx, _, cancel := s3a.routedLookupContext(filer)() + return ctx, cancel +} // getObjectEntryRoutedByKey resolves an object's entry preferring the key's write // owner (the same route key the write path hashes), so a read sees a just-written @@ -43,8 +86,11 @@ func (s3a *S3ApiServer) getObjectScopedEntryRoutedByKey(bucket, object, dir, nam } var entry *filer_pb.Entry + attemptContext := s3a.routedLookupContext(preferred) err := s3a.withFilerClientFailover(context.Background(), preferred, false, true, func(client filer_pb.SeaweedFilerClient) error { - resp, lookupErr := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{ + ctx, _, cancel := attemptContext() + defer cancel() + resp, lookupErr := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{ Directory: dir, Name: name, }) @@ -59,7 +105,10 @@ func (s3a *S3ApiServer) getObjectScopedEntryRoutedByKey(bucket, object, dir, nam // prior owner once while the ring change is within the cooling-off window. if errors.Is(err, filer_pb.ErrNotFound) { if prior := s3a.priorWriteOwner(bucket, object); prior != "" && prior != owner { - if priorEntry, priorErr := s3a.lookupEntryOnFiler(context.Background(), prior, dir, name); priorErr == nil { + probeCtx, cancel := s3a.routedProbeContext(prior) + priorEntry, priorErr := s3a.lookupEntryOnFiler(probeCtx, prior, dir, name) + cancel() + if priorErr == nil { return priorEntry, nil } } @@ -82,8 +131,11 @@ func (s3a *S3ApiServer) listObjectScopedEntriesRoutedByKey(bucket, object, paren err = listRetry(parentDirectoryPath, func() error { entries = entries[:0] isLast = false + attemptContext := s3a.routedLookupContext(preferred) return s3a.withFilerClientFailover(context.Background(), preferred, false, true, func(client filer_pb.SeaweedFilerClient) error { - return filer_pb.SeaweedList(context.Background(), client, parentDirectoryPath, prefix, func(entry *filer_pb.Entry, isLastEntry bool) error { + ctx, answered, cancel := attemptContext() + defer cancel() + return filer_pb.SeaweedList(ctx, answeringClient{client, answered}, parentDirectoryPath, prefix, func(entry *filer_pb.Entry, isLastEntry bool) error { entries = append(entries, entry) if isLastEntry { isLast = true @@ -98,6 +150,34 @@ func (s3a *S3ApiServer) listObjectScopedEntriesRoutedByKey(bucket, object, paren return entries, isLast, err } +// answeringClient calls answered once a listing stream delivers its first +// message, ahead of SeaweedList's one-entry look-ahead. +type answeringClient struct { + filer_pb.SeaweedFilerClient + answered func() +} + +func (c answeringClient) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (filer_pb.SeaweedFiler_ListEntriesClient, error) { + stream, err := c.SeaweedFilerClient.ListEntries(ctx, in, opts...) + if err != nil { + return nil, err + } + return answeringStream{stream, c.answered}, nil +} + +type answeringStream struct { + filer_pb.SeaweedFiler_ListEntriesClient + answered func() +} + +func (s answeringStream) Recv() (*filer_pb.ListEntriesResponse, error) { + resp, err := s.SeaweedFiler_ListEntriesClient.Recv() + if err == nil { + s.answered() + } + return resp, err +} + func (s3a *S3ApiServer) priorWriteOwner(bucket, object string) pb.ServerAddress { if object == "" || s3a.objectWriteLockClient == nil { return "" @@ -106,7 +186,7 @@ func (s3a *S3ApiServer) priorWriteOwner(bucket, object string) pb.ServerAddress } func (s3a *S3ApiServer) markOwnerUnreachable(owner pb.ServerAddress) { - s3a.unreachableOwners.Store(owner, time.Now().Add(unreachableOwnerTTL)) + s3a.unreachableOwners.Store(owner, time.Now().Add(s3a.unreachableOwnerTTL())) } func (s3a *S3ApiServer) ownerRecentlyUnreachable(owner pb.ServerAddress) bool { diff --git a/weed/s3api/s3api_object_routed_read_deadline_test.go b/weed/s3api/s3api_object_routed_read_deadline_test.go new file mode 100644 index 0000000000..0168d7944b --- /dev/null +++ b/weed/s3api/s3api_object_routed_read_deadline_test.go @@ -0,0 +1,246 @@ +package s3api + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/cluster" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +// slowLookupFiler answers LookupDirectoryEntry and ListEntries with an entry +// named after itself, after delay. A delay of -1 never answers, standing in for +// an owner behind a partition that drops packets: the caller's deadline is the +// only way out. +type slowLookupFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + name string + delay time.Duration + calls atomic.Int32 +} + +func (f *slowLookupFiler) wait(ctx context.Context) error { + f.calls.Add(1) + if f.delay < 0 { + <-ctx.Done() + return ctx.Err() + } + select { + case <-time.After(f.delay): + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (f *slowLookupFiler) LookupDirectoryEntry(ctx context.Context, _ *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + if err := f.wait(ctx); err != nil { + return nil, err + } + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Name: f.name}}, nil +} + +func (f *slowLookupFiler) ListEntries(_ *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { + if err := f.wait(stream.Context()); err != nil { + return err + } + return stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{Name: f.name}}) +} + +// newRoutedReadTestServer returns a gateway whose filer list is filers (the +// first is the current filer) and whose ring makes owner every key's owner. +func newRoutedReadTestServer(t *testing.T, owner pb.ServerAddress, routedLookupTimeout time.Duration, filers ...pb.ServerAddress) *S3ApiServer { + t.Helper() + s3a := newFailoverTestServer(t, filers...) + s3a.option.RoutedLookupTimeout = routedLookupTimeout + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, owner) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{owner}, 1) + return s3a +} + +// An owner that never answers costs a read the routed-lookup deadline, not +// gRPC's connect timeout: the walk moves on to the current filer, which reads +// the same entry, and flags the owner so the next read does not dial it at all. +func TestRoutedLookupFailsOverAtDeadline(t *testing.T) { + owner := &slowLookupFiler{name: "owner", delay: -1} + local := &slowLookupFiler{name: "local"} + ownerAddr := startFakeFiler(t, owner) + s3a := newRoutedReadTestServer(t, ownerAddr, 200*time.Millisecond, startFakeFiler(t, local)) + + start := time.Now() + entry, err := s3a.getObjectEntryRoutedByKey("b", "k") + elapsed := time.Since(start) + if err != nil { + t.Fatalf("getObjectEntryRoutedByKey: %v", err) + } + if entry.Name != "local" { + t.Fatalf("entry from %q, want the current filer's", entry.Name) + } + if elapsed > 2*time.Second { + t.Fatalf("read took %v, want about the 200ms deadline", elapsed) + } + if !s3a.ownerRecentlyUnreachable(ownerAddr) { + t.Fatal("owner that missed its deadline should be skipped by the next read") + } + + if _, err := s3a.getObjectEntryRoutedByKey("b", "k"); err != nil { + t.Fatalf("second read: %v", err) + } + if n := owner.calls.Load(); n != 1 { + t.Fatalf("owner dialled %d times, want 1: the second read should skip it", n) + } +} + +// The deadline is a bound on an unreachable owner, not on a slow one when +// disabled: with RoutedLookupTimeout 0 a read waits for the owner as before. +func TestRoutedLookupWithoutDeadlineWaitsForOwner(t *testing.T) { + owner := &slowLookupFiler{name: "owner", delay: 300 * time.Millisecond} + local := &slowLookupFiler{name: "local"} + s3a := newRoutedReadTestServer(t, startFakeFiler(t, owner), 0, startFakeFiler(t, local)) + + entry, err := s3a.getObjectEntryRoutedByKey("b", "k") + if err != nil { + t.Fatalf("getObjectEntryRoutedByKey: %v", err) + } + if entry.Name != "owner" { + t.Fatalf("entry from %q, want the owner's", entry.Name) + } +} + +// An owner that is the gateway's current filer gets no deadline: there is no +// closer filer to fail over to, and a slow answer there is still the answer. +func TestRoutedLookupAtCurrentFilerIsUnbounded(t *testing.T) { + owner := &slowLookupFiler{name: "owner", delay: 300 * time.Millisecond} + other := &slowLookupFiler{name: "other"} + ownerAddr := startFakeFiler(t, owner) + s3a := newRoutedReadTestServer(t, ownerAddr, 100*time.Millisecond, ownerAddr, startFakeFiler(t, other)) + if current := s3a.filerClient.GetCurrentFiler(); current != ownerAddr { + t.Fatalf("current filer %s, want the owner %s", current, ownerAddr) + } + + entry, err := s3a.getObjectEntryRoutedByKey("b", "k") + if err != nil { + t.Fatalf("getObjectEntryRoutedByKey: %v", err) + } + if entry.Name != "owner" { + t.Fatalf("entry from %q, want the owner's", entry.Name) + } + if n := other.calls.Load(); n != 0 { + t.Fatalf("other filer asked %d times; the current filer's owner should not be timed out", n) + } +} + +// Only the owner's attempt is bounded: when the walk falls through to a filer +// that is itself slow, that filer is waited for rather than failing the read. +func TestRoutedLookupDeadlineAppliesToOwnerOnly(t *testing.T) { + owner := &slowLookupFiler{name: "owner", delay: -1} + local := &slowLookupFiler{name: "local", delay: 300 * time.Millisecond} + s3a := newRoutedReadTestServer(t, startFakeFiler(t, owner), 100*time.Millisecond, startFakeFiler(t, local)) + + entry, err := s3a.getObjectEntryRoutedByKey("b", "k") + if err != nil { + t.Fatalf("getObjectEntryRoutedByKey: %v", err) + } + if entry.Name != "local" { + t.Fatalf("entry from %q, want the current filer's", entry.Name) + } +} + +// The scoped listing (a .versions scan) fails over at the same deadline. +func TestRoutedListFailsOverAtDeadline(t *testing.T) { + owner := &slowLookupFiler{name: "owner", delay: -1} + local := &slowLookupFiler{name: "local"} + s3a := newRoutedReadTestServer(t, startFakeFiler(t, owner), 200*time.Millisecond, startFakeFiler(t, local)) + + start := time.Now() + entries, _, err := s3a.listObjectScopedEntriesRoutedByKey("b", "k", "/buckets/b/k.versions", "", "", false, 10) + elapsed := time.Since(start) + if err != nil { + t.Fatalf("listObjectScopedEntriesRoutedByKey: %v", err) + } + if len(entries) != 1 || entries[0].Name != "local" { + t.Fatalf("entries %v, want the current filer's", entries) + } + if elapsed > 2*time.Second { + t.Fatalf("listing took %v, want about the 200ms deadline", elapsed) + } +} + +// An owner is skipped for UnreachableOwnerTTL, or the default when unset, and +// read owner-first again once it passes. +func TestUnreachableOwnerTTL(t *testing.T) { + owner := pb.ServerAddress("127.0.0.1:8888.18888") + + for _, tc := range []struct { + option *S3ApiServerOption + want time.Duration + }{ + {nil, defaultUnreachableOwnerTTL}, + {&S3ApiServerOption{}, defaultUnreachableOwnerTTL}, + {&S3ApiServerOption{UnreachableOwnerTTL: 30 * time.Second}, 30 * time.Second}, + } { + s3a := &S3ApiServer{option: tc.option} + before := time.Now() + s3a.markOwnerUnreachable(owner) + v, ok := s3a.unreachableOwners.Load(owner) + if !ok { + t.Fatal("owner not flagged") + } + if ttl := v.(time.Time).Sub(before); ttl < tc.want || ttl > tc.want+time.Second { + t.Errorf("option %+v: owner skipped for %v, want %v", tc.option, ttl, tc.want) + } + } + + s3a := &S3ApiServer{option: &S3ApiServerOption{UnreachableOwnerTTL: 50 * time.Millisecond}} + s3a.markOwnerUnreachable(owner) + if !s3a.ownerRecentlyUnreachable(owner) { + t.Fatal("owner should be skipped within the TTL") + } + time.Sleep(100 * time.Millisecond) + if s3a.ownerRecentlyUnreachable(owner) { + t.Fatal("owner should be read owner-first again once the TTL passed") + } +} + +// trailingListFiler streams one entry at once and a second after tail, like a +// store scan that keeps going after its first rows. +type trailingListFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + tail time.Duration +} + +func (f *trailingListFiler) ListEntries(_ *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { + if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{Name: "v1"}}); err != nil { + return err + } + select { + case <-time.After(f.tail): + case <-stream.Context().Done(): + return stream.Context().Err() + } + return stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{Name: "v2"}}) +} + +// The deadline bounds the wait for the owner's first answer, not a listing it +// has started streaming: the walk cannot replay a stream that already +// delivered entries, so cutting it off would fail the listing. +func TestRoutedListDeadlineEndsAtFirstEntry(t *testing.T) { + owner := &trailingListFiler{tail: 400 * time.Millisecond} + local := &slowLookupFiler{name: "local"} + ownerAddr := startFakeFiler(t, owner) + s3a := newRoutedReadTestServer(t, ownerAddr, 100*time.Millisecond, startFakeFiler(t, local)) + + entries, _, err := s3a.listObjectScopedEntriesRoutedByKey("b", "k", "/buckets/b/k.versions", "", "", false, 10) + if err != nil { + t.Fatalf("listObjectScopedEntriesRoutedByKey: %v", err) + } + if len(entries) != 2 || entries[0].Name != "v1" || entries[1].Name != "v2" { + t.Fatalf("entries %v, want the owner's full listing", entries) + } + if s3a.ownerRecentlyUnreachable(ownerAddr) { + t.Fatal("an owner that answered should not be flagged unreachable") + } +} diff --git a/weed/s3api/s3api_server.go b/weed/s3api/s3api_server.go index 7f5045a827..4257494ae2 100644 --- a/weed/s3api/s3api_server.go +++ b/weed/s3api/s3api_server.go @@ -88,6 +88,16 @@ type S3ApiServerOption struct { // GetUser) need an explicit iam: grant instead of being allowed to every // authenticated identity. IamSelfServiceRequiresGrant bool + // RoutedLookupTimeout bounds a route-by-key entry lookup at a key owner + // that is not the current filer; past it the read fails over to the next + // filer. 0 leaves the lookup unbounded. + RoutedLookupTimeout time.Duration + // UnreachableOwnerTTL is how long a key owner whose read just failed is + // skipped by route-by-key reads. 0 uses defaultUnreachableOwnerTTL. + UnreachableOwnerTTL time.Duration + // 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 } // s3ChunkCacheChunkSizeMB is the assumed chunk size (in MiB) used to convert @@ -250,6 +260,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl FilerGroup: option.FilerGroup, DiscoveryInterval: 5 * time.Minute, HomeFiler: option.HomeFiler, + GrpcTimeout: option.VolumeLookupTimeout, }) masterClient.SetOnPeerUpdateFn(filerClient.OnPeerUpdate) masterClient.SetOnVolumeLocationChangeFn(filerClient.OnVolumeLocationChange) @@ -262,7 +273,8 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl len(option.Filers), option.FilerGroup, option.Masters) } else { filerClient = wdclient.NewFilerClient(option.Filers, option.GrpcDialOption, option.DataCenter, &wdclient.FilerClientOption{ - HomeFiler: option.HomeFiler, + HomeFiler: option.HomeFiler, + GrpcTimeout: option.VolumeLookupTimeout, }) glog.V(1).Infof("S3 API initialized FilerClient with %d filer(s) (no discovery)", len(option.Filers)) }