diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index d63268f..e40c14d 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -44,7 +44,7 @@ jobs: go-version-file: 'kms/go.mod' - name: Test run: | - go test ./kms ./kes + go test ./kms/... ./kes/... vulncheck: name: Vulncheck @@ -58,7 +58,9 @@ jobs: with: go-version-file: 'kms/go.mod' - name: Get govulncheck - run: go install golang.org/x/vuln/cmd/govulncheck@latest + # Pinned because govulncheck's Go floor moves ahead of the toolchain + # this workflow derives from kms/go.mod: v1.8.0 requires Go 1.26. + run: go install golang.org/x/vuln/cmd/govulncheck@v1.7.0 shell: bash - name: Run govulncheck env: diff --git a/kms/client.go b/kms/client.go index 6c334fd..8c1edc8 100644 --- a/kms/client.go +++ b/kms/client.go @@ -132,11 +132,18 @@ func NewClient(conf *Config) (*Client, error) { Hosts: hosts, RoundTripper: transport, } - return &Client{ + client := &Client{ direct: http.Client{Transport: lb.RoundTripper}, client: http.Client{Transport: lb}, lb: lb, - }, nil + } + + // Live does not send its request through the load balancer, which + // would never select a suspended host. + lb.Probe = func(ctx context.Context, host string) error { + return client.Live(ctx, &LivenessRequest{Hosts: []string{host}}) + } + return client, nil } // Client is a KMS client. It performs client-side load balancing diff --git a/kms/client_test.go b/kms/client_test.go new file mode 100644 index 0000000..15c15df --- /dev/null +++ b/kms/client_test.go @@ -0,0 +1,48 @@ +// Copyright 2025 - MinIO, Inc. All rights reserved. +// Use of this source code is governed by the AGPLv3 +// license that can be found in the LICENSE file. + +package kms + +import ( + "context" + "net/http" + "testing" + + "github.com/minio/kms-go/kms/internal/api" +) + +type recordingRoundTripper struct { + paths chan string +} + +// RoundTrip records the path it was asked for and replies with 200 OK. +func (r *recordingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + r.paths <- req.URL.Path + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil +} + +// A client must probe a suspended host for liveness. Without a probe, +// the load balancer re-admits a host on a timer, even one that is +// still unreachable. +func TestNewClientProbesForLiveness(t *testing.T) { + transport := &recordingRoundTripper{paths: make(chan string, 1)} + + client, err := NewClient(&Config{ + Endpoints: []string{"kms-0.local:7373"}, + Transport: transport, + }) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + if client.lb.Probe == nil { + t.Fatal("NewClient did not configure a probe") + } + + if err := client.lb.Probe(context.Background(), "kms-1.local:7373"); err != nil { + t.Fatalf("Probe: %v", err) + } + if path := <-transport.paths; path != api.PathHealthLive { + t.Fatalf("Probe requested %q, want %q", path, api.PathHealthLive) + } +} diff --git a/kms/internal/https/retry.go b/kms/internal/https/retry.go index 9d1de9c..48dfccc 100644 --- a/kms/internal/https/retry.go +++ b/kms/internal/https/retry.go @@ -27,8 +27,11 @@ import ( // If a request to one of these hosts fails, the LoadBalancer retries // the request with different hosts until either the request succeeds // or there are no hosts remaining resp. the retry limit is reached. -// Hosts for which requests fail are temporarily excluded and no longer -// selected for subsequent requests. +// Hosts for which requests fail are suspended and no longer selected +// for subsequent requests. +// +// A suspended host is re-admitted once a Probe of that host succeeds. +// Without a Probe, it is re-admitted after Timeout elapsed. type LoadBalancer struct { // Underlying RoundTripper used to send requests. http.RoundTripper @@ -40,17 +43,41 @@ type LoadBalancer struct { // request. Hosts []string - // Timeout controls how long a host is excluded if a + // Timeout controls how long a host is suspended if a // request to this host fails. If 0, defaults to 30 // seconds. + // + // It is only used if Probe is nil. Timeout time.Duration + // Probe reports whether a host is able to serve requests. + // It should return a nil error if, and only if, the host + // responded. + // + // If Probe is not nil, a suspended host is only re-admitted + // once a Probe of that host succeeds. An unreachable host + // therefore stays suspended instead of being re-admitted on + // a timer while it is still unreachable. + // + // Probe must not send its requests through the LoadBalancer + // itself since the LoadBalancer does not select suspended + // hosts. + Probe func(ctx context.Context, host string) error + + // ProbeInterval is the delay between two rounds of probing + // the suspended hosts. If 0, defaults to 5 seconds. A probe + // is canceled once ProbeInterval elapsed. + // + // It is only used if Probe is not nil. + ProbeInterval time.Duration + // Retry specifies how often the LoadBalancer retries // a request with different hosts bef Retry int mu sync.RWMutex timeout map[string]time.Time + probing bool } // URL returns an URL string with the next host and the provided @@ -85,14 +112,14 @@ func (lb *LoadBalancer) Host() (string, error) { case 1: return lb.Hosts[0], nil default: - t, r := timeout(lb.Timeout), rand.Intn(len(lb.Hosts)) + r := rand.Intn(len(lb.Hosts)) lb.mu.RLock() defer lb.mu.RUnlock() now := time.Now() for i := 0; i < len(lb.Hosts); i++ { - if timeout, ok := lb.timeout[lb.Hosts[r]]; !ok || now.Sub(timeout) > t { + if !lb.isSuspended(lb.Hosts[r], now) { return lb.Hosts[r], nil } r = (r + 1) % len(lb.Hosts) @@ -109,51 +136,131 @@ func (lb *LoadBalancer) Host() (string, error) { // succeeded before. It stops retrying once the request succeeds, // there are no more non-suspended hosts remaining or the retry limit // is reached. -// Hosts, for which requests fail, are temporarily excluded and no longer -// selected for subsequent requests or retries. +// Hosts, for which requests fail, are suspended and no longer selected +// for subsequent requests or retries. func (lb *LoadBalancer) RoundTrip(req *http.Request) (*http.Response, error) { resp, err := lb.RoundTripper.RoundTrip(req) - if err != nil && isRetryable(err) { + if err != nil && isRetryable(req.Context(), err) { r := slices.Index(lb.Hosts, req.URL.Host) if r < 0 { return resp, err } + lb.suspend(req.URL.Host) now := time.Now() - lb.mu.Lock() - if lb.timeout == nil { - lb.timeout = map[string]time.Time{} - } - lb.timeout[req.URL.Host] = now - lb.mu.Unlock() - - t := timeout(lb.Timeout) for i := 1; i < len(lb.Hosts); i++ { r = (r + 1) % len(lb.Hosts) lb.mu.RLock() - timeout, ok := lb.timeout[lb.Hosts[r]] + suspended := lb.isSuspended(lb.Hosts[r], now) lb.mu.RUnlock() - if ok && now.Sub(timeout) < t { + if suspended { continue } closeResponseBody(resp) req.URL.Host = lb.Hosts[r] resp, err = lb.RoundTripper.RoundTrip(req) - if err == nil || !isRetryable(err) { + if err == nil || !isRetryable(req.Context(), err) { return resp, err } - - lb.mu.Lock() - lb.timeout[req.URL.Host] = time.Now() - lb.mu.Unlock() + lb.suspend(req.URL.Host) } } return resp, err } +// suspend excludes host from host selection. It starts probing the +// suspended hosts if lb re-admits hosts based on Probe and no probing +// is in progress. +func (lb *LoadBalancer) suspend(host string) { + lb.mu.Lock() + defer lb.mu.Unlock() + + if lb.timeout == nil { + lb.timeout = map[string]time.Time{} + } + lb.timeout[host] = time.Now() + + if lb.Probe != nil && !lb.probing { + lb.probing = true + go lb.probeHosts() + } +} + +// resume re-admits host to host selection. +func (lb *LoadBalancer) resume(host string) { + lb.mu.Lock() + delete(lb.timeout, host) + lb.mu.Unlock() +} + +// isSuspended reports whether host is currently excluded from host +// selection. Callers must hold lb.mu. +func (lb *LoadBalancer) isSuspended(host string, now time.Time) bool { + t, ok := lb.timeout[host] + if !ok { + return false + } + if lb.Probe != nil { + return true + } + return now.Sub(t) <= timeout(lb.Timeout) +} + +// probeHosts probes all suspended hosts, once per ProbeInterval, and +// re-admits those that respond. It returns once no host is suspended +// anymore. A new probeHosts is started by the next suspend. +func (lb *LoadBalancer) probeHosts() { + interval := probeInterval(lb.ProbeInterval) + for { + hosts := lb.suspendedHosts() + if len(hosts) == 0 { + return + } + + var wg sync.WaitGroup + for _, host := range hosts { + wg.Add(1) + go func() { + defer wg.Done() + + ctx, cancel := context.WithTimeout(context.Background(), interval) + defer cancel() + + if lb.Probe(ctx, host) == nil { + lb.resume(host) + } + }() + } + wg.Wait() + + time.Sleep(interval) + } +} + +// suspendedHosts returns the currently suspended hosts. It stops +// probing if no host is suspended, such that the emptiness check +// and the hand-off to the next suspend happen atomically. +func (lb *LoadBalancer) suspendedHosts() []string { + lb.mu.Lock() + defer lb.mu.Unlock() + + if len(lb.timeout) == 0 { + lb.probing = false + return nil + } + + hosts := make([]string, 0, len(lb.timeout)) + for host := range lb.timeout { + hosts = append(hosts, host) + } + return hosts +} + +// timeout returns how long a host stays suspended when no Probe decides +// about it, defaulting to 30 seconds. func timeout(d time.Duration) time.Duration { if d <= 0 { return 30 * time.Second @@ -161,17 +268,35 @@ func timeout(d time.Duration) time.Duration { return d } -func isRetryable(err error) bool { +// probeInterval returns the delay between two probe rounds, defaulting +// to 5 seconds. +func probeInterval(d time.Duration) time.Duration { + if d <= 0 { + return 5 * time.Second + } + return d +} + +// isRetryable reports whether a request that failed with err should be +// retried with a different host, and therefore whether the host it was +// sent to should be suspended. +func isRetryable(ctx context.Context, err error) bool { if err == nil { return false } - if errors.Is(err, context.Canceled) { + + // A dial or I/O timeout also matches context.DeadlineExceeded since + // net.Dialer implements its Timeout with a context deadline. Only an + // expired request context tells the two apart: the caller is gone, so + // no retry can succeed and the host is not at fault. + if ctx.Err() != nil { return false } - - return true + return !errors.Is(err, context.Canceled) } +// closeResponseBody drains and closes the body of a response that is +// being discarded, so that its connection can be reused. func closeResponseBody(resp *http.Response) { if resp == nil || resp.Body == nil { return diff --git a/kms/internal/https/retry_test.go b/kms/internal/https/retry_test.go new file mode 100644 index 0000000..e0b91d6 --- /dev/null +++ b/kms/internal/https/retry_test.go @@ -0,0 +1,276 @@ +// Copyright 2025 - MinIO, Inc. All rights reserved. +// Use of this source code is governed by the AGPLv3 +// license that can be found in the LICENSE file. + +package https + +import ( + "context" + "errors" + "net/http" + "net/url" + "testing" + "time" +) + +// errDown is returned by probes and round trips for a host that is down. +var errDown = errors.New("host is down") + +// roundTripFunc is an http.RoundTripper that reports which hosts it +// was asked for. +type roundTripFunc func(*http.Request) (*http.Response, error) + +// RoundTrip calls f. +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } + +// Host must not return a suspended host while other hosts are available. +func TestLoadBalancerHostSkipsSuspendedHost(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b", "c"}, + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + lb.suspend("b") + + for i := 0; i < 100; i++ { + host, err := lb.Host() + if err != nil { + t.Fatalf("Host: %v", err) + } + if host == "b" { + t.Fatal("Host returned the suspended host 'b'") + } + } +} + +// Host must still return a host once every host is suspended, so that a +// client keeps making progress during a full outage. +func TestLoadBalancerHostWithAllHostsSuspended(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b", "c"}, + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + for _, host := range lb.Hosts { + lb.suspend(host) + } + + host, err := lb.Host() + if err != nil { + t.Fatalf("Host: %v", err) + } + if host == "" { + t.Fatal("Host returned no host while all hosts are suspended") + } +} + +// A host that does not respond must stay suspended even after Timeout +// elapsed. This is the behavior probing exists for: re-admitting an +// unreachable host on a timer makes every client pay its dial timeout +// again. +func TestLoadBalancerProbeKeepsUnresponsiveHostSuspended(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + Timeout: time.Millisecond, + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Millisecond, + } + lb.suspend("a") + + // Well past Timeout, which must not re-admit a host that a Probe + // decides about. + time.Sleep(20 * time.Millisecond) + + for i := 0; i < 100; i++ { + if host, _ := lb.Host(); host != "b" { + t.Fatalf("Host = %q, want the only host that responds", host) + } + } +} + +// A suspended host must be re-admitted once, and only once, a probe of it +// succeeds. Probing must then stop, so that it does not outlive the +// outage. +func TestLoadBalancerProbeReadmitsHostOnlyOnceItResponds(t *testing.T) { + live := make(chan struct{}) + probed := make(chan string, 1024) + + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + ProbeInterval: time.Millisecond, + } + lb.Probe = func(_ context.Context, host string) error { + probed <- host + select { + case <-live: + return nil + default: + return errDown + } + } + lb.suspend("a") + + // For as long as 'a' does not respond, it must not be re-admitted, + // however often it is probed. + for i := 0; i < 5; i++ { + if host := <-probed; host != "a" { + t.Fatalf("probed host = %q, want the suspended host 'a'", host) + } + if host, _ := lb.Host(); host != "b" { + t.Fatalf("Host = %q, want the only host that is not suspended", host) + } + } + + close(live) + waitFor(t, "'a' to be re-admitted once it responds", func() bool { + return !lb.suspended("a") + }) + + // Once no host is suspended anymore, probing must stop so that it + // does not outlive the outage. + waitFor(t, "probing to stop", func() bool { + lb.mu.RLock() + defer lb.mu.RUnlock() + return !lb.probing + }) +} + +// Without a Probe, Timeout keeps its previous meaning and re-admits a +// suspended host once it elapsed. +func TestLoadBalancerTimeoutReadmitsHostWithoutProbe(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + Timeout: 10 * time.Millisecond, + } + lb.suspend("a") + + if host, _ := lb.Host(); host != "b" { + t.Fatalf("Host = %q, want the only host that is not suspended", host) + } + + waitFor(t, "'a' to be re-admitted after the timeout elapsed", func() bool { + for i := 0; i < 100; i++ { + if host, _ := lb.Host(); host == "a" { + return true + } + } + return false + }) +} + +// RoundTrip must retry a failed request with another host, suspend the +// host it failed for, and start probing that host. +func TestLoadBalancerRoundTripSuspendsFailedHost(t *testing.T) { + probed := make(chan string, 1024) + + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + RoundTripper: roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host == "a" { + return nil, errDown + } + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }), + ProbeInterval: time.Millisecond, + } + lb.Probe = func(_ context.Context, host string) error { + probed <- host + return errDown + } + + resp, err := lb.RoundTrip(&http.Request{URL: &url.URL{Scheme: "https", Host: "a"}}) + if err != nil { + t.Fatalf("RoundTrip did not retry the request with a different host: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("StatusCode = %d, want %d", resp.StatusCode, http.StatusOK) + } + if !lb.suspended("a") { + t.Fatal("RoundTrip did not suspend the host its request failed for") + } + if host := <-probed; host != "a" { + t.Fatalf("probed host = %q, want the suspended host 'a'", host) + } +} + +// suspended reports whether host is currently suspended. It exists for +// tests only; production code consults isSuspended while holding lb.mu. +func (lb *LoadBalancer) suspended(host string) bool { + lb.mu.RLock() + defer lb.mu.RUnlock() + + _, ok := lb.timeout[host] + return ok +} + +// waitFor polls cond until it holds, and fails the test if it does not +// within a fixed timeout. +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + + const Timeout = 10 * time.Second + for deadline := time.Now().Add(Timeout); time.Now().Before(deadline); { + if cond() { + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("timed out after %v waiting for %s", Timeout, what) +} + +// A dial timeout matches context.DeadlineExceeded because net.Dialer +// implements its Timeout with a context deadline. It is the error an +// unreachable host produces, so it must suspend that host. +func TestLoadBalancerRoundTripSuspendsHostOnTimeoutWithLiveContext(t *testing.T) { + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + RoundTripper: roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host == "a" { + return nil, context.DeadlineExceeded + } + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + }), + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + + resp, err := lb.RoundTrip(&http.Request{URL: &url.URL{Scheme: "https", Host: "a"}}) + if err != nil { + t.Fatalf("RoundTrip did not retry the request with a different host: %v", err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("StatusCode = %d, want %d", resp.StatusCode, http.StatusOK) + } + if !lb.suspended("a") { + t.Fatal("RoundTrip did not suspend the host that timed out") + } +} + +// An expired request context means the caller is gone, not that the host +// is unhealthy. RoundTrip must neither suspend the host nor retry. +func TestLoadBalancerRoundTripKeepsHostOnCallerTimeout(t *testing.T) { + hosts := make(chan string, 1024) + lb := &LoadBalancer{ + Hosts: []string{"a", "b"}, + RoundTripper: roundTripFunc(func(req *http.Request) (*http.Response, error) { + hosts <- req.URL.Host + return nil, context.DeadlineExceeded + }), + Probe: func(context.Context, string) error { return errDown }, + ProbeInterval: time.Hour, + } + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + req := (&http.Request{URL: &url.URL{Scheme: "https", Host: "a"}}).WithContext(ctx) + if _, err := lb.RoundTrip(req); err == nil { + t.Fatal("RoundTrip did not return the caller's error") + } + if lb.suspended("a") { + t.Fatal("RoundTrip suspended a host because the caller's context expired") + } + if len(hosts) != 1 { + t.Fatalf("RoundTrip sent %d requests, want 1 - it must not retry for a caller that is gone", len(hosts)) + } +}