client-go/rest: backoff with context support

The BackoffManager interface sleeps without considering the caller's context,
i.e. cancellation is not supported. This alone is reason enough to deprecate it
and to replace it with an interface that supports a context parameter.

The other reason is that contextual logging needs that parameter.

Kubernetes-commit: b15a1943d51adfb8c5e0185d58d25e038c3d6ade
This commit is contained in:
Patrick Ohly
2024-09-02 20:18:47 +02:00
committed by Kubernetes Publisher
parent 2b2015d460
commit 7aa9904196
11 changed files with 421 additions and 57 deletions

View File

@@ -35,6 +35,7 @@ import (
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
utiltesting "k8s.io/client-go/util/testing"
"k8s.io/klog/v2/ktesting"
"github.com/google/go-cmp/cmp"
)
@@ -335,26 +336,26 @@ func TestHTTPProxy(t *testing.T) {
}
func TestCreateBackoffManager(t *testing.T) {
_, ctx := ktesting.NewTestContext(t)
theUrl, _ := url.Parse("http://localhost")
// 1 second base backoff + duration of 2 seconds -> exponential backoff for requests.
t.Setenv(envBackoffBase, "1")
t.Setenv(envBackoffDuration, "2")
backoff := readExpBackoffConfig()
backoff.UpdateBackoff(theUrl, nil, 500)
backoff.UpdateBackoff(theUrl, nil, 500)
if backoff.CalculateBackoff(theUrl)/time.Second != 2 {
backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500)
backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500)
if backoff.CalculateBackoffWithContext(ctx, theUrl)/time.Second != 2 {
t.Errorf("Backoff env not working.")
}
// 0 duration -> no backoff.
t.Setenv(envBackoffBase, "1")
t.Setenv(envBackoffDuration, "0")
backoff.UpdateBackoff(theUrl, nil, 500)
backoff.UpdateBackoff(theUrl, nil, 500)
backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500)
backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500)
backoff = readExpBackoffConfig()
if backoff.CalculateBackoff(theUrl)/time.Second != 0 {
if backoff.CalculateBackoffWithContext(ctx, theUrl)/time.Second != 0 {
t.Errorf("Zero backoff duration, but backoff still occurring.")
}
@@ -362,9 +363,9 @@ func TestCreateBackoffManager(t *testing.T) {
t.Setenv(envBackoffBase, "")
t.Setenv(envBackoffDuration, "")
backoff = readExpBackoffConfig()
backoff.UpdateBackoff(theUrl, nil, 500)
backoff.UpdateBackoff(theUrl, nil, 500)
if backoff.CalculateBackoff(theUrl)/time.Second != 0 {
backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500)
backoff.UpdateBackoffWithContext(ctx, theUrl, nil, 500)
if backoff.CalculateBackoffWithContext(ctx, theUrl)/time.Second != 0 {
t.Errorf("Backoff should have been 0.")
}