@@ -17,7 +17,9 @@ type ExternalWatchers struct {
17
17
}
18
18
19
19
var (
20
- ObserveInterval = 20 * time .Second
20
+ ObserveInterval = 20 * time .Second
21
+ WaitForReady = 5 * time .Second
22
+ MaxRetriesForReady = 5
21
23
)
22
24
23
25
type Resource interface {
@@ -30,6 +32,7 @@ type CheckDeltaFunc func(obj Resource) (bool, error)
30
32
type HandleAutoStartFunc func (ctx context.Context , obj Resource ) (ctrl.Result , error )
31
33
type HandleReconcileFunc func (ctx context.Context , obj Resource ) (ctrl.Result , error )
32
34
type DeleteWatcherFunc func (name string )
35
+ type IsResourceReadyFunc func (obj Resource ) (bool , error )
33
36
34
37
func NewExternalWatchers () * ExternalWatchers {
35
38
return & ExternalWatchers {
@@ -64,12 +67,24 @@ func (e *ExternalWatchers) HandleWatcher(ctx context.Context, req ctrl.Request,
64
67
func StartWatcher (ctx context.Context , resource Resource ,
65
68
stopChan chan struct {}, fetchResource FetchResourceFunc , updateStatus UpdateStatusFunc ,
66
69
checkDelta CheckDeltaFunc , handleAutoStart HandleAutoStartFunc , handleReconcile HandleReconcileFunc ,
67
- deleteWatcher DeleteWatcherFunc ) (ctrl.Result , error ) {
68
- ticker := time .NewTicker (ObserveInterval )
69
- defer ticker .Stop ()
70
+ deleteWatcher DeleteWatcherFunc , isResourceReady IsResourceReadyFunc ) (ctrl.Result , error ) {
70
71
logger := log .FromContext (ctx )
71
72
resourceName := resource .GetName ()
72
73
74
+ ready , err := waitForResourceReady (ctx , resource , isResourceReady )
75
+ if err != nil {
76
+ logger .Error (err , "Error waiting for resource to be ready" )
77
+ return ctrl.Result {}, err
78
+ }
79
+ if ! ready {
80
+ logger .Info (fmt .Sprintf ("Resource %s is not ready to watch" , resourceName ))
81
+ deleteWatcher (resourceName )
82
+ return ctrl.Result {Requeue : true , RequeueAfter : 3 * time .Second }, nil
83
+ }
84
+
85
+ ticker := time .NewTicker (ObserveInterval )
86
+ defer ticker .Stop ()
87
+
73
88
for {
74
89
select {
75
90
case <- ticker .C :
@@ -117,6 +132,24 @@ func StartWatcher(ctx context.Context, resource Resource,
117
132
}
118
133
}
119
134
135
+ func waitForResourceReady (ctx context.Context , resource Resource , isResourceReady IsResourceReadyFunc ) (bool , error ) {
136
+ logger := log .FromContext (ctx )
137
+ for retry := 0 ; retry < MaxRetriesForReady ; retry ++ {
138
+ ready , err := isResourceReady (resource )
139
+ if err != nil {
140
+ logger .Error (err , "Error checking if the resource is ready" )
141
+ return false , err
142
+ }
143
+ if ready {
144
+ return true , nil
145
+ }
146
+ if retry < MaxRetriesForReady - 1 {
147
+ time .Sleep (WaitForReady )
148
+ }
149
+ }
150
+ return false , nil
151
+ }
152
+
120
153
func (e * ExternalWatchers ) DeleteWatcher (name string ) {
121
154
e .mu .Lock ()
122
155
defer e .mu .Unlock ()
0 commit comments