Skip to content

Commit b6783ba

Browse files
authored
Merge pull request #194 from tomasaschan/thread-safe-dynamic-watch
Avoid concurrent writes to a map in dynamicWatch
2 parents 7dcbbb6 + 5c7da94 commit b6783ba

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

pkg/patterns/declarative/pkg/watch/dynamic.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package watch
1919
import (
2020
"context"
2121
"fmt"
22+
"sync"
2223
"time"
2324

2425
"k8s.io/apimachinery/pkg/api/meta"
@@ -56,7 +57,7 @@ type dynamicWatch struct {
5657

5758
// lastRV caches the last reported resource version.
5859
// This helps us avoid sending duplicate events (e.g. on a rewatch)
59-
lastRV map[types.NamespacedName]string
60+
lastRV sync.Map
6061
}
6162

6263
func (dw *dynamicWatch) newDynamicClient(gvk schema.GroupVersionKind, namespace string) (dynamic.ResourceInterface, error) {
@@ -79,7 +80,7 @@ func (dw *dynamicWatch) Add(trigger schema.GroupVersionKind, options metav1.List
7980
return fmt.Errorf("creating client for (%s): %v", trigger.String(), err)
8081
}
8182

82-
dw.lastRV = make(map[types.NamespacedName]string)
83+
dw.lastRV = sync.Map{}
8384

8485
go func() {
8586
for {
@@ -140,14 +141,14 @@ func (dw *dynamicWatch) watchUntilClosed(client dynamic.ResourceInterface, trigg
140141
switch clientEvent.Type {
141142
case watch.Deleted:
142143
// stop lastRV growing indefinitely
143-
delete(dw.lastRV, key)
144+
dw.lastRV.Delete(key)
144145
// We always send the delete notification
145146
case watch.Added, watch.Modified:
146-
if previousRV, found := dw.lastRV[key]; found && previousRV == rv {
147+
if previousRV, found := dw.lastRV.Load(key); found && previousRV == rv {
147148
// Don't send spurious invalidations
148149
continue
149150
}
150-
dw.lastRV[key] = rv
151+
dw.lastRV.Store(key, rv)
151152
}
152153

153154
log.WithValues("type", clientEvent.Type).WithValues("kind", trigger.String()).WithValues("name", key.Name, "namespace", key.Namespace).Info("broadcasting event")

0 commit comments

Comments
 (0)