use of org.apache.camel.util.StopWatch in project camel by apache.
the class DefaultShutdownStrategy method doShutdown.
protected boolean doShutdown(CamelContext context, List<RouteStartupOrder> routes, long timeout, TimeUnit timeUnit, boolean suspendOnly, boolean abortAfterTimeout, boolean forceShutdown) throws Exception {
// timeout must be a positive value
if (timeout <= 0) {
throw new IllegalArgumentException("Timeout must be a positive value");
}
// just return if no routes to shutdown
if (routes.isEmpty()) {
return true;
}
StopWatch watch = new StopWatch();
// at first sort according to route startup order
List<RouteStartupOrder> routesOrdered = new ArrayList<RouteStartupOrder>(routes);
routesOrdered.sort(new Comparator<RouteStartupOrder>() {
public int compare(RouteStartupOrder o1, RouteStartupOrder o2) {
return o1.getStartupOrder() - o2.getStartupOrder();
}
});
if (shutdownRoutesInReverseOrder) {
Collections.reverse(routesOrdered);
}
if (suspendOnly) {
LOG.info("Starting to graceful suspend " + routesOrdered.size() + " routes (timeout " + timeout + " " + timeUnit.toString().toLowerCase(Locale.ENGLISH) + ")");
} else {
LOG.info("Starting to graceful shutdown " + routesOrdered.size() + " routes (timeout " + timeout + " " + timeUnit.toString().toLowerCase(Locale.ENGLISH) + ")");
}
// use another thread to perform the shutdowns so we can support timeout
timeoutOccurred.set(false);
currentShutdownTaskFuture = getExecutorService().submit(new ShutdownTask(context, routesOrdered, timeout, timeUnit, suspendOnly, abortAfterTimeout, timeoutOccurred));
try {
currentShutdownTaskFuture.get(timeout, timeUnit);
} catch (ExecutionException e) {
// unwrap execution exception
throw ObjectHelper.wrapRuntimeCamelException(e.getCause());
} catch (Exception e) {
// either timeout or interrupted exception was thrown so this is okay
// as interrupted would mean cancel was called on the currentShutdownTaskFuture to signal a forced timeout
// we hit a timeout, so set the flag
timeoutOccurred.set(true);
// timeout then cancel the task
currentShutdownTaskFuture.cancel(true);
// signal we are forcing shutdown now, since timeout occurred
this.forceShutdown = forceShutdown;
// if set, stop processing and return false to indicate that the shutdown is aborting
if (!forceShutdown && abortAfterTimeout) {
LOG.warn("Timeout occurred during graceful shutdown. Aborting the shutdown now." + " Notice: some resources may still be running as graceful shutdown did not complete successfully.");
// we attempt to force shutdown so lets log the current inflight exchanges which are affected
logInflightExchanges(context, routes, isLogInflightExchangesOnTimeout());
return false;
} else {
if (forceShutdown || shutdownNowOnTimeout) {
LOG.warn("Timeout occurred during graceful shutdown. Forcing the routes to be shutdown now." + " Notice: some resources may still be running as graceful shutdown did not complete successfully.");
// we attempt to force shutdown so lets log the current inflight exchanges which are affected
logInflightExchanges(context, routes, isLogInflightExchangesOnTimeout());
// force the routes to shutdown now
shutdownRoutesNow(routesOrdered);
// now the route consumers has been shutdown, then prepare route services for shutdown now (forced)
for (RouteStartupOrder order : routes) {
for (Service service : order.getServices()) {
prepareShutdown(service, false, true, true, isSuppressLoggingOnTimeout());
}
}
} else {
LOG.warn("Timeout occurred during graceful shutdown. Will ignore shutting down the remainder routes." + " Notice: some resources may still be running as graceful shutdown did not complete successfully.");
logInflightExchanges(context, routes, isLogInflightExchangesOnTimeout());
}
}
} finally {
currentShutdownTaskFuture = null;
}
// convert to seconds as its easier to read than a big milli seconds number
long seconds = TimeUnit.SECONDS.convert(watch.stop(), TimeUnit.MILLISECONDS);
LOG.info("Graceful shutdown of " + routesOrdered.size() + " routes completed in " + seconds + " seconds");
return true;
}
use of org.apache.camel.util.StopWatch in project camel by apache.
the class DefaultExecutorServiceManager method doShutdown.
private boolean doShutdown(ExecutorService executorService, long shutdownAwaitTermination, boolean failSafe) {
if (executorService == null) {
return false;
}
boolean warned = false;
// we ought to shutdown much faster)
if (!executorService.isShutdown()) {
StopWatch watch = new StopWatch();
LOG.trace("Shutdown of ExecutorService: {} with await termination: {} millis", executorService, shutdownAwaitTermination);
executorService.shutdown();
if (shutdownAwaitTermination > 0) {
try {
if (!awaitTermination(executorService, shutdownAwaitTermination)) {
warned = true;
LOG.warn("Forcing shutdown of ExecutorService: {} due first await termination elapsed.", executorService);
executorService.shutdownNow();
// we are now shutting down aggressively, so wait to see if we can completely shutdown or not
if (!awaitTermination(executorService, shutdownAwaitTermination)) {
LOG.warn("Cannot completely force shutdown of ExecutorService: {} due second await termination elapsed.", executorService);
}
}
} catch (InterruptedException e) {
warned = true;
LOG.warn("Forcing shutdown of ExecutorService: {} due interrupted.", executorService);
// we were interrupted during shutdown, so force shutdown
executorService.shutdownNow();
}
}
// if we logged at WARN level, then report at INFO level when we are complete so the end user can see this in the log
if (warned) {
LOG.info("Shutdown of ExecutorService: {} is shutdown: {} and terminated: {} took: {}.", executorService, executorService.isShutdown(), executorService.isTerminated(), TimeUtils.printDuration(watch.taken()));
} else if (LOG.isDebugEnabled()) {
LOG.debug("Shutdown of ExecutorService: {} is shutdown: {} and terminated: {} took: {}.", executorService, executorService.isShutdown(), executorService.isTerminated(), TimeUtils.printDuration(watch.taken()));
}
}
// let lifecycle strategy be notified as well which can let it be managed in JMX as well
ThreadPoolExecutor threadPool = null;
if (executorService instanceof ThreadPoolExecutor) {
threadPool = (ThreadPoolExecutor) executorService;
} else if (executorService instanceof SizedScheduledExecutorService) {
threadPool = ((SizedScheduledExecutorService) executorService).getScheduledThreadPoolExecutor();
}
if (threadPool != null) {
for (LifecycleStrategy lifecycle : camelContext.getLifecycleStrategies()) {
lifecycle.onThreadPoolRemove(camelContext, threadPool);
}
}
// remove reference as its shutdown (do not remove if fail-safe)
if (!failSafe) {
executorServices.remove(executorService);
}
return warned;
}
use of org.apache.camel.util.StopWatch in project camel by apache.
the class DefaultExecutorServiceManager method awaitTermination.
@Override
public boolean awaitTermination(ExecutorService executorService, long shutdownAwaitTermination) throws InterruptedException {
// log progress every 2nd second so end user is aware of we are shutting down
StopWatch watch = new StopWatch();
long interval = Math.min(2000, shutdownAwaitTermination);
boolean done = false;
while (!done && interval > 0) {
if (executorService.awaitTermination(interval, TimeUnit.MILLISECONDS)) {
done = true;
} else {
LOG.info("Waited {} for ExecutorService: {} to terminate...", TimeUtils.printDuration(watch.taken()), executorService);
// recalculate interval
interval = Math.min(2000, shutdownAwaitTermination - watch.taken());
}
}
return done;
}
use of org.apache.camel.util.StopWatch in project camel by apache.
the class DirectVmProducerBlockingTest method testProducerBlocksWithNoConsumers.
public void testProducerBlocksWithNoConsumers() throws Exception {
DirectVmEndpoint endpoint = getMandatoryEndpoint("direct-vm:suspended", DirectVmEndpoint.class);
endpoint.getConsumer().suspend();
StopWatch watch = new StopWatch();
try {
template.sendBody("direct-vm:start?block=true&timeout=2000", "hello world");
fail("Expected CamelExecutionException");
} catch (CamelExecutionException e) {
DirectVmConsumerNotAvailableException cause = assertIsInstanceOf(DirectVmConsumerNotAvailableException.class, e.getCause());
assertIsInstanceOf(CamelExchangeException.class, cause);
assertTrue(watch.taken() > 1500);
}
}
use of org.apache.camel.util.StopWatch in project camel by apache.
the class VmInOutChainedTimeoutTest method testVmInOutChainedTimeout.
public void testVmInOutChainedTimeout() throws Exception {
StopWatch watch = new StopWatch();
try {
template2.requestBody("vm:a?timeout=1000", "Hello World");
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
// the chained vm caused the timeout
ExchangeTimedOutException cause = assertIsInstanceOf(ExchangeTimedOutException.class, e.getCause());
assertEquals(200, cause.getTimeout());
}
long delta = watch.stop();
assertTrue("Should be faster than 1 sec, was: " + delta, delta < 1100);
}
Aggregations