use of fish.payara.microprofile.faulttolerance.FaultToleranceService in project Payara by payara.
the class RetryInterceptor method intercept.
@AroundInvoke
public Object intercept(InvocationContext invocationContext) throws Exception {
Object proceededInvocationContext = null;
FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
Config config = null;
try {
config = ConfigProvider.getConfig();
} catch (IllegalArgumentException ex) {
logger.log(Level.INFO, "No config could be found", ex);
}
try {
if (faultToleranceService.isFaultToleranceEnabled(faultToleranceService.getApplicationName(invocationManager, invocationContext), config)) {
logger.log(Level.FINER, "Proceeding invocation with retry semantics");
proceededInvocationContext = retry(invocationContext);
} else {
// If fault tolerance isn't enabled, just proceed as normal
logger.log(Level.FINE, "Fault Tolerance not enabled for {0}, proceeding normally without retry.", faultToleranceService.getApplicationName(invocationManager, invocationContext));
proceededInvocationContext = invocationContext.proceed();
}
} catch (Exception ex) {
Fallback fallback = FaultToleranceCdiUtils.getAnnotation(beanManager, Fallback.class, invocationContext);
if (fallback != null) {
logger.log(Level.FINE, "Fallback annotation found on method - falling back from Retry");
FallbackPolicy fallbackPolicy = new FallbackPolicy(fallback, config, invocationContext);
proceededInvocationContext = fallbackPolicy.fallback(invocationContext);
} else {
throw ex;
}
}
return proceededInvocationContext;
}
use of fish.payara.microprofile.faulttolerance.FaultToleranceService in project Payara by payara.
the class TimeoutInterceptor method startTimeout.
/**
* Helper method that schedules a thread interrupt after a period of time.
* @param timeoutMillis The time in milliseconds to wait before interrupting.
* @param timedOut A threadlocal that stores whether or not the interrupt has occurred.
* @return A future that can be cancelled if the method execution completes before the interrupt happens
* @throws NamingException If the configured ManagedScheduledExecutorService could not be found
*/
private Future startTimeout(long timeoutMillis, ThreadLocal<Boolean> timedOut) throws NamingException {
final Thread thread = Thread.currentThread();
Runnable timeoutTask = () -> {
thread.interrupt();
timedOut.set(true);
};
FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
ManagedScheduledExecutorService managedScheduledExecutorService = faultToleranceService.getManagedScheduledExecutorService();
return managedScheduledExecutorService.schedule(timeoutTask, timeoutMillis, TimeUnit.MILLISECONDS);
}
use of fish.payara.microprofile.faulttolerance.FaultToleranceService in project Payara by payara.
the class BulkheadInterceptor method intercept.
@AroundInvoke
public Object intercept(InvocationContext invocationContext) throws Exception {
Object proceededInvocationContext = null;
FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
Config config = null;
try {
config = ConfigProvider.getConfig();
} catch (IllegalArgumentException ex) {
logger.log(Level.INFO, "No config could be found", ex);
}
try {
String appName = faultToleranceService.getApplicationName(invocationManager, invocationContext);
// Attempt to proceed the InvocationContext with Bulkhead semantics if Fault Tolerance is enabled
if (faultToleranceService.isFaultToleranceEnabled(appName, config)) {
logger.log(Level.FINER, "Proceeding invocation with bulkhead semantics");
proceededInvocationContext = bulkhead(invocationContext);
} else {
// If fault tolerance isn't enabled, just proceed as normal
logger.log(Level.FINE, "Fault Tolerance not enabled for {0}, proceeding normally without bulkhead.", faultToleranceService.getApplicationName(invocationManager, invocationContext));
proceededInvocationContext = invocationContext.proceed();
}
} catch (Exception ex) {
Retry retry = FaultToleranceCdiUtils.getAnnotation(beanManager, Retry.class, invocationContext);
if (retry != null) {
logger.log(Level.FINE, "Retry annotation found on method, propagating error upwards.");
throw ex;
} else {
// If an exception was thrown, check if the method is annotated with @Fallback
Fallback fallback = FaultToleranceCdiUtils.getAnnotation(beanManager, Fallback.class, invocationContext);
// If the method was annotated with Fallback, attempt it, otherwise just propagate the exception upwards
if (fallback != null) {
logger.log(Level.FINE, "Fallback annotation found on method, and no Retry annotation - " + "falling back from Bulkhead");
FallbackPolicy fallbackPolicy = new FallbackPolicy(fallback, config, invocationContext);
proceededInvocationContext = fallbackPolicy.fallback(invocationContext);
} else {
logger.log(Level.FINE, "Fallback annotation not found on method, propagating error upwards.", ex);
throw ex;
}
}
}
return proceededInvocationContext;
}
use of fish.payara.microprofile.faulttolerance.FaultToleranceService in project Payara by payara.
the class CircuitBreakerInterceptor method circuitBreak.
private Object circuitBreak(InvocationContext invocationContext) throws Exception {
Object proceededInvocationContext = null;
FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
CircuitBreaker circuitBreaker = FaultToleranceCdiUtils.getAnnotation(beanManager, CircuitBreaker.class, invocationContext);
Config config = null;
try {
config = ConfigProvider.getConfig();
} catch (IllegalArgumentException ex) {
logger.log(Level.INFO, "No config could be found", ex);
}
Class<? extends Throwable>[] failOn = circuitBreaker.failOn();
try {
String failOnString = ((String) FaultToleranceCdiUtils.getOverrideValue(config, Retry.class, "failOn", invocationContext, String.class).get());
List<Class> classList = new ArrayList<>();
// Remove any curly or square brackets from the string, as well as any spaces and ".class"es and loop
for (String className : failOnString.replaceAll("[\\{\\[ \\]\\}]", "").replaceAll("\\.class", "").split(",")) {
// Get a class object
classList.add(Class.forName(className));
}
failOn = classList.toArray(failOn);
} catch (NoSuchElementException nsee) {
logger.log(Level.FINER, "Could not find element in config", nsee);
} catch (ClassNotFoundException cnfe) {
logger.log(Level.INFO, "Could not find class from failOn config, defaulting to annotation. " + "Make sure you give the full canonical class name.", cnfe);
}
long delay = (Long) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "value", invocationContext, Long.class).orElse(circuitBreaker.delay());
ChronoUnit delayUnit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "delayUnit", invocationContext, ChronoUnit.class).orElse(circuitBreaker.delayUnit());
int requestVolumeThreshold = (Integer) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "requestVolumeThreshold", invocationContext, Integer.class).orElse(circuitBreaker.requestVolumeThreshold());
double failureRatio = (Double) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "failureRatio", invocationContext, Double.class).orElse(circuitBreaker.failureRatio());
int successThreshold = (Integer) FaultToleranceCdiUtils.getOverrideValue(config, CircuitBreaker.class, "successThreshold", invocationContext, Integer.class).orElse(circuitBreaker.successThreshold());
long delayMillis = Duration.of(delay, delayUnit).toMillis();
InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
CircuitBreakerState circuitBreakerState = faultToleranceService.getCircuitBreakerState(faultToleranceService.getApplicationName(invocationManager, invocationContext), invocationContext.getMethod(), circuitBreaker);
switch(circuitBreakerState.getCircuitState()) {
case OPEN:
logger.log(Level.FINER, "CircuitBreaker is Open, throwing exception");
// If open, immediately throw an error
throw new CircuitBreakerOpenException("CircuitBreaker for method " + invocationContext.getMethod().getName() + "is in state OPEN.");
case CLOSED:
// If closed, attempt to proceed the invocation context
try {
logger.log(Level.FINER, "Proceeding CircuitBreaker context");
proceededInvocationContext = invocationContext.proceed();
} catch (Exception ex) {
logger.log(Level.FINE, "Exception executing CircuitBreaker context");
// Check if the exception is something that should record a failure
if (shouldFail(failOn, ex)) {
logger.log(Level.FINE, "Caught exception is included in CircuitBreaker failOn, " + "recording failure against CircuitBreaker");
// Add a failure result to the queue
circuitBreakerState.recordClosedResult(Boolean.FALSE);
// Calculate the failure threshold
long failureThreshold = Math.round(requestVolumeThreshold * failureRatio);
// If we're over the failure threshold, open the circuit
if (circuitBreakerState.isOverFailureThreshold(failureThreshold)) {
logger.log(Level.FINE, "CircuitBreaker is over failure threshold {0}, opening circuit", failureThreshold);
circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.OPEN);
// Kick off a thread that will half-open the circuit after the specified delay
scheduleHalfOpen(delayMillis, circuitBreakerState);
}
}
// Finally, propagate the error upwards
throw ex;
}
// If everything is bon, just add a success value
circuitBreakerState.recordClosedResult(Boolean.TRUE);
break;
case HALF_OPEN:
// If half-open, attempt to proceed the invocation context
try {
logger.log(Level.FINER, "Proceeding half open CircuitBreaker context");
proceededInvocationContext = invocationContext.proceed();
} catch (Exception ex) {
logger.log(Level.FINE, "Exception executing CircuitBreaker context");
// Check if the exception is something that should record a failure
if (shouldFail(failOn, ex)) {
logger.log(Level.FINE, "Caught exception is included in CircuitBreaker failOn, " + "reopening half open circuit");
// Open the circuit again, and reset the half-open result counter
circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.OPEN);
circuitBreakerState.resetHalfOpenSuccessfulResultCounter();
scheduleHalfOpen(delayMillis, circuitBreakerState);
}
throw ex;
}
// If the invocation context hasn't thrown an error, record a success
circuitBreakerState.incrementHalfOpenSuccessfulResultCounter();
logger.log(Level.FINER, "Number of consecutive successful circuitbreaker executions = {0}", circuitBreakerState.getHalfOpenSuccessFulResultCounter());
// If we've hit the success threshold, close the circuit
if (circuitBreakerState.getHalfOpenSuccessFulResultCounter() == successThreshold) {
logger.log(Level.FINE, "Number of consecutive successful CircuitBreaker executions is above " + "threshold {0}, closing circuit", successThreshold);
circuitBreakerState.setCircuitState(CircuitBreakerState.CircuitState.CLOSED);
// Reset the counter for when we next need to use it
circuitBreakerState.resetHalfOpenSuccessfulResultCounter();
// Reset the rolling results window
circuitBreakerState.resetResults();
}
break;
}
return proceededInvocationContext;
}
use of fish.payara.microprofile.faulttolerance.FaultToleranceService in project Payara by payara.
the class TimeoutInterceptor method intercept.
@AroundInvoke
public Object intercept(InvocationContext invocationContext) throws Exception {
Object proceededInvocationContext = null;
FaultToleranceService faultToleranceService = Globals.getDefaultBaseServiceLocator().getService(FaultToleranceService.class);
InvocationManager invocationManager = Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class);
Config config = null;
try {
config = ConfigProvider.getConfig();
} catch (IllegalArgumentException ex) {
logger.log(Level.INFO, "No config could be found", ex);
}
try {
if (faultToleranceService.isFaultToleranceEnabled(faultToleranceService.getApplicationName(invocationManager, invocationContext), config)) {
logger.log(Level.FINER, "Proceeding invocation with timeout semantics");
proceededInvocationContext = timeout(invocationContext);
} else {
// If fault tolerance isn't enabled, just proceed as normal
logger.log(Level.FINE, "Fault Tolerance not enabled for {0}, proceeding normally without timeout.", faultToleranceService.getApplicationName(invocationManager, invocationContext));
proceededInvocationContext = invocationContext.proceed();
}
} catch (Exception ex) {
Retry retry = FaultToleranceCdiUtils.getAnnotation(beanManager, Retry.class, invocationContext);
if (retry != null) {
logger.log(Level.FINE, "Retry annotation found on method, propagating error upwards.");
throw ex;
} else {
Fallback fallback = FaultToleranceCdiUtils.getAnnotation(beanManager, Fallback.class, invocationContext);
if (fallback != null) {
logger.log(Level.FINE, "Fallback annotation found on method, and no Retry annotation - " + "falling back from Timeout");
FallbackPolicy fallbackPolicy = new FallbackPolicy(fallback, config, invocationContext);
proceededInvocationContext = fallbackPolicy.fallback(invocationContext);
} else {
throw ex;
}
}
}
return proceededInvocationContext;
}
Aggregations