Merge pull request #122152 from pohly/client-go-event-context-fix

client-go events: support context.Background() as context

Kubernetes-commit: e51e3c74f720cd299e10a5e0c500a749bb36c251
This commit is contained in:
Kubernetes Publisher 2024-02-12 06:48:06 -08:00
commit 5fb8d886b5

View File

@ -198,16 +198,29 @@ func NewBroadcaster(opts ...BroadcasterOption) EventBroadcaster {
ctx := c.Context
if ctx == nil {
ctx = context.Background()
} else {
}
// The are two scenarios where it makes no sense to wait for context cancelation:
// - The context was nil.
// - The context was context.Background() to begin with.
//
// Both cases get checked here.
haveCtxCancelation := ctx.Done() == nil
eventBroadcaster.cancelationCtx, eventBroadcaster.cancel = context.WithCancel(ctx)
if haveCtxCancelation {
// Calling Shutdown is not required when a context was provided:
// when the context is canceled, this goroutine will shut down
// the broadcaster.
//
// If Shutdown is called first, then this goroutine will
// also stop.
go func() {
<-ctx.Done()
<-eventBroadcaster.cancelationCtx.Done()
eventBroadcaster.Broadcaster.Shutdown()
}()
}
eventBroadcaster.cancelationCtx, eventBroadcaster.cancel = context.WithCancel(ctx)
return eventBroadcaster
}