Skip to content

Avoid concurrent writes to a map in dynamicWatch #194

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

Merged
Merged
Changes from all 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
11 changes: 6 additions & 5 deletions pkg/patterns/declarative/pkg/watch/dynamic.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package watch
import (
"context"
"fmt"
"sync"
"time"

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

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

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

dw.lastRV = make(map[types.NamespacedName]string)
dw.lastRV = sync.Map{}

go func() {
for {
Expand Down Expand Up @@ -140,14 +141,14 @@ func (dw *dynamicWatch) watchUntilClosed(client dynamic.ResourceInterface, trigg
switch clientEvent.Type {
case watch.Deleted:
// stop lastRV growing indefinitely
delete(dw.lastRV, key)
dw.lastRV.Delete(key)
// We always send the delete notification
case watch.Added, watch.Modified:
if previousRV, found := dw.lastRV[key]; found && previousRV == rv {
if previousRV, found := dw.lastRV.Load(key); found && previousRV == rv {
// Don't send spurious invalidations
continue
}
dw.lastRV[key] = rv
dw.lastRV.Store(key, rv)
}

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