Search in sources :

Example 6 with RouteStartupOrder

use of org.apache.camel.spi.RouteStartupOrder in project camel by apache.

the class RouteStartupOrderWithDefaultTest method testRouteStartupOrder.

public void testRouteStartupOrder() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    template.sendBody("direct:start", "Hello World");
    assertMockEndpointsSatisfied();
    // assert correct order
    DefaultCamelContext dcc = (DefaultCamelContext) context;
    List<RouteStartupOrder> order = dcc.getRouteStartupOrder();
    assertEquals(5, order.size());
    assertEquals("seda://foo", order.get(0).getRoute().getEndpoint().getEndpointUri());
    assertEquals("direct://start", order.get(1).getRoute().getEndpoint().getEndpointUri());
    assertEquals("seda://bar", order.get(2).getRoute().getEndpoint().getEndpointUri());
    assertEquals("direct://bar", order.get(3).getRoute().getEndpoint().getEndpointUri());
    // the one with no startup order should be last
    assertEquals("direct://default", order.get(4).getRoute().getEndpoint().getEndpointUri());
}
Also used : MockEndpoint(org.apache.camel.component.mock.MockEndpoint) RouteStartupOrder(org.apache.camel.spi.RouteStartupOrder) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext)

Example 7 with RouteStartupOrder

use of org.apache.camel.spi.RouteStartupOrder in project camel by apache.

the class DefaultCamelContext method doStop.

