2020import java .util .Map ;
2121import java .util .Optional ;
2222import java .util .Set ;
23+ import java .util .concurrent .CancellationException ;
2324import java .util .concurrent .ConcurrentHashMap ;
25+ import java .util .concurrent .ExecutionException ;
2426import java .util .concurrent .ScheduledExecutorService ;
2527import java .util .concurrent .ScheduledFuture ;
2628import java .util .concurrent .TimeUnit ;
@@ -52,7 +54,7 @@ public class PerResourcePollingEventSource<R, P extends HasMetadata, ID>
5254
5355 private static final Logger log = LoggerFactory .getLogger (PerResourcePollingEventSource .class );
5456
55- private final Map <ResourceID , ScheduledFuture < Void > > scheduledFutures = new ConcurrentHashMap <>();
57+ private final Map <ResourceID , ScheduledPoll > scheduledFutures = new ConcurrentHashMap <>();
5658 private final Cache <P > primaryResourceCache ;
5759 private final Set <ResourceID > fetchedForPrimaries = ConcurrentHashMap .newKeySet ();
5860
@@ -120,26 +122,34 @@ private void cacheResources(P primary, Set<R> values, boolean fromGetter) {
120122
121123 // the polling of a resource that is gone ends with its last task, which would otherwise stay
122124 // registered and keep the resource from being polled again if it is recreated
123- private synchronized void forgetTask (ResourceID primaryID , long generation ) {
124- if (generation == lifecycleGeneration ) {
125+ private synchronized void forgetTask (ResourceID primaryID , long generation , Object chain ) {
126+ if (generation == lifecycleGeneration && isCurrentChain ( primaryID , chain ) ) {
125127 scheduledFutures .remove (primaryID );
126128 }
127129 }
128130
131+ // a chain is replaced or dropped when its resource is deleted, a fetch of the replaced chain
132+ // outliving that is not to continue it, or it would run next to the one of a recreated resource
133+ private boolean isCurrentChain (ResourceID primaryID , Object chain ) {
134+ var current = scheduledFutures .get (primaryID );
135+ return current != null && current .chain () == chain ;
136+ }
137+
129138 // a fetch ignoring the interruption of a stop can return after a restart, its result is not to
130139 // overwrite what the polls of the new run cached in the meantime
131140 private synchronized void cacheAndScheduleNextExecution (
132- P primary , Set <R > values , long generation ) {
133- if (generation != lifecycleGeneration ) {
141+ P primary , Set <R > values , long generation , Object chain ) {
142+ if (generation != lifecycleGeneration
143+ || !isCurrentChain (ResourceID .fromResource (primary ), chain )) {
134144 return ;
135145 }
136146 cacheResources (primary , values , false );
137- scheduleNextExecution (primary , values , generation );
147+ scheduleNextExecution (primary , values , generation , chain );
138148 }
139149
140150 @ SuppressWarnings ("unchecked" )
141151 private synchronized void scheduleNextExecution (
142- P primary , Set <R > actualResources , long generation ) {
152+ P primary , Set <R > actualResources , long generation , Object chain ) {
143153 if (generation != lifecycleGeneration ) {
144154 return ;
145155 }
@@ -150,10 +160,10 @@ private synchronized void scheduleNextExecution(
150160 ScheduledFuture <Void > scheduledFuture =
151161 (ScheduledFuture <Void >)
152162 executorService .schedule (
153- new FetchingExecutor (primaryID , generation ),
163+ new FetchingExecutor (primaryID , generation , chain ),
154164 fetchDuration .toMillis (),
155165 TimeUnit .MILLISECONDS );
156- scheduledFutures .put (primaryID , scheduledFuture );
166+ scheduledFutures .put (primaryID , new ScheduledPoll ( chain , scheduledFuture ) );
157167 }
158168
159169 @ Override
@@ -169,10 +179,10 @@ public void onResourceUpdated(P newResource, P oldResource) {
169179 @ Override
170180 public synchronized void onResourceDeleted (P resource ) {
171181 var resourceID = ResourceID .fromResource (resource );
172- var scheduledFuture = scheduledFutures .remove (resourceID );
173- if (scheduledFuture != null ) {
182+ var scheduledPoll = scheduledFutures .remove (resourceID );
183+ if (scheduledPoll != null ) {
174184 log .debug ("Canceling scheduledFuture for resource: {}" , resource );
175- scheduledFuture .cancel (true );
185+ scheduledPoll . future () .cancel (true );
176186 }
177187 handleDelete (resourceID );
178188 fetchedForPrimaries .remove (resourceID );
@@ -188,23 +198,68 @@ private synchronized void checkAndRegisterTask(P resource) {
188198 return ;
189199 }
190200 var primaryID = ResourceID .fromResource (resource );
201+ discardTaskIfFailed (primaryID );
191202 if (scheduledFutures .get (primaryID ) == null
192203 && (registerPredicate == null || registerPredicate .test (resource ))) {
193204 var cachedResources = cachedResourcesFor (primaryID );
194205 var actualResources = cachedResources .isEmpty () ? null : cachedResources ;
195206 // note that there is a delay, to not do two fetches when the resources first appeared
196207 // and getSecondaryResource is called on reconciliation.
197- scheduleNextExecution (resource , actualResources , lifecycleGeneration );
208+ scheduleNextExecution (resource , actualResources , lifecycleGeneration , new Object ());
209+ }
210+ }
211+
212+ // a task that ended without scheduling the next one, e.g. on an Error, would otherwise stay
213+ // registered and keep the resource from being polled again
214+ private void discardTaskIfFailed (ResourceID primaryID ) {
215+ var poll = scheduledFutures .get (primaryID );
216+ if (poll == null || !poll .future ().isDone ()) {
217+ return ;
198218 }
219+ var future = poll .future ();
220+ try {
221+ future .get ();
222+ } catch (ExecutionException e ) {
223+ log .error (
224+ "Previous polling task for resource {} failed unexpectedly, polling is rescheduled" ,
225+ primaryID ,
226+ e .getCause ());
227+ } catch (CancellationException e ) {
228+ log .debug ("Previous polling task for resource {} was cancelled" , primaryID );
229+ } catch (InterruptedException e ) {
230+ Thread .currentThread ().interrupt ();
231+ return ;
232+ }
233+ scheduledFutures .remove (primaryID , poll );
199234 }
200235
236+ private synchronized void rescheduleAfterFailure (
237+ ResourceID primaryID , long generation , Object chain , Exception failure ) {
238+ if (generation != lifecycleGeneration || !isCurrentChain (primaryID , chain )) {
239+ log .debug (
240+ "Polling of resource {} failed after it was stopped or its resource deleted" , primaryID );
241+ return ;
242+ }
243+ log .error ("Exception during polling for resource: {}" , primaryID , failure );
244+ // not scheduled for a resource that is gone, the polling of it was cancelled with its deletion
245+ primaryResourceCache
246+ .get (primaryID )
247+ .ifPresentOrElse (
248+ primary -> scheduleNextExecution (primary , null , generation , chain ),
249+ () -> forgetTask (primaryID , generation , chain ));
250+ }
251+
252+ private record ScheduledPoll (Object chain , ScheduledFuture <Void > future ) {}
253+
201254 private class FetchingExecutor implements Runnable {
202255 private final ResourceID primaryID ;
203256 private final long generation ;
257+ private final Object chain ;
204258
205- public FetchingExecutor (ResourceID primaryID , long generation ) {
259+ public FetchingExecutor (ResourceID primaryID , long generation , Object chain ) {
206260 this .primaryID = primaryID ;
207261 this .generation = generation ;
262+ this .chain = chain ;
208263 }
209264
210265 @ Override
@@ -218,10 +273,17 @@ public void run() {
218273 if (primary .isEmpty ()) {
219274 log .warn ("No resource in cache for resource ID: {}" , primaryID );
220275 // no new execution is scheduled in this case, an on delete event should be received shortly
221- forgetTask (primaryID , generation );
276+ forgetTask (primaryID , generation , chain );
222277 } else {
223- var values = resourceFetcher .fetchResources (primary .get ());
224- cacheAndScheduleNextExecution (primary .get (), values , generation );
278+ try {
279+ var values = resourceFetcher .fetchResources (primary .get ());
280+ cacheAndScheduleNextExecution (primary .get (), values , generation , chain );
281+ } catch (Exception e ) {
282+ rescheduleAfterFailure (primaryID , generation , chain , e );
283+ } catch (Error e ) {
284+ log .error ("Fatal error during polling for resource: {}" , primaryID , e );
285+ throw e ;
286+ }
225287 }
226288 }
227289 }
@@ -276,7 +338,7 @@ public void stop() throws OperatorException {
276338 // map cleared so that they are registered again on a restart
277339 synchronized (this ) {
278340 lifecycleGeneration ++;
279- scheduledFutures .values ().forEach (future -> future .cancel (true ));
341+ scheduledFutures .values ().forEach (poll -> poll . future () .cancel (true ));
280342 scheduledFutures .clear ();
281343 }
282344 if (ownsExecutorService && executorService != null ) {
0 commit comments