Skip to content

Commit 56f27d6

Browse files
committed
Use context.WithTimeoutCause and context.WithCancelCause for better readability
1 parent 2f5d70a commit 56f27d6

File tree

12 files changed

+33
-31
lines changed

12 files changed

+33
-31
lines changed

cmd/clusterctl/client/repository/repository_gitlab.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ func (g *gitLabRepository) GetFile(ctx context.Context, version, path string) ([
147147
return content, nil
148148
}
149149

150-
timeoutctx, cancel := context.WithTimeout(ctx, 30*time.Second)
150+
timeoutctx, cancel := context.WithTimeoutCause(ctx, 30*time.Second, errors.New("http request timeout expired"))
151151
defer cancel()
152152
request, err := http.NewRequestWithContext(timeoutctx, http.MethodGet, url, http.NoBody)
153153
if err != nil {

controllers/clustercache/cluster_accessor_client.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ func createCachedClient(ctx context.Context, clusterAccessorConfig *clusterAcces
228228

229229
// Use a context that is independent of the passed in context, so the cache doesn't get stopped
230230
// when the passed in context is canceled.
231-
cacheCtx, cacheCtxCancel := context.WithCancel(context.Background())
231+
cacheCtx, cacheCtxCancel := context.WithCancelCause(context.Background())
232232

233233
// We need to be able to stop the cache's shared informers, so wrap this in a stoppableCache.
234234
cache := &stoppableCache{
@@ -261,7 +261,7 @@ func createCachedClient(ctx context.Context, clusterAccessorConfig *clusterAcces
261261
go cache.Start(cacheCtx) //nolint:errcheck
262262

263263
// Wait until the cache is initially synced.
264-
cacheSyncCtx, cacheSyncCtxCancel := context.WithTimeout(ctx, clusterAccessorConfig.Cache.InitialSyncTimeout)
264+
cacheSyncCtx, cacheSyncCtxCancel := context.WithTimeoutCause(ctx, clusterAccessorConfig.Cache.InitialSyncTimeout, errors.New("initial sync timeout expired"))
265265
defer cacheSyncCtxCancel()
266266
if !cache.WaitForCacheSync(cacheSyncCtx) {
267267
cache.Stop()
@@ -297,13 +297,13 @@ type clientWithTimeout struct {
297297
var _ client.Client = &clientWithTimeout{}
298298

299299
func (c clientWithTimeout) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
300-
ctx, cancel := context.WithTimeout(ctx, c.timeout)
300+
ctx, cancel := context.WithTimeoutCause(ctx, c.timeout, errors.New("call timeout expired"))
301301
defer cancel()
302302
return c.Client.Get(ctx, key, obj, opts...)
303303
}
304304

305305
func (c clientWithTimeout) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
306-
ctx, cancel := context.WithTimeout(ctx, c.timeout)
306+
ctx, cancel := context.WithTimeoutCause(ctx, c.timeout, errors.New("call timeout expired"))
307307
defer cancel()
308308
return c.Client.List(ctx, list, opts...)
309309
}
@@ -314,7 +314,7 @@ type stoppableCache struct {
314314

315315
lock sync.Mutex
316316
stopped bool
317-
cancelFunc context.CancelFunc
317+
cancelFunc context.CancelCauseFunc
318318
}
319319

320320
// Stop cancels the cache.Cache's context, unless it has already been stopped.
@@ -327,5 +327,5 @@ func (cc *stoppableCache) Stop() {
327327
}
328328

329329
cc.stopped = true
330-
cc.cancelFunc()
330+
cc.cancelFunc(errors.New("stoppable cache context cancelled"))
331331
}

controllers/remote/cluster_cache_healthcheck_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"time"
2626

2727
. "github.com/onsi/gomega"
28+
"github.com/pkg/errors"
2829
corev1 "k8s.io/api/core/v1"
2930
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
3031
"k8s.io/apimachinery/pkg/runtime"
@@ -106,7 +107,7 @@ func TestClusterCacheHealthCheck(t *testing.T) {
106107

107108
testClusterKey = util.ObjectKey(testCluster)
108109

109-
_, cancel := context.WithCancel(ctx)
110+
_, cancel := context.WithCancelCause(ctx)
110111
cc = &stoppableCache{cancelFunc: cancel}
111112
cct.clusterAccessors[testClusterKey] = &clusterAccessor{cache: cc}
112113

@@ -123,7 +124,7 @@ func TestClusterCacheHealthCheck(t *testing.T) {
123124
t.Log("Deleting Namespace")
124125
g.Expect(env.Delete(ctx, ns)).To(Succeed())
125126
t.Log("Stopping the manager")
126-
cc.cancelFunc()
127+
cc.cancelFunc(errors.New("context cancelled"))
127128
mgrCancel()
128129
}
129130

controllers/remote/cluster_cache_tracker.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,7 @@ func (t *ClusterCacheTracker) createCachedClient(ctx context.Context, config *re
514514

515515
// Use a context that is independent of the passed in context, so the cache doesn't get stopped
516516
// when the passed in context is canceled.
517-
cacheCtx, cacheCtxCancel := context.WithCancel(context.Background())
517+
cacheCtx, cacheCtxCancel := context.WithCancelCause(context.Background())
518518

519519
// We need to be able to stop the cache's shared informers, so wrap this in a stoppableCache.
520520
cache := &stoppableCache{
@@ -547,7 +547,7 @@ func (t *ClusterCacheTracker) createCachedClient(ctx context.Context, config *re
547547
go cache.Start(cacheCtx) //nolint:errcheck
548548

549549
// Wait until the cache is initially synced
550-
cacheSyncCtx, cacheSyncCtxCancel := context.WithTimeout(ctx, initialCacheSyncTimeout)
550+
cacheSyncCtx, cacheSyncCtxCancel := context.WithTimeoutCause(ctx, initialCacheSyncTimeout, errors.New("initial sync timeout expired"))
551551
defer cacheSyncCtxCancel()
552552
if !cache.WaitForCacheSync(cacheSyncCtx) {
553553
cache.Stop()
@@ -774,13 +774,13 @@ type clientWithTimeout struct {
774774
var _ client.Client = &clientWithTimeout{}
775775

776776
func (c clientWithTimeout) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
777-
ctx, cancel := context.WithTimeout(ctx, c.timeout)
777+
ctx, cancel := context.WithTimeoutCause(ctx, c.timeout, errors.New("call timeout expired"))
778778
defer cancel()
779779
return c.Client.Get(ctx, key, obj, opts...)
780780
}
781781

782782
func (c clientWithTimeout) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
783-
ctx, cancel := context.WithTimeout(ctx, c.timeout)
783+
ctx, cancel := context.WithTimeoutCause(ctx, c.timeout, errors.New("call timeout expired"))
784784
defer cancel()
785785
return c.Client.List(ctx, list, opts...)
786786
}

controllers/remote/stoppable_cache.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"context"
2121
"sync"
2222

23+
"github.com/pkg/errors"
2324
"sigs.k8s.io/controller-runtime/pkg/cache"
2425
)
2526

@@ -29,7 +30,7 @@ type stoppableCache struct {
2930

3031
lock sync.Mutex
3132
stopped bool
32-
cancelFunc context.CancelFunc
33+
cancelFunc context.CancelCauseFunc
3334
}
3435

3536
// Stop cancels the cache.Cache's context, unless it has already been stopped.
@@ -42,5 +43,5 @@ func (cc *stoppableCache) Stop() {
4243
}
4344

4445
cc.stopped = true
45-
cc.cancelFunc()
46+
cc.cancelFunc(errors.New("stoppable cache context cancelled"))
4647
}

controlplane/kubeadm/internal/etcd/etcd.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ func newEtcdClient(ctx context.Context, etcdClient etcd, callTimeout time.Durati
176176
return nil, errors.New("etcd client was not configured with any endpoints")
177177
}
178178

179-
ctx, cancel := context.WithTimeout(ctx, callTimeout)
179+
ctx, cancel := context.WithTimeoutCause(ctx, callTimeout, errors.New("call timeout expired"))
180180
defer cancel()
181181

182182
status, err := etcdClient.Status(ctx, endpoints[0])
@@ -200,7 +200,7 @@ func (c *Client) Close() error {
200200

201201
// Members retrieves a list of etcd members.
202202
func (c *Client) Members(ctx context.Context) ([]*Member, error) {
203-
ctx, cancel := context.WithTimeout(ctx, c.CallTimeout)
203+
ctx, cancel := context.WithTimeoutCause(ctx, c.CallTimeout, errors.New("call timeout expired"))
204204
defer cancel()
205205

206206
response, err := c.EtcdClient.MemberList(ctx)
@@ -231,7 +231,7 @@ func (c *Client) Members(ctx context.Context) ([]*Member, error) {
231231

232232
// MoveLeader moves the leader to the provided member ID.
233233
func (c *Client) MoveLeader(ctx context.Context, newLeaderID uint64) error {
234-
ctx, cancel := context.WithTimeout(ctx, c.CallTimeout)
234+
ctx, cancel := context.WithTimeoutCause(ctx, c.CallTimeout, errors.New("call timeout expired"))
235235
defer cancel()
236236

237237
_, err := c.EtcdClient.MoveLeader(ctx, newLeaderID)
@@ -240,7 +240,7 @@ func (c *Client) MoveLeader(ctx context.Context, newLeaderID uint64) error {
240240

241241
// RemoveMember removes a given member.
242242
func (c *Client) RemoveMember(ctx context.Context, id uint64) error {
243-
ctx, cancel := context.WithTimeout(ctx, c.CallTimeout)
243+
ctx, cancel := context.WithTimeoutCause(ctx, c.CallTimeout, errors.New("call timeout expired"))
244244
defer cancel()
245245

246246
_, err := c.EtcdClient.MemberRemove(ctx, id)
@@ -249,7 +249,7 @@ func (c *Client) RemoveMember(ctx context.Context, id uint64) error {
249249

250250
// UpdateMemberPeerURLs updates the list of peer URLs.
251251
func (c *Client) UpdateMemberPeerURLs(ctx context.Context, id uint64, peerURLs []string) ([]*Member, error) {
252-
ctx, cancel := context.WithTimeout(ctx, c.CallTimeout)
252+
ctx, cancel := context.WithTimeoutCause(ctx, c.CallTimeout, errors.New("call timeout expired"))
253253
defer cancel()
254254

255255
response, err := c.EtcdClient.MemberUpdate(ctx, id, peerURLs)
@@ -267,7 +267,7 @@ func (c *Client) UpdateMemberPeerURLs(ctx context.Context, id uint64, peerURLs [
267267

268268
// Alarms retrieves all alarms on a cluster.
269269
func (c *Client) Alarms(ctx context.Context) ([]MemberAlarm, error) {
270-
ctx, cancel := context.WithTimeout(ctx, c.CallTimeout)
270+
ctx, cancel := context.WithTimeoutCause(ctx, c.CallTimeout, errors.New("call timeout expired"))
271271
defer cancel()
272272

273273
alarmResponse, err := c.EtcdClient.AlarmList(ctx)

exp/runtime/internal/controllers/warmup.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func (r *warmupRunnable) Start(ctx context.Context) error {
6969
if r.warmupTimeout == 0 {
7070
r.warmupTimeout = defaultWarmupTimeout
7171
}
72-
ctx, cancel := context.WithTimeout(ctx, r.warmupTimeout)
72+
ctx, cancel := context.WithTimeoutCause(ctx, r.warmupTimeout, errors.New("warmup timeout expired"))
7373
defer cancel()
7474

7575
err := wait.PollUntilContextTimeout(ctx, r.warmupInterval, r.warmupTimeout, true, func(ctx context.Context) (done bool, err error) {

hack/tools/internal/log-push/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ func getLogsFromGCS(ctx context.Context, logPath string, logFileRegex *regexp.Re
170170
klog.Infof("Getting logs from gs://%s/%s", bucket, folder)
171171

172172
// Set timeout.
173-
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
173+
ctx, cancel := context.WithTimeoutCause(ctx, 2*time.Minute, errors.New("new client timeout expired"))
174174
defer cancel()
175175

176176
// Create GCS client.

hack/tools/internal/tilt-prepare/main.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -458,8 +458,8 @@ func runTaskGroup(ctx context.Context, name string, tasks map[string]taskFunctio
458458
}(time.Now())
459459

460460
// Create a context to be used for canceling all the tasks when another fails.
461-
ctx, cancel := context.WithCancel(ctx)
462-
defer cancel()
461+
ctx, cancel := context.WithCancelCause(ctx)
462+
defer cancel(errors.New("run task group context cancelled"))
463463

464464
// Make channels to pass fatal errors in WaitGroup
465465
errors := make(chan error)
@@ -483,7 +483,7 @@ func runTaskGroup(ctx context.Context, name string, tasks map[string]taskFunctio
483483
break
484484
case err := <-errors:
485485
// cancel all the running tasks
486-
cancel()
486+
cancel(err)
487487
// consumes all the errors from the channel
488488
errList := []error{err}
489489
Loop:

internal/controllers/machine/drain/drain.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ func (d *Helper) EvictPods(ctx context.Context, podDeleteList *PodDeleteList) Ev
304304

305305
// Trigger evictions for at most 10s. We'll continue on the next reconcile if we hit the timeout.
306306
evictionTimeout := 10 * time.Second
307-
ctx, cancel := context.WithTimeout(ctx, evictionTimeout)
307+
ctx, cancel := context.WithTimeoutCause(ctx, evictionTimeout, errors.New("eviction timeout expired"))
308308
defer cancel()
309309

310310
res := EvictionResult{

0 commit comments

Comments
 (0)