Skip to content

Commit 0c27c07

Browse files
committed
Wait for watch to start
Technically we don't know when the watch events will come in, but this does greatly help the determinism of reconcile operations, which is important for golden testing.
1 parent cbb12fa commit 0c27c07

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

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

Lines changed: 15 additions & 2 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"
@@ -100,16 +101,25 @@ func (dw *dynamicWatch) Add(trigger schema.GroupVersionKind, options metav1.List
100101
return fmt.Errorf("creating client for (%s): %v", trigger.String(), err)
101102
}
102103

104+
var watchStarted sync.WaitGroup
105+
106+
watchStarted.Add(1)
107+
103108
go func() {
109+
firstWatchStarted := &watchStarted
110+
104111
for {
105112
ctx := context.TODO()
106113

107-
dkw.watchUntilClosed(ctx, target)
114+
dkw.watchUntilClosed(ctx, target, firstWatchStarted)
115+
firstWatchStarted = nil // only notify once
108116

109117
time.Sleep(WatchDelay)
110118
}
111119
}()
112120

121+
watchStarted.Wait()
122+
113123
return nil
114124
}
115125

@@ -127,14 +137,17 @@ type clientObject struct {
127137
// from this Watch but it will ensure we always Reconcile when needed`.
128138
//
129139
// [1] https://github.com/kubernetes/kubernetes/issues/54878#issuecomment-357575276
130-
func (w *dynamicKindWatch) watchUntilClosed(ctx context.Context, eventTarget metav1.ObjectMeta) {
140+
func (w *dynamicKindWatch) watchUntilClosed(ctx context.Context, eventTarget metav1.ObjectMeta, watchStarted *sync.WaitGroup) {
131141
log := log.FromContext(ctx)
132142

133143
options := w.FilterOptions
134144
// Though we don't use the resource version, we allow bookmarks to help keep TCP connections healthy.
135145
options.AllowWatchBookmarks = true
136146

137147
events, err := w.resource.Watch(context.TODO(), options)
148+
if watchStarted != nil {
149+
watchStarted.Done()
150+
}
138151
if err != nil {
139152
log.WithValues("kind", w.GVK.String()).WithValues("namespace", w.FilterNamespace).WithValues("labels", options.LabelSelector).Error(err, "failed to add watch to dynamic client")
140153
return

0 commit comments

Comments
 (0)