Search in sources :

Example 1 with ExecutionException

use of java.util.concurrent.ExecutionException in project camel by apache.

the class DisruptorTimeoutTest method testDisruptorTimeout.

@Test
public void testDisruptorTimeout() throws Exception {
    final MockEndpoint result = getMockEndpoint("mock:result");
    result.setExpectedMessageCount(0);
    final Future<String> out = template.asyncRequestBody("disruptor:foo?timeout=" + timeout, "World", String.class);
    try {
        out.get();
        fail("Should have thrown an exception");
    } catch (ExecutionException e) {
        assertIsInstanceOf(CamelExecutionException.class, e.getCause());
        assertIsInstanceOf(ExchangeTimedOutException.class, e.getCause().getCause());
        final DisruptorEndpoint de = (DisruptorEndpoint) context.getRoute("disruptor").getEndpoint();
        assertNotNull("Consumer endpoint cannot be null", de);
        //we can't remove the exchange from a Disruptor once it is published, but it should never reach the
        //mock:result endpoint because it should be filtered out by the DisruptorConsumer
        result.await(1, TimeUnit.SECONDS);
        assertMockEndpointsSatisfied();
    }
}
Also used : CamelExecutionException(org.apache.camel.CamelExecutionException) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) ExecutionException(java.util.concurrent.ExecutionException) CamelExecutionException(org.apache.camel.CamelExecutionException) ExchangeTimedOutException(org.apache.camel.ExchangeTimedOutException) Test(org.junit.Test)

Example 2 with ExecutionException

use of java.util.concurrent.ExecutionException 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;
}
Also used : ArrayList(java.util.ArrayList) ExecutorService(java.util.concurrent.ExecutorService) Service(org.apache.camel.Service) RouteStartupOrder(org.apache.camel.spi.RouteStartupOrder) ExecutionException(java.util.concurrent.ExecutionException) ExecutionException(java.util.concurrent.ExecutionException) StopWatch(org.apache.camel.util.StopWatch)

Example 3 with ExecutionException

use of java.util.concurrent.ExecutionException in project camel by apache.

the class EnricherAsyncUnhandledExceptionTest method testInOutWithRequestBody.

@Test
public void testInOutWithRequestBody() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:pickedUp");
    mock.expectedMessageCount(1);
    // this direct endpoint should receive an exception
    try {
        Future<Object> obj = template.asyncRequestBody("direct:in", "Hello World");
        // wait five seconds at most; else, let's assume something went wrong
        obj.get(5000, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        // if we receive an exception, the async routing engine is working correctly
        // before the Enricher was fixed for cases where routing was async and the AggregationStrategy 
        // threw an exception, the call to requestBody would stall indefinitely
        // unwrap the exception chain
        assertTrue(e instanceof ExecutionException);
        assertTrue(e.getCause() instanceof CamelExecutionException);
        assertTrue(e.getCause().getCause() instanceof CamelExchangeException);
        assertTrue(e.getCause().getCause().getCause() instanceof RuntimeException);
        assertTrue(e.getCause().getCause().getCause().getMessage().equals("Bang! Unhandled exception"));
        mock.assertIsSatisfied();
        return;
    }
    fail("Expected an RuntimeException");
}
Also used : CamelExecutionException(org.apache.camel.CamelExecutionException) CamelExchangeException(org.apache.camel.CamelExchangeException) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) CamelExecutionException(org.apache.camel.CamelExecutionException) ExecutionException(java.util.concurrent.ExecutionException) CamelExecutionException(org.apache.camel.CamelExecutionException) ExecutionException(java.util.concurrent.ExecutionException) CamelExchangeException(org.apache.camel.CamelExchangeException) Test(org.junit.Test)

Example 4 with ExecutionException

use of java.util.concurrent.ExecutionException in project flink by apache.

the class StackTraceSampleCoordinatorTest method testTriggerStackTraceSampleTimeout.

