Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: event handler listen to ctx.Done #38

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/piper/piper.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ func main() {
// Create context that listens for the interrupt signal from the OS.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
event_handler.Start(ctx, stop, cfg, globalClients)
event_handler.Start(ctx, cfg, globalClients)
server.Start(ctx, stop, cfg, globalClients)
}
25 changes: 17 additions & 8 deletions pkg/event_handler/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"log"
)

func Start(ctx context.Context, stop context.CancelFunc, cfg *conf.GlobalConfig, clients *clients.Clients) {
func Start(ctx context.Context, cfg *conf.GlobalConfig, clients *clients.Clients) {
labelSelector := &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{Key: "piper.quickube.com/notified",
Expand All @@ -27,14 +27,23 @@ func Start(ctx context.Context, stop context.CancelFunc, cfg *conf.GlobalConfig,
Notifier: notifier,
}
go func() {
for event := range watcher.ResultChan() {
err2 := handler.Handle(ctx, &event)
if err2 != nil {
log.Printf("[event handler] failed to Handle workflow event %s", err2) // ERROR
for {
select {
case <-ctx.Done():
log.Print("[event handler] context canceled, stopping watcher")
watcher.Stop()
return
case event, ok := <-watcher.ResultChan():
if !ok {
log.Print("[event handler] result channel closed")
watcher.Stop()
return
}
if err2 := handler.Handle(ctx, &event); err2 != nil {
log.Printf("[event handler] failed to Handle workflow event: %v", err2)
}
}
}
log.Print("[event handler] stopped work, closing watcher")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@GoshaDo can explain how the race condition could happen ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If stop() is called, it will cancel the context (ctx). If the context is already canceled before watcher.Stop() completes, there could be race conditions or unexpected behavior.

watcher.Stop()
stop()

}()
}
Loading