@@ -20,7 +20,6 @@ import (
2020 "context"
2121 "errors"
2222 "fmt"
23- "sync"
2423 "time"
2524
2625 "go.uber.org/zap"
@@ -35,16 +34,22 @@ import (
3534 "k8s.io/apimachinery/pkg/labels"
3635 "sigs.k8s.io/controller-runtime/pkg/builder"
3736 ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
37+ "sigs.k8s.io/controller-runtime/pkg/event"
3838 "sigs.k8s.io/controller-runtime/pkg/handler"
3939 "sigs.k8s.io/controller-runtime/pkg/manager"
4040 "sigs.k8s.io/controller-runtime/pkg/reconcile"
41+ "sigs.k8s.io/controller-runtime/pkg/source"
42+ mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager"
4143)
4244
4345const (
4446 ControllerName = "syncagent-syncmanager"
4547
4648 // numSyncWorkers is the number of concurrent workers within each sync controller.
4749 numSyncWorkers = 4
50+
51+ syncControllerMinRetryDelay = 5 * time .Second
52+ syncControllerMaxRetryDelay = 5 * time .Minute
4853)
4954
5055type ClusterProviderFunc func () []string
@@ -66,11 +71,12 @@ type Reconciler struct {
6671 agentName string
6772 enableServerSideApply bool
6873
69- syncCancelsLock sync. RWMutex
74+ controllerEvents chan event. TypedGenericEvent [ * syncagentv1alpha1. PublishedResource ]
7075 // A map of sync controllers, one for each PublishedResource, using their
7176 // UIDs and resourceVersion as the map keys; using the version ensures that
7277 // when a PR changes, the old controller is orphaned and will be shut down.
73- syncCancels map [string ]context.CancelCauseFunc
78+ // Only accessed by the reconcile worker, so no lock is needed.
79+ syncControllers map [string ]* syncController
7480}
7581
7682// Add creates a new controller and adds it to the given manager.
@@ -101,8 +107,8 @@ func Add(
101107 agentName : agentName ,
102108 resourceProber : resourceProber ,
103109 enableServerSideApply : enableServerSideApply ,
104- syncCancelsLock : sync. RWMutex {} ,
105- syncCancels : map [string ]context. CancelCauseFunc {},
110+ controllerEvents : make ( chan event. TypedGenericEvent [ * syncagentv1alpha1. PublishedResource ]) ,
111+ syncControllers : map [string ]* syncController {},
106112 }
107113
108114 bldr := builder .
@@ -114,6 +120,9 @@ func Add(
114120 builder .WithPredicates (predicate .ByLabels (prFilter )),
115121 )
116122
123+ bldr .WatchesRawSource (source .Channel (reconciler .controllerEvents ,
124+ & handler.TypedEnqueueRequestForObject [* syncagentv1alpha1.PublishedResource ]{},
125+ ))
117126 _ , err = bldr .Build (reconciler )
118127
119128 return err
@@ -148,11 +157,26 @@ func (r *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (reco
148157func (r * Reconciler ) ensureSyncController (ctx context.Context , log * zap.SugaredLogger , pubRes * syncagentv1alpha1.PublishedResource ) (reconcile.Result , error ) {
149158 key := getPublishedResourceKey (pubRes )
150159
151- // controller already exists
152- if _ , exists := r .syncCancels [key ]; exists {
160+ if r .ctx .Err () != nil {
153161 return reconcile.Result {}, nil
154162 }
155163
164+ retryDelay := syncControllerMinRetryDelay
165+
166+ // Stopped controllers are only removed here, so a late exit can't remove a replacement.
167+ if controller , exists := r .syncControllers [key ]; exists {
168+ select {
169+ case <- controller .done :
170+ if delay := time .Until (controller .finishedAt .Add (controller .retryDelay )); delay > 0 {
171+ return reconcile.Result {RequeueAfter : delay }, nil
172+ }
173+ retryDelay = nextRetryDelay (controller )
174+ delete (r .syncControllers , key )
175+ default :
176+ return reconcile.Result {}, nil
177+ }
178+ }
179+
156180 prlog := log .With ("prkey" , key , "name" , pubRes .Name )
157181
158182 // Multicluster-runtime *hates* it when you create a controller that watches
@@ -178,7 +202,7 @@ func (r *Reconciler) ensureSyncController(ctx context.Context, log *zap.SugaredL
178202
179203 // create the sync controller;
180204 // use the reconciler's log without any additional reconciling context
181- syncController , err := controllersync .Create (
205+ runnable , err := controllersync .Create (
182206 // This can be the reconciling context, as it's only used to find the target CRD during setup;
183207 // this context *must not* be stored in the sync controller!
184208 ctx ,
@@ -197,13 +221,26 @@ func (r *Reconciler) ensureSyncController(ctx context.Context, log *zap.SugaredL
197221 return reconcile.Result {}, fmt .Errorf ("failed to create sync controller: %w" , err )
198222 }
199223
200- r .syncCancels [key ] = ctrlCancel
224+ controller := & syncController {
225+ Runnable : runnable ,
226+ cancel : ctrlCancel ,
227+ done : make (chan struct {}),
228+ retryDelay : retryDelay ,
229+ notify : func () {
230+ select {
231+ case r .controllerEvents <- event.TypedGenericEvent [* syncagentv1alpha1.PublishedResource ]{Object : pubRes .DeepCopy ()}:
232+ case <- ctrlCtx .Done ():
233+ }
234+ },
235+ }
236+ r .syncControllers [key ] = controller
201237
202238 // time to start the controller; this will spawn a new goroutine if
203239 // successful; the new controller will be pre-seeded with all knonwn
204240 // (engaged) clusters by the DMCM.
205- if err = r .dmcm .StartController (ctrlCtx , log .With ("prkey" , key ), syncController ); err != nil {
241+ if err = r .dmcm .StartController (ctrlCtx , log .With ("prkey" , key ), controller ); err != nil {
206242 ctrlCancel (errors .New ("failed to start sync controller" ))
243+ delete (r .syncControllers , key )
207244 return reconcile.Result {}, fmt .Errorf ("failed to start sync controller: %w" , err )
208245 }
209246
@@ -214,13 +251,10 @@ func (r *Reconciler) cleanupController(log *zap.SugaredLogger, pubRes *syncagent
214251 key := getPublishedResourceKey (pubRes )
215252 log .Infow ("Stopping sync controller…" , "prkey" , key )
216253
217- r .syncCancelsLock .Lock ()
218- defer r .syncCancelsLock .Unlock ()
219-
220- cancel , ok := r .syncCancels [key ]
254+ controller , ok := r .syncControllers [key ]
221255 if ok {
222- cancel (errors .New ("controller is no longer needed" ))
223- delete (r .syncCancels , key )
256+ controller . cancel (errors .New ("controller is no longer needed" ))
257+ delete (r .syncControllers , key )
224258 }
225259
226260 return nil
@@ -244,3 +278,35 @@ func getPublishedResourceKey(pr *syncagentv1alpha1.PublishedResource) string {
244278func isSyncEnabled (pr * syncagentv1alpha1.PublishedResource ) bool {
245279 return pr .Spec .Synchronization == nil || pr .Spec .Synchronization .Enabled
246280}
281+
282+ // syncController requests a reconcile when the wrapped controller exits unexpectedly.
283+ type syncController struct {
284+ mcmanager.Runnable
285+ cancel context.CancelCauseFunc
286+ done chan struct {}
287+ notify func ()
288+ retryDelay time.Duration
289+ startedAt time.Time
290+ finishedAt time.Time
291+ }
292+
293+ func (c * syncController ) Start (ctx context.Context ) error {
294+ c .startedAt = time .Now ()
295+ err := c .Runnable .Start (ctx )
296+ c .finishedAt = time .Now ()
297+ close (c .done )
298+ defer c .cancel (errors .New ("sync controller stopped" ))
299+ if ctx .Err () == nil {
300+ c .notify ()
301+ }
302+ return err
303+ }
304+
305+ // nextRetryDelay doubles the delay for controllers that keep failing and resets
306+ // it once a controller has been running for longer than the maximum delay.
307+ func nextRetryDelay (c * syncController ) time.Duration {
308+ if c .finishedAt .Sub (c .startedAt ) >= syncControllerMaxRetryDelay {
309+ return syncControllerMinRetryDelay
310+ }
311+ return min (c .retryDelay * 2 , syncControllerMaxRetryDelay )
312+ }
0 commit comments