Skip to content

Commit 57edf50

Browse files
committed
add NewCancelRunnable
Signed-off-by: Tim Ramlot <[email protected]>
1 parent 5a56e55 commit 57edf50

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

pkg/manager/manager.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"net"
2424
"net/http"
2525
"reflect"
26+
"sync"
2627
"time"
2728

2829
"github.com/go-logr/logr"
@@ -341,6 +342,34 @@ type LeaderElectionRunnable interface {
341342
NeedLeaderElection() bool
342343
}
343344

345+
// NewCancelRunnable returns a new Runnable and a function to cancel that runnable.
346+
func NewCancelRunnable(r Runnable) (Runnable, context.CancelFunc) {
347+
mu := sync.Mutex{}
348+
var cancels []func()
349+
canceled := false
350+
351+
return RunnableFunc(func(ctx context.Context) error {
352+
mu.Lock()
353+
var cancel context.CancelFunc
354+
ctx, cancel = context.WithCancel(ctx)
355+
if canceled {
356+
cancel()
357+
} else {
358+
cancels = append(cancels, cancel)
359+
}
360+
mu.Unlock()
361+
362+
return r.Start(ctx)
363+
}), func() {
364+
mu.Lock()
365+
defer mu.Unlock()
366+
canceled = true
367+
for _, cancel := range cancels {
368+
cancel()
369+
}
370+
}
371+
}
372+
344373
// New returns a new Manager for creating Controllers.
345374
func New(config *rest.Config, options Options) (Manager, error) {
346375
// Set default values for options fields

0 commit comments

Comments
 (0)