|
| 1 | +package io.javaoperatorsdk.operator.processing.expectation; |
| 2 | + |
| 3 | +import java.time.Duration; |
| 4 | +import java.time.LocalDateTime; |
| 5 | +import java.util.Optional; |
| 6 | +import java.util.concurrent.ConcurrentHashMap; |
| 7 | + |
| 8 | +import io.fabric8.kubernetes.api.model.HasMetadata; |
| 9 | +import io.javaoperatorsdk.operator.api.reconciler.Context; |
| 10 | +import io.javaoperatorsdk.operator.processing.event.ResourceID; |
| 11 | + |
| 12 | +public class ExpectationManager<P extends HasMetadata> { |
| 13 | + |
| 14 | + private final ConcurrentHashMap<ResourceID, RegisteredExpectation<P>> registeredExpectations = |
| 15 | + new ConcurrentHashMap<>(); |
| 16 | + |
| 17 | + public void setExpectation(P primary, Expectation<P> expectation, Duration timeout) { |
| 18 | + registeredExpectations.put( |
| 19 | + ResourceID.fromResource(primary), |
| 20 | + new RegisteredExpectation<>(LocalDateTime.now(), timeout, expectation)); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Checks if provided expectation is fulfilled. Return the expectation result. If the result of |
| 25 | + * expectation is fulfilled or timeout, the expectation is automatically removed; |
| 26 | + */ |
| 27 | + public Optional<ExpectationResult<P>> checkOnExpectation(P primary, Context<P> context) { |
| 28 | + var resourceID = ResourceID.fromResource(primary); |
| 29 | + var regExp = registeredExpectations.get(ResourceID.fromResource(primary)); |
| 30 | + if (regExp == null) { |
| 31 | + return Optional.empty(); |
| 32 | + } |
| 33 | + if (regExp.expectation().isFulfilled(primary, context)) { |
| 34 | + registeredExpectations.remove(resourceID); |
| 35 | + return Optional.of( |
| 36 | + new ExpectationResult<>(regExp.expectation(), ExpectationStatus.FULFILLED)); |
| 37 | + } else if (regExp.isTimedOut()) { |
| 38 | + registeredExpectations.remove(resourceID); |
| 39 | + return Optional.of( |
| 40 | + new ExpectationResult<>(regExp.expectation(), ExpectationStatus.TIMED_OUT)); |
| 41 | + } else { |
| 42 | + return Optional.of( |
| 43 | + new ExpectationResult<>(regExp.expectation(), ExpectationStatus.NOT_FULFILLED)); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + public boolean isExpectationPresent(P primary) { |
| 48 | + return registeredExpectations.containsKey(ResourceID.fromResource(primary)); |
| 49 | + } |
| 50 | + |
| 51 | + public Optional<Expectation<P>> getExpectation(P primary) { |
| 52 | + var regExp = registeredExpectations.get(ResourceID.fromResource(primary)); |
| 53 | + return Optional.ofNullable(regExp).map(RegisteredExpectation::expectation); |
| 54 | + } |
| 55 | + |
| 56 | + public void cleanup(P primary) { |
| 57 | + registeredExpectations.remove(ResourceID.fromResource(primary)); |
| 58 | + } |
| 59 | +} |
0 commit comments