Skip to content

Commit

Permalink
add NewCancelRunnable
Browse files Browse the repository at this point in the history
Signed-off-by: Tim Ramlot <42113979+inteon@users.noreply.github.com>
  • Loading branch information
inteon committed Feb 4, 2023
1 parent 5a56e55 commit 57edf50
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions pkg/manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"net"
"net/http"
"reflect"
"sync"
"time"

"github.com/go-logr/logr"
Expand Down Expand Up @@ -341,6 +342,34 @@ type LeaderElectionRunnable interface {
NeedLeaderElection() bool
}

// NewCancelRunnable returns a new Runnable and a function to cancel that runnable.
func NewCancelRunnable(r Runnable) (Runnable, context.CancelFunc) {
mu := sync.Mutex{}
var cancels []func()
canceled := false

return RunnableFunc(func(ctx context.Context) error {
mu.Lock()
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
if canceled {
cancel()
} else {
cancels = append(cancels, cancel)
}
mu.Unlock()

return r.Start(ctx)
}), func() {
mu.Lock()
defer mu.Unlock()
canceled = true
for _, cancel := range cancels {
cancel()
}
}
}

// New returns a new Manager for creating Controllers.
func New(config *rest.Config, options Options) (Manager, error) {
// Set default values for options fields
Expand Down

0 comments on commit 57edf50

Please sign in to comment.