Skip to content

Commit d15f4ed

Browse files
authored
fix: log and recover from failures in PerResourcePollingEventSource polling (#3700)
Exceptions thrown by the resource fetcher are logged and the next poll is scheduled, errors are logged and rethrown. A registered task that ended without scheduling the next one is discarded and polling rescheduled when the primary resource is registered again. A fetch ignoring the interruption of the deletion could reschedule after the resource was recreated, leaving two polling chains for it. Signed-off-by: Attila Mészáros <a_meszaros@apple.com>
1 parent a5df0fa commit d15f4ed

2 files changed

Lines changed: 163 additions & 18 deletions

File tree

‎operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java‎

Lines changed: 80 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@
2020
import java.util.Map;
2121
import java.util.Optional;
2222
import java.util.Set;
23+
import java.util.concurrent.CancellationException;
2324
import java.util.concurrent.ConcurrentHashMap;
25+
import java.util.concurrent.ExecutionException;
2426
import java.util.concurrent.ScheduledExecutorService;
2527
import java.util.concurrent.ScheduledFuture;
2628
import 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) {

‎operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.util.concurrent.Executors;
2525
import java.util.concurrent.ScheduledExecutorService;
2626
import java.util.concurrent.TimeUnit;
27+
import java.util.function.Supplier;
2728
import java.util.stream.Stream;
2829

2930
import org.junit.jupiter.api.BeforeEach;
@@ -273,6 +274,39 @@ void supportsDynamicPollingDelay() {
273274
.untilAsserted(() -> verify(supplier, times(2)).fetchResources(any()));
274275
}
275276

277+
@Test
278+
void keepsPollingAfterTheFetcherThrowsAnException() {
279+
when(supplier.fetchResources(any()))
280+
.thenThrow(new IllegalStateException("temporary failure"))
281+
.thenReturn(Set.of(SampleExternalResource.testResource1()));
282+
283+
source.onResourceCreated(testCustomResource);
284+
285+
await()
286+
.untilAsserted(
287+
() -> {
288+
verify(supplier, atLeast(3)).fetchResources(eq(testCustomResource));
289+
verify(eventHandler, atLeastOnce()).handleEvent(any());
290+
});
291+
}
292+
293+
@Test
294+
void pollingFailedWithAnErrorIsRegisteredAgainWhenTheResourceIsUpdated() {
295+
when(supplier.fetchResources(any()))
296+
.thenThrow(new OutOfMemoryError("test"))
297+
.thenReturn(Set.of(SampleExternalResource.testResource1()));
298+
299+
source.onResourceCreated(testCustomResource);
300+
await().untilAsserted(() -> verify(supplier, times(1)).fetchResources(any()));
301+
await()
302+
.pollDelay(Duration.ofMillis(2 * PERIOD))
303+
.untilAsserted(() -> verify(supplier, times(1)).fetchResources(any()));
304+
305+
source.onResourceUpdated(testCustomResource, testCustomResource);
306+
307+
await().untilAsserted(() -> verify(supplier, atLeast(3)).fetchResources(any()));
308+
}
309+
276310
@Test
277311
void pollsAgainAfterRestart() {
278312
source.onResourceCreated(testCustomResource);
@@ -286,6 +320,55 @@ void pollsAgainAfterRestart() {
286320
await().untilAsserted(() -> verify(supplier, atLeast(2)).fetchResources(any()));
287321
}
288322

323+
@Test
324+
void aFailingFetchOutlivingTheDeletionDoesNotStartASecondPollingChain() throws Exception {
325+
verifyFetchOutlivingDeletionDoesNotStartASecondPollingChain(
326+
() -> {
327+
throw new IllegalStateException("failure after the deletion");
328+
});
329+
}
330+
331+
@Test
332+
void aFetchOutlivingTheDeletionDoesNotStartASecondPollingChain() throws Exception {
333+
verifyFetchOutlivingDeletionDoesNotStartASecondPollingChain(
334+
() -> Set.of(SampleExternalResource.testResource1()));
335+
}
336+
337+
private void verifyFetchOutlivingDeletionDoesNotStartASecondPollingChain(
338+
Supplier<Set<SampleExternalResource>> result) throws Exception {
339+
var fetching = new CountDownLatch(1);
340+
var release = new CountDownLatch(1);
341+
when(supplier.fetchResources(any()))
342+
.thenAnswer(
343+
invocation -> {
344+
fetching.countDown();
345+
var interrupted = false;
346+
while (release.getCount() > 0) {
347+
try {
348+
release.await();
349+
} catch (InterruptedException e) {
350+
interrupted = true;
351+
}
352+
}
353+
if (interrupted) {
354+
Thread.currentThread().interrupt();
355+
}
356+
return result.get();
357+
})
358+
.thenReturn(Set.of(SampleExternalResource.testResource1()));
359+
360+
source.onResourceCreated(testCustomResource);
361+
assertThat(fetching.await(5, TimeUnit.SECONDS)).isTrue();
362+
source.onResourceDeleted(testCustomResource);
363+
source.onResourceCreated(testCustomResource);
364+
clearInvocations(supplier);
365+
release.countDown();
366+
367+
await()
368+
.pollDelay(Duration.ofMillis(10 * PERIOD))
369+
.untilAsserted(() -> verify(supplier, atMost(15)).fetchResources(any()));
370+
}
371+
289372
@Test
290373
void aFetchOutlivingARestartDoesNotStartASecondPollingChain() throws Exception {
291374
var fetching = new CountDownLatch(1);

0 commit comments

Comments
 (0)