Skip to content

Commit 10d6c8a

Browse files
committed
Use context.WithTimeoutCause and context.WithCancelCause for better readability
1 parent 010af7f commit 10d6c8a

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
@@ -242,7 +242,7 @@ func createCachedClient(ctx, cacheCtx context.Context, clusterAccessorConfig *cl
242242

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

247247
// We need to be able to stop the cache's shared informers, so wrap this in a stoppableCache.
248248
cache := &stoppableCache{
@@ -275,7 +275,7 @@ func createCachedClient(ctx, cacheCtx context.Context, clusterAccessorConfig *cl
275275
go cache.Start(cacheCtx) //nolint:errcheck
276276

277277
// Wait until the cache is initially synced.
278-
cacheSyncCtx, cacheSyncCtxCancel := context.WithTimeout(ctx, clusterAccessorConfig.Cache.InitialSyncTimeout)
278+
cacheSyncCtx, cacheSyncCtxCancel := context.WithTimeoutCause(ctx, clusterAccessorConfig.Cache.InitialSyncTimeout, errors.New("initial sync timeout expired"))
279279
defer cacheSyncCtxCancel()
280280
if !cache.WaitForCacheSync(cacheSyncCtx) {
281281
cache.Stop()
@@ -311,13 +311,13 @@ type clientWithTimeout struct {
311311
var _ client.Client = &clientWithTimeout{}
312312

313313
func (c clientWithTimeout) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
314-
ctx, cancel := context.WithTimeout(ctx, c.timeout)
314+
ctx, cancel := context.WithTimeoutCause(ctx, c.timeout, errors.New("call timeout expired"))
315315
defer cancel()
316316
return c.Client.Get(ctx, key, obj, opts...)
317317
}
318318

319319
func (c clientWithTimeout) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {
320-
ctx, cancel := context.WithTimeout(ctx, c.timeout)
320+
ctx, cancel := context.WithTimeoutCause(ctx, c.timeout, errors.New("call timeout expired"))
321321
defer cancel()
322322
return c.Client.List(ctx, list, opts...)
323323
}
@@ -328,7 +328,7 @@ type stoppableCache struct {
328328

329329
lock sync.Mutex
330330
stopped bool
331-
cancelFunc context.CancelFunc
331+
cancelFunc context.CancelCauseFunc
332332
}
333333

334334
// Stop cancels the cache.Cache's context, unless it has already been stopped.
@@ -341,5 +341,5 @@ func (cc *stoppableCache) Stop() {
341341
}
342342

343343
cc.stopped = true
344-
cc.cancelFunc()
344+
cc.cancelFunc(errors.New("stoppable cache context cancelled"))
345345
}

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
@@ -185,7 +185,7 @@ func newEtcdClient(ctx context.Context, etcdClient etcd, callTimeout time.Durati
185185
return nil, errors.New("etcd client was not configured with any endpoints")
186186
}
187187

188-
ctx, cancel := context.WithTimeout(ctx, callTimeout)
188+
ctx, cancel := context.WithTimeoutCause(ctx, callTimeout, errors.New("call timeout expired"))
189189
defer cancel()
190190

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

210210
// Members retrieves a list of etcd members.
211211
func (c *Client) Members(ctx context.Context) ([]*Member, error) {
212-
ctx, cancel := context.WithTimeout(ctx, c.CallTimeout)
212+
ctx, cancel := context.WithTimeoutCause(ctx, c.CallTimeout, errors.New("call timeout expired"))
213213
defer cancel()
214214

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

241241
// MoveLeader moves the leader to the provided member ID.
242242
func (c *Client) MoveLeader(ctx context.Context, newLeaderID 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.MoveLeader(ctx, newLeaderID)
@@ -249,7 +249,7 @@ func (c *Client) MoveLeader(ctx context.Context, newLeaderID uint64) error {
249249

250250
// RemoveMember removes a given member.
251251
func (c *Client) RemoveMember(ctx context.Context, id uint64) 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
_, err := c.EtcdClient.MemberRemove(ctx, id)
@@ -258,7 +258,7 @@ func (c *Client) RemoveMember(ctx context.Context, id uint64) error {
258258

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

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

277277
// Alarms retrieves all alarms on a cluster.
278278
func (c *Client) Alarms(ctx context.Context) ([]MemberAlarm, error) {
279-
ctx, cancel := context.WithTimeout(ctx, c.CallTimeout)
279+
ctx, cancel := context.WithTimeoutCause(ctx, c.CallTimeout, errors.New("call timeout expired"))
280280
defer cancel()
281281

282282
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
@@ -315,7 +315,7 @@ func (d *Helper) EvictPods(ctx context.Context, podDeleteList *PodDeleteList) Ev
315315

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

321321
res := EvictionResult{

0 commit comments

Comments
 (0)