/** Tests that samples time out if they don't finish in time. */
@Test(timeout = 1000L)
public void testTriggerStackTraceSampleTimeout() throws Exception {
    int timeout = 100;
    coord = new StackTraceSampleCoordinator(system.dispatcher(), timeout);
    final ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
    try {
        ExecutionVertex[] vertices = new ExecutionVertex[] { mockExecutionVertexWithTimeout(new ExecutionAttemptID(), ExecutionState.RUNNING, scheduledExecutorService, timeout) };
        Future<StackTraceSample> sampleFuture = coord.triggerStackTraceSample(vertices, 1, Time.milliseconds(100L), 0);
        // Wait for the timeout
        Thread.sleep(timeout * 2);
        boolean success = false;
        for (int i = 0; i < 10; i++) {
            if (sampleFuture.isDone()) {
                success = true;
                break;
            }
            Thread.sleep(timeout);
        }
        assertTrue("Sample did not time out", success);
        try {
            sampleFuture.get();
            fail("Expected exception.");
        } catch (ExecutionException e) {
            assertTrue(e.getCause().getCause().getMessage().contains("Timeout"));
        }
        // Collect after the timeout (should be ignored)
        ExecutionAttemptID executionId = vertices[0].getCurrentExecutionAttempt().getAttemptId();
        coord.collectStackTraces(0, executionId, new ArrayList<StackTraceElement[]>());
    } finally {
        scheduledExecutorService.shutdownNow();
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutionAttemptID(org.apache.flink.runtime.executiongraph.ExecutionAttemptID) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) TriggerStackTraceSample(org.apache.flink.runtime.messages.StackTraceSampleMessages.TriggerStackTraceSample) ExecutionException(java.util.concurrent.ExecutionException) ExecutionVertex(org.apache.flink.runtime.executiongraph.ExecutionVertex) Test(org.junit.Test)

Example 5 with ExecutionException

use of java.util.concurrent.ExecutionException in project flink by apache.

the class SchedulerSlotSharingTest method scheduleSingleVertexType.

@Test
public void scheduleSingleVertexType() {
    try {
        JobVertexID jid1 = new JobVertexID();
        SlotSharingGroup sharingGroup = new SlotSharingGroup(jid1);
        Scheduler scheduler = new Scheduler(TestingUtils.directExecutionContext());
        Instance i1 = getRandomInstance(2);
        Instance i2 = getRandomInstance(2);
        scheduler.newInstanceAvailable(i1);
        scheduler.newInstanceAvailable(i2);
        // schedule 4 tasks from the first vertex group
        SimpleSlot s1 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 0, 8), sharingGroup), false).get();
        SimpleSlot s2 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 1, 8), sharingGroup), false).get();
        SimpleSlot s3 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 2, 8), sharingGroup), false).get();
        SimpleSlot s4 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 3, 8), sharingGroup), false).get();
        assertNotNull(s1);
        assertNotNull(s2);
        assertNotNull(s3);
        assertNotNull(s4);
        assertTrue(areAllDistinct(s1, s2, s3, s4));
        // we cannot schedule another task from the first vertex group
        try {
            scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 4, 8), sharingGroup), false).get();
            fail("Scheduler accepted too many tasks at the same time");
        } catch (ExecutionException e) {
            assertTrue(e.getCause() instanceof NoResourceAvailableException);
        } catch (Exception e) {
            fail("Wrong exception.");
        }
        // release something
        s3.releaseSlot();
        // allocate another slot from that group
        SimpleSlot s5 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 4, 8), sharingGroup), false).get();
        assertNotNull(s5);
        // release all old slots
        s1.releaseSlot();
        s2.releaseSlot();
        s4.releaseSlot();
        SimpleSlot s6 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 5, 8), sharingGroup), false).get();
        SimpleSlot s7 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 6, 8), sharingGroup), false).get();
        SimpleSlot s8 = scheduler.allocateSlot(new ScheduledUnit(getTestVertex(jid1, 7, 8), sharingGroup), false).get();
        assertNotNull(s6);
        assertNotNull(s7);
        assertNotNull(s8);
        // make sure we have two slots on the first instance, and two on the second
        int c = 0;
        c += (s5.getTaskManagerID().equals(i1.getTaskManagerID())) ? 1 : -1;
        c += (s6.getTaskManagerID().equals(i1.getTaskManagerID())) ? 1 : -1;
        c += (s7.getTaskManagerID().equals(i1.getTaskManagerID())) ? 1 : -1;
        c += (s8.getTaskManagerID().equals(i1.getTaskManagerID())) ? 1 : -1;
        assertEquals(0, c);
        // release all
        s5.releaseSlot();
        s6.releaseSlot();
        s7.releaseSlot();
        s8.releaseSlot();
        // test that everything is released
        assertEquals(4, scheduler.getNumberOfAvailableSlots());
        // check the scheduler's bookkeeping
        assertEquals(0, scheduler.getNumberOfLocalizedAssignments());
        assertEquals(0, scheduler.getNumberOfNonLocalizedAssignments());
        assertEquals(8, scheduler.getNumberOfUnconstrainedAssignments());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Instance(org.apache.flink.runtime.instance.Instance) SchedulerTestUtils.getRandomInstance(org.apache.flink.runtime.jobmanager.scheduler.SchedulerTestUtils.getRandomInstance) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) ExecutionException(java.util.concurrent.ExecutionException) SimpleSlot(org.apache.flink.runtime.instance.SimpleSlot) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

ExecutionException (java.util.concurrent.ExecutionException)1341 IOException (java.io.IOException)367 Test (org.junit.Test)335 TimeoutException (java.util.concurrent.TimeoutException)258 ArrayList (java.util.ArrayList)237 Future (java.util.concurrent.Future)218 ExecutorService (java.util.concurrent.ExecutorService)152 CountDownLatch (java.util.concurrent.CountDownLatch)103 List (java.util.List)98 CancellationException (java.util.concurrent.CancellationException)98 Callable (java.util.concurrent.Callable)97 Test (org.testng.annotations.Test)78 HashMap (java.util.HashMap)69 Map (java.util.Map)65 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)64 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)63 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)56 ParallelTest (com.hazelcast.test.annotation.ParallelTest)47 QuickTest (com.hazelcast.test.annotation.QuickTest)47 UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)46