Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
11 changes: 9 additions & 2 deletions kms/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 48 additions & 0 deletions kms/client_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
179 changes: 152 additions & 27 deletions kms/internal/https/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -109,69 +136,167 @@ 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
}
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
Expand Down
Loading
Loading