Search in sources :

Example 6 with FaultToleranceService

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;
}
Also used : FallbackPolicy(fish.payara.microprofile.faulttolerance.interceptors.fallback.FallbackPolicy) Config(org.eclipse.microprofile.config.Config) InvocationManager(org.glassfish.api.invocation.InvocationManager) Fallback(org.eclipse.microprofile.faulttolerance.Fallback) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) NoSuchElementException(java.util.NoSuchElementException) AroundInvoke(javax.interceptor.AroundInvoke)

Example 7 with FaultToleranceService

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);
}
Also used : FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) ManagedScheduledExecutorService(javax.enterprise.concurrent.ManagedScheduledExecutorService)

Example 8 with FaultToleranceService

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;
}
Also used : FallbackPolicy(fish.payara.microprofile.faulttolerance.interceptors.fallback.FallbackPolicy) Config(org.eclipse.microprofile.config.Config) InvocationManager(org.glassfish.api.invocation.InvocationManager) Fallback(org.eclipse.microprofile.faulttolerance.Fallback) Retry(org.eclipse.microprofile.faulttolerance.Retry) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) BulkheadException(org.eclipse.microprofile.faulttolerance.exceptions.BulkheadException) AroundInvoke(javax.interceptor.AroundInvoke)

Example 9 with FaultToleranceService

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;
}
Also used : CircuitBreaker(org.eclipse.microprofile.faulttolerance.CircuitBreaker) Config(org.eclipse.microprofile.config.Config) CircuitBreakerState(fish.payara.microprofile.faulttolerance.state.CircuitBreakerState) ArrayList(java.util.ArrayList) InvocationManager(org.glassfish.api.invocation.InvocationManager) CircuitBreakerOpenException(org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) NamingException(javax.naming.NamingException) NoSuchElementException(java.util.NoSuchElementException) CircuitBreakerOpenException(org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException) Retry(org.eclipse.microprofile.faulttolerance.Retry) NoSuchElementException(java.util.NoSuchElementException) ChronoUnit(java.time.temporal.ChronoUnit)

Example 10 with FaultToleranceService

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;
}
Also used : FallbackPolicy(fish.payara.microprofile.faulttolerance.interceptors.fallback.FallbackPolicy) Config(org.eclipse.microprofile.config.Config) InvocationManager(org.glassfish.api.invocation.InvocationManager) Fallback(org.eclipse.microprofile.faulttolerance.Fallback) Retry(org.eclipse.microprofile.faulttolerance.Retry) FaultToleranceService(fish.payara.microprofile.faulttolerance.FaultToleranceService) NamingException(javax.naming.NamingException) TimeoutException(org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException) AroundInvoke(javax.interceptor.AroundInvoke)

Aggregations

FaultToleranceService (fish.payara.microprofile.faulttolerance.FaultToleranceService)11 InvocationManager (org.glassfish.api.invocation.InvocationManager)9 Config (org.eclipse.microprofile.config.Config)8 FallbackPolicy (fish.payara.microprofile.faulttolerance.interceptors.fallback.FallbackPolicy)5 AroundInvoke (javax.interceptor.AroundInvoke)5 Fallback (org.eclipse.microprofile.faulttolerance.Fallback)5 Retry (org.eclipse.microprofile.faulttolerance.Retry)5 NoSuchElementException (java.util.NoSuchElementException)4 RequestTraceSpan (fish.payara.notification.requesttracing.RequestTraceSpan)3 NamingException (javax.naming.NamingException)3 ChronoUnit (java.time.temporal.ChronoUnit)2 ArrayList (java.util.ArrayList)2 ManagedScheduledExecutorService (javax.enterprise.concurrent.ManagedScheduledExecutorService)2 BulkheadException (org.eclipse.microprofile.faulttolerance.exceptions.BulkheadException)2 CircuitBreakerOpenException (org.eclipse.microprofile.faulttolerance.exceptions.CircuitBreakerOpenException)2 CircuitBreakerState (fish.payara.microprofile.faulttolerance.state.CircuitBreakerState)1 List (java.util.List)1 Callable (java.util.concurrent.Callable)1 ExecutionException (java.util.concurrent.ExecutionException)1 Semaphore (java.util.concurrent.Semaphore)1