Skip to content

Commit 125b765

Browse files
committed
incus/server/events: Fix issue with race condition
AddHandler is checking if the listener is not nil before starting it. However, when the last handler is removed, the listener could be set to nil asynchronously in a goroutine. If a new handler was added immediately after, there was a chance the listener would never be started again, leading to dropped events. This fix ensures that the listener is properly restarted in such cases. Signed-off-by: Piotr Resztak <[email protected]>
1 parent 6718079 commit 125b765

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

internal/server/events/internalListener.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type InternalListener struct {
1818
listenerCtx context.Context
1919
listenerCancel context.CancelFunc
2020
lock sync.Mutex
21+
wg sync.WaitGroup
2122
}
2223

2324
// NewInternalListener returns an InternalListener.
@@ -49,7 +50,9 @@ func (l *InternalListener) startListener() {
4950
l.listener = nil
5051
}(l.listenerCtx)
5152

53+
l.wg.Add(1)
5254
go func(ctx context.Context, handlers map[string]EventHandler) {
55+
defer l.wg.Done()
5356
for {
5457
select {
5558
case <-ctx.Done():
@@ -75,6 +78,7 @@ func (l *InternalListener) startListener() {
7578
func (l *InternalListener) stopListener() {
7679
if l.listenerCancel != nil {
7780
l.listenerCancel()
81+
l.wg.Wait()
7882
}
7983
}
8084

0 commit comments

Comments
 (0)