diff --git a/weed/command/embedded_filer_address.go b/weed/command/embedded_filer_address.go new file mode 100644 index 0000000000..dbc1bcc194 --- /dev/null +++ b/weed/command/embedded_filer_address.go @@ -0,0 +1,14 @@ +package command + +import "github.com/seaweedfs/seaweedfs/weed/pb" + +// embeddedFilerAddress returns the address a service embedded in the filer's +// process (such as S3) should use for that filer, in the form the filer +// registers in the master: ip:port.grpcPort. A zero *portGrpc gets the filer's +// default, port+10000, written back so the filer listens on the same port. +func embeddedFilerAddress(ip string, port int, portGrpc *int) string { + if *portGrpc == 0 { + *portGrpc = 10000 + port + } + return string(pb.NewServerAddress(ip, port, *portGrpc)) +} diff --git a/weed/command/embedded_filer_address_test.go b/weed/command/embedded_filer_address_test.go new file mode 100644 index 0000000000..a1a0e917b2 --- /dev/null +++ b/weed/command/embedded_filer_address_test.go @@ -0,0 +1,37 @@ +package command + +import ( + "testing" + + "github.com/seaweedfs/seaweedfs/weed/pb" +) + +func TestEmbeddedFilerAddressDefaultsGrpcPort(t *testing.T) { + p := 0 + if got := embeddedFilerAddress("10.0.0.1", 8889, &p); got != "10.0.0.1:8889.18889" { + t.Fatalf("address: want 10.0.0.1:8889.18889, got %s", got) + } + if p != 18889 { + t.Fatalf("grpc port: want the default 18889 written back, got %d", p) + } +} + +func TestEmbeddedFilerAddressKeepsExplicitGrpcPort(t *testing.T) { + p := 19999 + if got := embeddedFilerAddress("10.0.0.1", 8889, &p); got != "10.0.0.1:8889.19999" { + t.Fatalf("address: want 10.0.0.1:8889.19999, got %s", got) + } + if p != 19999 { + t.Fatalf("grpc port changed: %d", p) + } +} + +// The embedded S3 gateway must name its filer the way the filer registers in +// the master, or discovery treats them as different filers. +func TestEmbeddedFilerAddressMatchesRegisteredForm(t *testing.T) { + p := 0 + got := embeddedFilerAddress("10.0.0.1", 8889, &p) + if want := string(pb.NewServerAddress("10.0.0.1", 8889, 18889)); got != want { + t.Fatalf("address: want registered form %s, got %s", want, got) + } +} diff --git a/weed/command/filer.go b/weed/command/filer.go index 2244db3629..e6f0d573c5 100644 --- a/weed/command/filer.go +++ b/weed/command/filer.go @@ -307,10 +307,11 @@ func runFiler(cmd *Command, args []string) bool { // -ip.bind is unset and the bind address falls back to -ip. This must be // captured before startFiler fills *f.bindIp in place. filerBindIpUnset := *f.bindIp == "" - filerAddress := string(pb.NewServerAddress(*f.ip, *f.port, *f.portGrpc)) + filerAddress := embeddedFilerAddress(*f.ip, *f.port, f.portGrpc) startDelay := time.Duration(2) if *filerStartS3 { filerS3Options.filer = &filerAddress + filerS3Options.homeFiler = filerAddress filerS3Options.ip = f.ip if *filerS3Options.bindIp == "" { filerS3Options.listenOnLocalhost = &filerBindIpUnset diff --git a/weed/command/mini.go b/weed/command/mini.go index 71304b20ff..7081d4c057 100644 --- a/weed/command/mini.go +++ b/weed/command/mini.go @@ -1564,8 +1564,9 @@ func runMini(cmd *Command, args []string) bool { // credential manager can also serve static users. miniFilerOptions.s3ConfigFile = miniS3Config - filerAddress := string(pb.NewServerAddress(*miniIp, *miniFilerOptions.port, *miniFilerOptions.portGrpc)) + filerAddress := embeddedFilerAddress(*miniIp, *miniFilerOptions.port, miniFilerOptions.portGrpc) miniS3Options.filer = &filerAddress + miniS3Options.homeFiler = filerAddress miniWebDavOptions.filer = &filerAddress // Register Unix socket paths for gRPC services so local inter-service diff --git a/weed/command/s3.go b/weed/command/s3.go index 8b70dc6623..5cccdbabfb 100644 --- a/weed/command/s3.go +++ b/weed/command/s3.go @@ -46,6 +46,7 @@ var ( // When adding a new field, update all four flag registration sites. type S3Options struct { filer *string + homeFiler string // set by an embedding command to its own filer; not a flag ip *string bindIp *string listenOnLocalhost *bool @@ -392,6 +393,7 @@ func (s3opt *S3Options) startS3Server() bool { s3ApiServer, s3ApiServer_err = s3api.NewS3ApiServer(router, &s3api.S3ApiServerOption{ Filers: filerAddresses, + HomeFiler: pb.ServerAddress(s3opt.homeFiler), Masters: masterAddresses, Port: *s3opt.port, Config: *s3opt.config, diff --git a/weed/command/server.go b/weed/command/server.go index a7c8c99ccb..f5b5fca474 100644 --- a/weed/command/server.go +++ b/weed/command/server.go @@ -408,8 +408,9 @@ func runServer(cmd *Command, args []string) bool { *filerOptions.disableHttp = *filerOptions.disableHttp || *serverDisableHttp masterOptions.disableHttp = serverDisableHttp - filerAddress := string(pb.NewServerAddress(*serverIp, *filerOptions.port, *filerOptions.portGrpc)) + filerAddress := embeddedFilerAddress(*serverIp, *filerOptions.port, filerOptions.portGrpc) s3Options.filer = &filerAddress + s3Options.homeFiler = filerAddress sftpOptions.filer = &filerAddress iamOptions.filer = &filerAddress webdavOptions.filer = &filerAddress diff --git a/weed/s3api/s3api_handlers.go b/weed/s3api/s3api_handlers.go index 1c55695a15..32f6004fb6 100644 --- a/weed/s3api/s3api_handlers.go +++ b/weed/s3api/s3api_handlers.go @@ -124,7 +124,7 @@ func (s3a *S3ApiServer) withFilerClientFailover(ctx context.Context, preferred p if err == nil { s3a.filerClient.RecordFilerSuccess(filer) if filer != currentFiler && filer != preferred { - s3a.filerClient.SetCurrentFiler(filer) + s3a.filerClient.SwitchCurrentFiler(currentFiler, filer) glog.V(1).Infof("WithFilerClient: failover from %s to %s succeeded", currentFiler, filer) } return nil diff --git a/weed/s3api/s3api_server.go b/weed/s3api/s3api_server.go index 12f370f62c..7f5045a827 100644 --- a/weed/s3api/s3api_server.go +++ b/weed/s3api/s3api_server.go @@ -49,6 +49,7 @@ import ( type S3ApiServerOption struct { Filers []pb.ServerAddress + HomeFiler pb.ServerAddress // filer of the embedding process, preferred whenever healthy Masters []pb.ServerAddress // For filer discovery Port int Config string @@ -248,6 +249,7 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl MasterClient: masterClient, FilerGroup: option.FilerGroup, DiscoveryInterval: 5 * time.Minute, + HomeFiler: option.HomeFiler, }) masterClient.SetOnPeerUpdateFn(filerClient.OnPeerUpdate) masterClient.SetOnVolumeLocationChangeFn(filerClient.OnVolumeLocationChange) @@ -259,7 +261,9 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl glog.V(1).Infof("S3 API initialized FilerClient with %d filer(s) and discovery enabled (group: %s, masters: %v)", len(option.Filers), option.FilerGroup, option.Masters) } else { - filerClient = wdclient.NewFilerClient(option.Filers, option.GrpcDialOption, option.DataCenter) + filerClient = wdclient.NewFilerClient(option.Filers, option.GrpcDialOption, option.DataCenter, &wdclient.FilerClientOption{ + HomeFiler: option.HomeFiler, + }) glog.V(1).Infof("S3 API initialized FilerClient with %d filer(s) (no discovery)", len(option.Filers)) } diff --git a/weed/wdclient/filer_client.go b/weed/wdclient/filer_client.go index b43fd3f09e..7119199ffe 100644 --- a/weed/wdclient/filer_client.go +++ b/weed/wdclient/filer_client.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "math/rand" + "slices" "strings" "sync" "sync/atomic" @@ -65,8 +66,23 @@ type FilerClient struct { discoveryInterval time.Duration // How often to refresh filer list from master stopDiscovery chan struct{} // Signal to stop discovery goroutine closeDiscoveryOnce sync.Once // Ensures discovery channel is closed at most once + + // Home filer: the filer this client returns to whenever it is healthy, + // e.g. the local filer of an embedded S3 gateway. Empty means no home. + homeFiler pb.ServerAddress + now func() time.Time // clock; nil means time.Now + + homeMu sync.Mutex // serializes current-filer switches with the fields below + homeBackoff time.Duration // wait after leaving home before returning to it + homeEligibleAt time.Time // home is not returned to before this time + lastReturnHome time.Time // when the client last returned home } +const ( + homeBackoffCap = 5 * time.Minute // ceiling of the return-to-home backoff + homeHoldReset = 10 * time.Minute // a return that holds this long resets the backoff +) + // filerVolumeProvider implements VolumeLocationProvider by querying filer // Supports multiple filer addresses with automatic failover type filerVolumeProvider struct { @@ -88,6 +104,11 @@ type FilerClientOption struct { MasterClient *MasterClient // Optional: enables filer discovery from master FilerGroup string // Optional: filer group name for discovery (required if MasterClient is set) DiscoveryInterval time.Duration // Optional: how often to refresh filer list (0 = use default of 5 minutes) + + // HomeFiler, when set, is preferred whenever it is healthy: after a failover + // the client returns to it once its circuit breaker resets, backing off if it + // keeps failing. Embedded S3 gateways set it to their local filer. + HomeFiler pb.ServerAddress } // NewFilerClient creates a new client that queries filer(s) for volume locations @@ -109,6 +130,7 @@ func NewFilerClient(filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialO retryBackoffFactor := 1.5 // Default: 1.5x backoff multiplier var masterClient *MasterClient var filerGroup string + var homeFiler pb.ServerAddress discoveryInterval := 5 * time.Minute // Default: refresh every 5 minutes // Override with provided options @@ -138,6 +160,7 @@ func NewFilerClient(filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialO if opt.RetryBackoffFactor > 0 { retryBackoffFactor = opt.RetryBackoffFactor } + homeFiler = opt.HomeFiler if opt.MasterClient != nil { masterClient = opt.MasterClient filerGroup = opt.FilerGroup @@ -170,6 +193,9 @@ func NewFilerClient(filerAddresses []pb.ServerAddress, grpcDialOption grpc.DialO masterClient: masterClient, filerGroup: filerGroup, discoveryInterval: discoveryInterval, + homeFiler: homeFiler, + now: time.Now, + homeBackoff: resetTimeout, } // Start filer discovery if master client is configured @@ -201,13 +227,66 @@ func (fc *FilerClient) GetCurrentFiler() pb.ServerAddress { return "" } - // Get current index (atomically updated on successful operations) - index := atomic.LoadInt32(&fc.filerIndex) - if index >= int32(len(fc.filerAddresses)) { - index = 0 - } + return fc.filerAddresses[fc.currentIndexPreferHomeLocked()] +} - return fc.filerAddresses[index] +// currentIndexPreferHomeLocked returns the index to use next: the home filer +// when the current one is not home and home is eligible again (switching to +// it), else the current filer. The caller holds filerAddressesMu. +func (fc *FilerClient) currentIndexPreferHomeLocked() int32 { + index := fc.loadIndexLocked() + if index < 0 { + return 0 + } + home := fc.homeIndexLocked() + if home < 0 || home == index { + return index + } + fc.homeMu.Lock() + defer fc.homeMu.Unlock() + if index = fc.loadIndexLocked(); index < 0 { + return 0 + } + if index != home && fc.homeEligibleLocked(home) { + fc.moveCurrentIndexLocked(fc.filerAddresses[index], home, switchReturnHome) + return home + } + return index +} + +// homeIndexLocked returns the position of the home filer in the list, or -1 +// when there is no home or it is not listed. The caller holds filerAddressesMu. +func (fc *FilerClient) homeIndexLocked() int32 { + if fc.homeFiler == "" { + return -1 + } + for i, f := range fc.filerAddresses { + if sameFiler(f, fc.homeFiler) { + return int32(i) + } + } + return -1 +} + +// homeEligibleLocked reports whether the client may return to the home filer +// at index home: it is listed, its circuit breaker is closed or due for a +// re-check, and the return backoff has passed. The caller holds +// filerAddressesMu and homeMu. +func (fc *FilerClient) homeEligibleLocked(home int32) bool { + if home < 0 || int(home) >= len(fc.filerHealth) { + return false + } + if fc.shouldSkipUnhealthyFilerWithHealth(fc.filerHealth[home]) { + return false + } + return !fc.clock().Before(fc.homeEligibleAt) +} + +func (fc *FilerClient) clock() time.Time { + if fc.now == nil { + return time.Now() + } + return fc.now() } // GetAllFilers returns a snapshot of all filer addresses @@ -228,14 +307,45 @@ func (fc *FilerClient) SetCurrentFiler(addr pb.ServerAddress) { fc.filerAddressesMu.RLock() defer fc.filerAddressesMu.RUnlock() - // Find the index of the specified filer address - for i, filer := range fc.filerAddresses { - if filerKey(filer) == filerKey(addr) { - atomic.StoreInt32(&fc.filerIndex, int32(i)) + if cur := fc.loadIndexLocked(); cur >= 0 { + fc.switchCurrentFilerLocked(fc.filerAddresses[cur], addr, switchFailover) + } +} + +// SwitchCurrentFiler moves the client from `from` to `to` after a failover, but +// only while `from` is still the current filer. A caller that picked `from` +// before another request switched the client (for example back to its home +// filer) holds a stale view, and acting on it would undo that switch. +func (fc *FilerClient) SwitchCurrentFiler(from, to pb.ServerAddress) { + fc.filerAddressesMu.RLock() + defer fc.filerAddressesMu.RUnlock() + fc.switchCurrentFilerLocked(from, to, switchFailover) +} + +// switchCurrentFilerLocked switches from `from` to `to` if `from` is current. +// The caller holds filerAddressesMu (read or write). +func (fc *FilerClient) switchCurrentFilerLocked(from, to pb.ServerAddress, reason string) { + fc.homeMu.Lock() + defer fc.homeMu.Unlock() + cur := fc.loadIndexLocked() + if cur < 0 || !sameFiler(fc.filerAddresses[cur], from) { + return + } + for i, f := range fc.filerAddresses { + if sameFiler(f, to) { + fc.moveCurrentIndexLocked(fc.filerAddresses[cur], int32(i), reason) return } } - // If address not found, leave index unchanged +} + +// loadIndexLocked returns the current index, or -1 when it is out of range. +func (fc *FilerClient) loadIndexLocked() int32 { + i := atomic.LoadInt32(&fc.filerIndex) + if i < 0 || i >= int32(len(fc.filerAddresses)) { + return -1 + } + return i } // ShouldSkipUnhealthyFiler checks if a filer address should be skipped based on health tracking @@ -516,11 +626,14 @@ func (fc *FilerClient) applyDiscoveredFilersLocked(discoveredFilers map[pb.Serve return } + // Map iteration order is random; sort so every rebuild lands the same way. + slices.Sort(newFilers) + // Remember the active filer so the round-robin pointer can follow it across the rebuild. currentIndex := atomic.LoadInt32(&fc.filerIndex) - var currentKey string + var currentFiler pb.ServerAddress if currentIndex >= 0 && currentIndex < int32(len(fc.filerAddresses)) { - currentKey = filerKey(fc.filerAddresses[currentIndex]) + currentFiler = fc.filerAddresses[currentIndex] } for _, f := range newFilers { @@ -531,16 +644,26 @@ func (fc *FilerClient) applyDiscoveredFilersLocked(discoveredFilers map[pb.Serve fc.filerAddresses = newAddresses fc.filerHealth = newHealth - var newIndex int32 - if currentKey != "" { + newIndex := int32(-1) + if currentFiler != "" { for i, f := range newAddresses { - if filerKey(f) == currentKey { + if sameFiler(f, currentFiler) { newIndex = int32(i) break } } } - atomic.StoreInt32(&fc.filerIndex, newIndex) + fc.homeMu.Lock() + if newIndex < 0 { + newIndex = 0 + if home := fc.homeIndexLocked(); home >= 0 && fc.homeEligibleLocked(home) { + newIndex = home + } else if home == 0 && len(newAddresses) > 1 { + newIndex = 1 // home is still backing off; take the next filer + } + } + fc.moveCurrentIndexLocked(currentFiler, newIndex, switchDiscovery) + fc.homeMu.Unlock() if len(removedFilers) > 0 { glog.V(0).Infof("FilerClient: removed %d filer(s) no longer in group '%s': %v", len(removedFilers), fc.filerGroup, removedFilers) @@ -550,6 +673,68 @@ func (fc *FilerClient) applyDiscoveredFilersLocked(discoveredFilers map[pb.Serve } } +// Reasons a FilerClient changes its current filer, as logged on each switch. +const ( + switchFailover = "failover" + switchReturnHome = "return_home" + switchDiscovery = "discovery" +) + +// sameFiler reports whether two addresses name the same filer, whether or not +// either spells out its gRPC port. +func sameFiler(a, b pb.ServerAddress) bool { + return filerKey(a) == filerKey(b) +} + +// moveCurrentIndexLocked makes newIndex current and, when that changes which +// filer is current, logs the switch and feeds the home-filer bookkeeping. The +// caller holds filerAddressesMu and homeMu, so the check that chose newIndex, +// the move and the bookkeeping form one step: a request that sees the new +// index also sees the return backoff it started, and concurrent failovers +// from one filer count once. +func (fc *FilerClient) moveCurrentIndexLocked(from pb.ServerAddress, newIndex int32, reason string) { + atomic.StoreInt32(&fc.filerIndex, newIndex) + if newIndex < 0 || newIndex >= int32(len(fc.filerAddresses)) { + return + } + to := fc.filerAddresses[newIndex] + if from == "" || sameFiler(from, to) { + return + } + backoff := fc.noteSwitchLocked(from, to, reason) + glog.V(0).Infof("FilerClient: current filer %s -> %s (%s), return backoff %v", from, to, reason, backoff) +} + +// noteSwitchLocked records a change of the current filer for the home-filer +// return logic and reports the return backoff now in effect. Leaving home on a +// failover starts the backoff; leaving it again soon after a return doubles it, +// up to homeBackoffCap; a return that held for homeHoldReset resets it. The +// caller holds homeMu. +func (fc *FilerClient) noteSwitchLocked(from, to pb.ServerAddress, reason string) time.Duration { + if fc.homeBackoff <= 0 { + fc.homeBackoff = fc.resetTimeout + } + if fc.homeFiler == "" { + return fc.homeBackoff + } + now := fc.clock() + switch { + case sameFiler(to, fc.homeFiler): + fc.lastReturnHome = now + case reason == switchFailover && sameFiler(from, fc.homeFiler) && !sameFiler(to, fc.homeFiler): + if !fc.lastReturnHome.IsZero() { + sinceReturn := now.Sub(fc.lastReturnHome) + if sinceReturn >= homeHoldReset { + fc.homeBackoff = fc.resetTimeout + } else if sinceReturn < 2*fc.homeBackoff { + fc.homeBackoff = min(2*fc.homeBackoff, homeBackoffCap) + } + } + fc.homeEligibleAt = now.Add(fc.homeBackoff) + } + return fc.homeBackoff +} + // OnVolumeLocationChange applies master-pushed changes to the lookup-fed cache, // so a retired server stops being tried before a read against it fails. An // add lifts the removal fence and caches the volume where the master client @@ -721,7 +906,7 @@ func (fc *FilerClient) shouldSkipUnhealthyFilerWithHealth(health *filerHealth) b return false // Never failed, shouldn't skip } lastFailureTime := time.Unix(0, lastFailureNs) - if time.Since(lastFailureTime) > fc.resetTimeout { + if fc.clock().Sub(lastFailureTime) > fc.resetTimeout { return false // Time to re-check } @@ -736,7 +921,7 @@ func (fc *FilerClient) recordFilerSuccessWithHealth(health *filerHealth) { // recordFilerFailureWithHealth increments failure count for an unhealthy filer func (fc *FilerClient) recordFilerFailureWithHealth(health *filerHealth) { atomic.AddInt32(&health.failureCount, 1) - atomic.StoreInt64(&health.lastFailureTimeNs, time.Now().UnixNano()) + atomic.StoreInt64(&health.lastFailureTimeNs, fc.clock().UnixNano()) } // LookupVolumeIds queries the filer for volume locations with automatic failover @@ -757,10 +942,14 @@ func (p *filerVolumeProvider) LookupVolumeIds(ctx context.Context, volumeIds []s for retry := 0; retry < maxRetries; retry++ { // Try all filer addresses with round-robin starting from current index // Skip known-unhealthy filers (circuit breaker pattern) - i := atomic.LoadInt32(&fc.filerIndex) - - // Get filer count with read lock + // Get start index and filer count with read lock fc.filerAddressesMu.RLock() + i := int32(0) + var startFiler pb.ServerAddress + if len(fc.filerAddresses) > 0 { + i = fc.currentIndexPreferHomeLocked() + startFiler = fc.filerAddresses[i] + } n := int32(len(fc.filerAddresses)) fc.filerAddressesMu.RUnlock() @@ -870,7 +1059,12 @@ func (p *filerVolumeProvider) LookupVolumeIds(ctx context.Context, volumeIds []s } // Success - update the preferred filer index and reset health tracking - atomic.StoreInt32(&fc.filerIndex, i) + // Move only if the lookup had to leave the filer it started on, and + // only while that filer is still current: a lookup in flight when the + // client returned home must not count as leaving home. + if filerAddress != startFiler { + fc.SwitchCurrentFiler(startFiler, filerAddress) + } fc.recordFilerSuccessWithHealth(health) glog.V(3).Infof("FilerClient: looked up %d volumes on %s, found %d", len(volumeIds), filerAddress, len(result)) return result, nil diff --git a/weed/wdclient/filer_client_home_test.go b/weed/wdclient/filer_client_home_test.go new file mode 100644 index 0000000000..dfe4682a67 --- /dev/null +++ b/weed/wdclient/filer_client_home_test.go @@ -0,0 +1,458 @@ +package wdclient + +import ( + "context" + "fmt" + "net" + "reflect" + "sync" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +// An embedded S3 gateway is seeded with its local filer as "ip:port" while the +// filer registers in the master as "ip:port.grpcPort". Both name the same filer, +// so discovery must keep it in place, with its health, as the current filer. +func TestDiscoveryKeepsSeededFilerUnderRegisteredForm(t *testing.T) { + fc := newTestFilerClient("10.0.0.1:8888") + seededHealth := fc.filerHealth[0] + atomic.StoreInt32(&seededHealth.failureCount, 2) + + fc.applyDiscoveredFilers(map[pb.ServerAddress]struct{}{ + "10.0.0.1:8888.18888": {}, + "10.0.0.2:8888.18888": {}, + "10.0.0.3:8888.18888": {}, + }) + + want := []pb.ServerAddress{"10.0.0.1:8888.18888", "10.0.0.2:8888.18888", "10.0.0.3:8888.18888"} + if got := filerAddressList(fc); !reflect.DeepEqual(got, want) { + t.Fatalf("filer list: want %v, got %v", want, got) + } + if fc.filerHealth[0] != seededHealth { + t.Fatalf("seeded filer lost its health entry") + } + if got := atomic.LoadInt32(&fc.filerHealth[0].failureCount); got != 2 { + t.Fatalf("seeded filer health reset: want failureCount 2, got %d", got) + } + if got := fc.GetCurrentFiler(); got != "10.0.0.1:8888.18888" { + t.Fatalf("current filer: want the seeded local filer, got %s", got) + } +} + +func TestDiscoveryOrderIsDeterministic(t *testing.T) { + discovered := map[pb.ServerAddress]struct{}{ + "10.0.0.1:8888.18888": {}, + "10.0.0.2:8888.18888": {}, + "10.0.0.3:8888.18888": {}, + "10.0.0.4:8888.18888": {}, + } + var first []pb.ServerAddress + for i := 0; i < 200; i++ { + fc := newTestFilerClient("10.0.0.9:8888") + fc.applyDiscoveredFilers(discovered) + got := filerAddressList(fc) + if first == nil { + first = got + continue + } + if !reflect.DeepEqual(got, first) { + t.Fatalf("run %d: list order changed: %v vs %v", i, got, first) + } + } +} + +func TestDiscoveryCurrentGoneFallsToFirstSorted(t *testing.T) { + a := pb.ServerAddress("10.0.0.1:18888") + b := pb.ServerAddress("10.0.0.2:18888") + c := pb.ServerAddress("10.0.0.3:18888") + fc := newTestFilerClient(a, b) + atomic.StoreInt32(&fc.filerIndex, 1) + + fc.applyDiscoveredFilers(map[pb.ServerAddress]struct{}{a: {}, c: {}}) + + if got := fc.GetCurrentFiler(); got != a { + t.Fatalf("current filer: want %s, got %s", a, got) + } +} + +type fakeClock struct { + mu sync.Mutex + t time.Time +} + +func (c *fakeClock) now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.t +} + +func (c *fakeClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.t = c.t.Add(d) +} + +const ( + homeA = pb.ServerAddress("10.0.0.1:8888.18888") + peerB = pb.ServerAddress("10.0.0.2:8888.18888") +) + +// newHomeTestClient returns a client on [home, peer] whose home is the first +// filer, with the default breaker (3 failures, 30s reset) and a fake clock. +func newHomeTestClient(clock *fakeClock) *FilerClient { + fc := newTestFilerClient(homeA, peerB) + fc.failureThreshold = 3 + fc.resetTimeout = 30 * time.Second + fc.homeFiler = homeA + fc.homeBackoff = fc.resetTimeout + fc.now = clock.now + return fc +} + +// failHome trips the breaker on home and fails over to the peer. +func failHome(fc *FilerClient) { + for i := 0; i < 3; i++ { + fc.RecordFilerFailure(homeA) + } + fc.SetCurrentFiler(peerB) +} + +func TestHomeReturnAfterBreakerReset(t *testing.T) { + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + + failHome(fc) + if got := fc.GetCurrentFiler(); got != peerB { + t.Fatalf("after failover: want %s, got %s", peerB, got) + } + clock.advance(10 * time.Second) + if got := fc.GetCurrentFiler(); got != peerB { + t.Fatalf("home still in breaker: want %s, got %s", peerB, got) + } + clock.advance(21 * time.Second) + if got := fc.GetCurrentFiler(); got != homeA { + t.Fatalf("after breaker reset: want home %s, got %s", homeA, got) + } +} + +func TestHomeBackoffDoublesOnFlap(t *testing.T) { + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + + failHome(fc) + clock.advance(31 * time.Second) + if got := fc.GetCurrentFiler(); got != homeA { + t.Fatalf("first return: want home, got %s", got) + } + + clock.advance(9 * time.Second) // +40s: home fails again soon after the return + failHome(fc) + if fc.homeBackoff != 60*time.Second { + t.Fatalf("backoff after flap: want 60s, got %v", fc.homeBackoff) + } + clock.advance(55 * time.Second) // +95s: breaker reset, backoff not yet over + if got := fc.GetCurrentFiler(); got != peerB { + t.Fatalf("inside backoff: want %s, got %s", peerB, got) + } + clock.advance(6 * time.Second) // +101s + if got := fc.GetCurrentFiler(); got != homeA { + t.Fatalf("after backoff: want home, got %s", got) + } +} + +// flapUntilHome fails home over, waits until it is eligible again and returns. +func flapUntilHome(t *testing.T, fc *FilerClient, clock *fakeClock) { + t.Helper() + failHome(fc) + wait := fc.homeBackoff + if wait < fc.resetTimeout { + wait = fc.resetTimeout + } + clock.advance(wait + time.Second) + if got := fc.GetCurrentFiler(); got != homeA { + t.Fatalf("expected a return home, got %s", got) + } + clock.advance(time.Second) +} + +func TestHomeBackoffCapsAtFiveMinutes(t *testing.T) { + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + for i := 0; i < 6; i++ { + flapUntilHome(t, fc, clock) + } + failHome(fc) + if fc.homeBackoff != 5*time.Minute { + t.Fatalf("backoff: want 5m cap, got %v", fc.homeBackoff) + } +} + +func TestHomeBackoffResetsAfterHold(t *testing.T) { + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + flapUntilHome(t, fc, clock) + flapUntilHome(t, fc, clock) + if fc.homeBackoff != 60*time.Second { + t.Fatalf("setup: want backoff 60s, got %v", fc.homeBackoff) + } + + clock.advance(10*time.Minute + time.Second) + failHome(fc) + if fc.homeBackoff != 30*time.Second { + t.Fatalf("after a 10m hold: want backoff reset to 30s, got %v", fc.homeBackoff) + } +} + +func TestNoHomeKeepsStickyBehaviour(t *testing.T) { + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + fc.homeFiler = "" + + failHome(fc) + clock.advance(time.Hour) + if got := fc.GetCurrentFiler(); got != peerB { + t.Fatalf("without a home the client must stay put: want %s, got %s", peerB, got) + } +} + +func TestDiscoveryPrefersHealthyHomeWhenCurrentGone(t *testing.T) { + x := pb.ServerAddress("10.0.0.0:8888.18888") // sorts and stays first + home := pb.ServerAddress("10.0.0.3:8888.18888") + fc := newTestFilerClient(x, peerB, home) + fc.homeFiler = home + fc.failureThreshold = 3 + fc.resetTimeout = 30 * time.Second + atomic.StoreInt32(&fc.filerIndex, 1) // current is the peer that leaves + + fc.applyDiscoveredFilers(map[pb.ServerAddress]struct{}{x: {}, home: {}}) + + if got := fc.filerAddresses[atomic.LoadInt32(&fc.filerIndex)]; got != home { + t.Fatalf("current after discovery: want home %s, got %s", home, got) + } +} + +// countingFiler answers LookupVolume with no locations and counts the calls. +type countingFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + calls atomic.Int32 + onLookup func() // optional, runs inside each LookupVolume call +} + +func (s *countingFiler) LookupVolume(context.Context, *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) { + s.calls.Add(1) + if s.onLookup != nil { + s.onLookup() + } + return &filer_pb.LookupVolumeResponse{}, nil +} + +func startCountingFiler(t *testing.T) (pb.ServerAddress, *countingFiler) { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + srv := &countingFiler{} + grpcServer := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(grpcServer, srv) + go func() { _ = grpcServer.Serve(lis) }() + t.Cleanup(grpcServer.Stop) + _, port, _ := net.SplitHostPort(lis.Addr().String()) + return pb.ServerAddress(fmt.Sprintf("127.0.0.1:0.%s", port)), srv +} + +func TestLookupStartsFromEligibleHome(t *testing.T) { + home, homeSrv := startCountingFiler(t) + peer, peerSrv := startCountingFiler(t) + fc := newTestFilerClient(home, peer) + fc.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials()) + fc.grpcTimeout = 5 * time.Second + fc.maxRetries = 1 + fc.failureThreshold = 3 + fc.resetTimeout = 30 * time.Second + fc.homeFiler = home + atomic.StoreInt32(&fc.filerIndex, 1) // current is the peer + + if _, err := (&filerVolumeProvider{filerClient: fc}).LookupVolumeIds(context.Background(), []string{"4"}); err != nil { + t.Fatalf("lookup: %v", err) + } + if homeSrv.calls.Load() != 1 || peerSrv.calls.Load() != 0 { + t.Fatalf("lookup calls: home=%d peer=%d, want home=1 peer=0", homeSrv.calls.Load(), peerSrv.calls.Load()) + } +} + +// A lookup that started on the peer and finishes after the client has returned +// home must not drag the client back to the peer: home never failed. +func TestLookupInFlightDuringReturnDoesNotLeaveHome(t *testing.T) { + home, _ := startCountingFiler(t) + peer, peerSrv := startCountingFiler(t) + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newTestFilerClient(home, peer) + fc.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials()) + fc.grpcTimeout = 5 * time.Second + fc.maxRetries = 1 + fc.failureThreshold = 3 + fc.resetTimeout = 30 * time.Second + fc.homeFiler = home + fc.homeBackoff = fc.resetTimeout + fc.now = clock.now + + for i := 0; i < 3; i++ { + fc.RecordFilerFailure(home) + } + fc.SetCurrentFiler(peer) + clock.advance(10 * time.Second) // home still in breaker: the lookup starts on the peer + + peerSrv.onLookup = func() { + clock.advance(25 * time.Second) // home becomes eligible mid-lookup + if got := fc.GetCurrentFiler(); got != home { + t.Errorf("mid-lookup return: want home %s, got %s", home, got) + } + } + if _, err := (&filerVolumeProvider{filerClient: fc}).LookupVolumeIds(context.Background(), []string{"4"}); err != nil { + t.Fatalf("lookup: %v", err) + } + + if got := fc.filerAddresses[atomic.LoadInt32(&fc.filerIndex)]; got != home { + t.Fatalf("after the lookup: want current home %s, got %s", home, got) + } + if fc.homeBackoff != 30*time.Second { + t.Fatalf("backoff: want unchanged 30s, got %v", fc.homeBackoff) + } +} + +// A failover decided against a filer that is no longer current is stale and +// must not move the client. +func TestStaleFailoverDoesNotMoveClient(t *testing.T) { + peerC := pb.ServerAddress("10.0.0.3:8888.18888") + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newTestFilerClient(homeA, peerB, peerC) + fc.failureThreshold = 3 + fc.resetTimeout = 30 * time.Second + fc.homeFiler = homeA + fc.homeBackoff = fc.resetTimeout + fc.now = clock.now + + fc.SwitchCurrentFiler(peerB, peerC) // the caller saw B as current; it is home + + if got := fc.filerAddresses[atomic.LoadInt32(&fc.filerIndex)]; got != homeA { + t.Fatalf("stale failover moved the client to %s", got) + } + if !fc.homeEligibleAt.IsZero() { + t.Fatalf("stale failover started the return backoff") + } +} + +// Many requests failing on home at once are one departure from home, not many. +func TestConcurrentFailoversFromHomeCountOnce(t *testing.T) { + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + failHome(fc) + clock.advance(31 * time.Second) + if got := fc.GetCurrentFiler(); got != homeA { + t.Fatalf("setup: want home, got %s", got) + } + clock.advance(time.Second) + + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < 16; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + fc.SwitchCurrentFiler(homeA, peerB) + }() + } + close(start) + wg.Wait() + + if fc.homeBackoff != 60*time.Second { + t.Fatalf("backoff: want one doubling to 60s, got %v", fc.homeBackoff) + } +} + +// One failure leaves home's breaker closed, so only the backoff keeps the +// client on the peer. A request reading the current filer while another fails +// over from home must not see the peer before that backoff is in place, or it +// switches straight back home. +func TestFailoverFromHomeRacingReadKeepsBackoff(t *testing.T) { + for iter := 0; iter < 200; iter++ { + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + fc.RecordFilerFailure(homeA) + + var stop atomic.Bool + var ready, done sync.WaitGroup + for g := 0; g < 4; g++ { + ready.Add(1) + done.Add(1) + go func() { + defer done.Done() + fc.GetCurrentFiler() + ready.Done() + for !stop.Load() { + fc.GetCurrentFiler() + } + }() + } + ready.Wait() + fc.SwitchCurrentFiler(homeA, peerB) + stop.Store(true) + done.Wait() + + if got := fc.GetCurrentFiler(); got != peerB { + t.Fatalf("iteration %d: returned home inside the backoff, current %s", iter, got) + } + } +} + +// A home still inside its return backoff is not picked just because it is +// listed first when discovery removes the current filer. +func TestDiscoverySkipsBackingOffHomeWhenCurrentGone(t *testing.T) { + peerC := pb.ServerAddress("10.0.0.3:8888.18888") + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + fc.filerAddresses = []pb.ServerAddress{homeA, peerB, peerC} + fc.filerHealth = []*filerHealth{{}, {}, {}} + fc.RecordFilerFailure(homeA) + fc.SwitchCurrentFiler(homeA, peerB) + + fc.applyDiscoveredFilers(map[pb.ServerAddress]struct{}{homeA: {}, peerC: {}}) + + if got := fc.GetCurrentFiler(); got != peerC { + t.Fatalf("current after discovery: want %s, got %s", peerC, got) + } +} + +// Discovery landing on home is a return too: failing again soon after it +// doubles the backoff like any other flap. +func TestReturnHomeByDiscoveryCountsForBackoff(t *testing.T) { + peerC := pb.ServerAddress("10.0.0.3:8888.18888") + clock := &fakeClock{t: time.Unix(1_000_000, 0)} + fc := newHomeTestClient(clock) + fc.filerAddresses = []pb.ServerAddress{homeA, peerB, peerC} + fc.filerHealth = []*filerHealth{{}, {}, {}} + fc.RecordFilerFailure(homeA) + fc.SwitchCurrentFiler(homeA, peerB) + + clock.advance(31 * time.Second) + fc.applyDiscoveredFilers(map[pb.ServerAddress]struct{}{homeA: {}, peerC: {}}) + if got := fc.filerAddresses[atomic.LoadInt32(&fc.filerIndex)]; got != homeA { + t.Fatalf("setup: want discovery to return home, got %s", got) + } + + clock.advance(9 * time.Second) + fc.RecordFilerFailure(homeA) + fc.SwitchCurrentFiler(homeA, peerC) + if fc.homeBackoff != 60*time.Second { + t.Fatalf("backoff after a flap following a discovery return: want 60s, got %v", fc.homeBackoff) + } +}