protected synchronized void doStop() throws Exception {
    stopWatch.restart();
    log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is shutting down");
    EventHelper.notifyCamelContextStopping(this);
    // stop route inputs in the same order as they was started so we stop the very first inputs first
    try {
        // force shutting down routes as they may otherwise cause shutdown to hang
        shutdownStrategy.shutdownForced(this, getRouteStartupOrder());
    } catch (Throwable e) {
        log.warn("Error occurred while shutting down routes. This exception will be ignored.", e);
    }
    // shutdown await manager to trigger interrupt of blocked threads to attempt to free these threads graceful
    shutdownServices(asyncProcessorAwaitManager);
    shutdownServices(getRouteStartupOrder().stream().sorted(Comparator.comparing(RouteStartupOrder::getStartupOrder).reversed()).map(DefaultRouteStartupOrder.class::cast).map(DefaultRouteStartupOrder::getRouteService).collect(Collectors.toList()), false);
    // do not clear route services or startup listeners as we can start Camel again and get the route back as before
    getRouteStartupOrder().clear();
    // but clear any suspend routes
    suspendedRouteServices.clear();
    // which we need to stop after the routes, as a POJO consumer is essentially a route also
    for (Service service : servicesToStop) {
        if (service instanceof Consumer) {
            shutdownServices(service);
        }
    }
    // shutdown default error handler thread pool
    if (errorHandlerExecutorService != null) {
        // force shutting down the thread pool
        getExecutorServiceManager().shutdownNow(errorHandlerExecutorService);
        errorHandlerExecutorService = null;
    }
    // shutdown debugger
    ServiceHelper.stopAndShutdownService(getDebugger());
    shutdownServices(endpoints.values());
    endpoints.clear();
    shutdownServices(components.values());
    components.clear();
    shutdownServices(languages.values());
    languages.clear();
    try {
        for (LifecycleStrategy strategy : lifecycleStrategies) {
            strategy.onContextStop(this);
        }
    } catch (Throwable e) {
        log.warn("Error occurred while stopping lifecycle strategies. This exception will be ignored.", e);
    }
    // shutdown services as late as possible
    shutdownServices(servicesToStop);
    servicesToStop.clear();
    // must notify that we are stopped before stopping the management strategy
    EventHelper.notifyCamelContextStopped(this);
    // stop the notifier service
    for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
        shutdownServices(notifier);
    }
    // shutdown executor service and management as the last one
    shutdownServices(executorServiceManager);
    shutdownServices(managementStrategy);
    shutdownServices(managementMBeanAssembler);
    shutdownServices(lifecycleStrategies);
    // do not clear lifecycleStrategies as we can start Camel again and get the route back as before
    // stop the lazy created so they can be re-created on restart
    forceStopLazyInitialization();
    // stop to clear introspection cache
    IntrospectionSupport.stop();
    stopWatch.stop();
    if (log.isInfoEnabled()) {
        log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") uptime {}", getUptime());
        log.info("Apache Camel " + getVersion() + " (CamelContext: " + getName() + ") is shutdown in " + TimeUtils.printDuration(stopWatch.taken()));
    }
    // and clear start date
    startDate = null;
    // [TODO] Remove in 3.0
    Container.Instance.unmanage(this);
}
Also used : PollingConsumer(org.apache.camel.PollingConsumer) Consumer(org.apache.camel.Consumer) LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) EventNotifier(org.apache.camel.spi.EventNotifier) Service(org.apache.camel.Service) StatefulService(org.apache.camel.StatefulService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SuspendableService(org.apache.camel.SuspendableService) RouteStartupOrder(org.apache.camel.spi.RouteStartupOrder)

Example 8 with RouteStartupOrder

use of org.apache.camel.spi.RouteStartupOrder in project camel by apache.

the class DefaultCamelContext method stopRoute.

public synchronized boolean stopRoute(String routeId, long timeout, TimeUnit timeUnit, boolean abortAfterTimeout) throws Exception {
    RouteService routeService = routeServices.get(routeId);
    if (routeService != null) {
        RouteStartupOrder route = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
        boolean completed = getShutdownStrategy().shutdown(this, route, timeout, timeUnit, abortAfterTimeout);
        if (completed) {
            // must stop route service as well
            stopRouteService(routeService, false);
        } else {
            // shutdown was aborted, make sure route is re-started properly
            startRouteService(routeService, false);
        }
        return completed;
    }
    return false;
}
Also used : RouteStartupOrder(org.apache.camel.spi.RouteStartupOrder)

Example 9 with RouteStartupOrder

use of org.apache.camel.spi.RouteStartupOrder in project camel by apache.

the class DefaultCamelContext method removeRoute.

public synchronized boolean removeRoute(String routeId) throws Exception {
    // remove the route from ErrorHandlerBuilder if possible
    if (getErrorHandlerBuilder() instanceof ErrorHandlerBuilderSupport) {
        ErrorHandlerBuilderSupport builder = (ErrorHandlerBuilderSupport) getErrorHandlerBuilder();
        builder.removeOnExceptionList(routeId);
    }
    // gather a map of all the endpoints in use by the routes, so we can known if a given endpoints is in use
    // by one or more routes, when we remove the route
    Map<String, Set<Endpoint>> endpointsInUse = new HashMap<String, Set<Endpoint>>();
    for (Map.Entry<String, RouteService> entry : routeServices.entrySet()) {
        endpointsInUse.put(entry.getKey(), entry.getValue().gatherEndpoints());
    }
    RouteService routeService = routeServices.get(routeId);
    if (routeService != null) {
        if (getRouteStatus(routeId).isStopped()) {
            routeService.setRemovingRoutes(true);
            shutdownRouteService(routeService);
            removeRouteDefinition(routeId);
            routeServices.remove(routeId);
            // remove route from startup order as well, as it was removed
            Iterator<RouteStartupOrder> it = routeStartupOrder.iterator();
            while (it.hasNext()) {
                RouteStartupOrder order = it.next();
                if (order.getRoute().getId().equals(routeId)) {
                    it.remove();
                }
            }
            // from the route which we have removed, then remove all its private endpoints
            // (eg the endpoints which are not in use by other routes)
            Set<Endpoint> toRemove = new LinkedHashSet<Endpoint>();
            for (Endpoint endpoint : endpointsInUse.get(routeId)) {
                // how many times is the endpoint in use
                int count = 0;
                for (Set<Endpoint> endpoints : endpointsInUse.values()) {
                    if (endpoints.contains(endpoint)) {
                        count++;
                    }
                }
                // notice we will count ourselves so if there is only 1 then its safe to remove
                if (count <= 1) {
                    toRemove.add(endpoint);
                }
            }
            for (Endpoint endpoint : toRemove) {
                log.debug("Removing: {} which was only in use by route: {}", endpoint, routeId);
                removeEndpoint(endpoint);
            }
            return true;
        } else {
            return false;
        }
    }
    return false;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ErrorHandlerBuilderSupport(org.apache.camel.builder.ErrorHandlerBuilderSupport) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) RouteStartupOrder(org.apache.camel.spi.RouteStartupOrder) Endpoint(org.apache.camel.Endpoint) Endpoint(org.apache.camel.Endpoint) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 10 with RouteStartupOrder

use of org.apache.camel.spi.RouteStartupOrder in project camel by apache.

the class DefaultShutdownStrategy method logInflightExchanges.

/**
     * Logs information about the inflight exchanges
     *
     * @param infoLevel <tt>true</tt> to log at INFO level, <tt>false</tt> to log at DEBUG level
     */
protected static void logInflightExchanges(CamelContext camelContext, List<RouteStartupOrder> routes, boolean infoLevel) {
    // check if we need to log
    if (!infoLevel && !LOG.isDebugEnabled()) {
        return;
    }
    Collection<InflightRepository.InflightExchange> inflights = camelContext.getInflightRepository().browse();
    int size = inflights.size();
    if (size == 0) {
        return;
    }
    // filter so inflight must start from any of the routes
    Set<String> routeIds = new HashSet<String>();
    for (RouteStartupOrder route : routes) {
        routeIds.add(route.getRoute().getId());
    }
    Collection<InflightRepository.InflightExchange> filtered = new ArrayList<InflightRepository.InflightExchange>();
    for (InflightRepository.InflightExchange inflight : inflights) {
        String routeId = inflight.getExchange().getFromRouteId();
        if (routeIds.contains(routeId)) {
            filtered.add(inflight);
        }
    }
    size = filtered.size();
    if (size == 0) {
        return;
    }
    StringBuilder sb = new StringBuilder("There are " + size + " inflight exchanges:");
    for (InflightRepository.InflightExchange inflight : filtered) {
        sb.append("\n\tInflightExchange: [exchangeId=").append(inflight.getExchange().getExchangeId()).append(", fromRouteId=").append(inflight.getExchange().getFromRouteId()).append(", routeId=").append(inflight.getRouteId()).append(", nodeId=").append(inflight.getNodeId()).append(", elapsed=").append(inflight.getElapsed()).append(", duration=").append(inflight.getDuration()).append("]");
    }
    if (infoLevel) {
        LOG.info(sb.toString());
    } else {
        LOG.debug(sb.toString());
    }
}
Also used : InflightRepository(org.apache.camel.spi.InflightRepository) ArrayList(java.util.ArrayList) RouteStartupOrder(org.apache.camel.spi.RouteStartupOrder) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

RouteStartupOrder (org.apache.camel.spi.RouteStartupOrder)26 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)12 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)11 ArrayList (java.util.ArrayList)10 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)8 Route (org.apache.camel.Route)4 ShutdownRoute (org.apache.camel.ShutdownRoute)4 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)3 TreeMap (java.util.TreeMap)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 Consumer (org.apache.camel.Consumer)3 SuspendableService (org.apache.camel.SuspendableService)3 LinkedHashSet (java.util.LinkedHashSet)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Endpoint (org.apache.camel.Endpoint)2 PollingConsumer (org.apache.camel.PollingConsumer)2 Service (org.apache.camel.Service)2 LifecycleStrategy (org.apache.camel.spi.LifecycleStrategy)2