Search in sources :

Example 11 with Service

use of org.apache.camel.Service in project camel by apache.

the class RouteService method startChildService.

protected void startChildService(Route route, List<Service> services) throws Exception {
    for (Service service : services) {
        LOG.debug("Starting child service on route: {} -> {}", route.getId(), service);
        for (LifecycleStrategy strategy : camelContext.getLifecycleStrategies()) {
            strategy.onServiceAdd(camelContext, service, route);
        }
        ServiceHelper.startService(service);
        addChildService(service);
    }
}
Also used : LifecycleStrategy(org.apache.camel.spi.LifecycleStrategy) Service(org.apache.camel.Service)

Example 12 with Service

use of org.apache.camel.Service in project camel by apache.

the class EventDrivenConsumerRoute method addServices.

/**
     * Factory method to lazily create the complete list of services required for this route
     * such as adding the processor or consumer
     */
@Override
protected void addServices(List<Service> services) throws Exception {
    Endpoint endpoint = getEndpoint();
    consumer = endpoint.createConsumer(processor);
    if (consumer != null) {
        services.add(consumer);
        if (consumer instanceof RouteAware) {
            ((RouteAware) consumer).setRoute(this);
        }
    }
    Processor processor = getProcessor();
    if (processor instanceof Service) {
        services.add((Service) processor);
    }
}
Also used : Processor(org.apache.camel.Processor) Endpoint(org.apache.camel.Endpoint) RouteAware(org.apache.camel.RouteAware) SuspendableService(org.apache.camel.SuspendableService) Service(org.apache.camel.Service)

Example 13 with Service

use of org.apache.camel.Service in project camel by apache.

the class ServicePoolAwareLeakyTest method testForMemoryLeak.

public void testForMemoryLeak() throws Exception {
    registerLeakyComponent();
    final Map<String, AtomicLong> references = new HashMap<String, AtomicLong>();
    // track LeakySieveProducer lifecycle
    context.addLifecycleStrategy(new LifecycleStrategySupport() {

        @Override
        public void onServiceAdd(CamelContext context, Service service, Route route) {
            if (service instanceof LeakySieveProducer) {
                String key = ((LeakySieveProducer) service).getEndpoint().getEndpointKey();
                AtomicLong num = references.get(key);
                if (num == null) {
                    num = new AtomicLong();
                    references.put(key, num);
                }
                num.incrementAndGet();
            }
        }

        @Override
        public void onServiceRemove(CamelContext context, Service service, Route route) {
            if (service instanceof LeakySieveProducer) {
                String key = ((LeakySieveProducer) service).getEndpoint().getEndpointKey();
                AtomicLong num = references.get(key);
                if (num == null) {
                    num = new AtomicLong();
                    references.put(key, num);
                }
                num.decrementAndGet();
            }
        }
    });
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:sieve-transient").id("sieve-transient").to(LEAKY_SIEVE_TRANSIENT);
            from("direct:sieve-stable").id("sieve-stable").to(LEAKY_SIEVE_STABLE);
        }
    });
    context.start();
    for (int i = 0; i < 1000; i++) {
        ServiceSupport service = (ServiceSupport) context.getProducerServicePool();
        assertEquals(ServiceStatus.Started, service.getStatus());
        if (isFailFast()) {
            assertEquals(2, context.getProducerServicePool().size());
            assertEquals(1, references.get(LEAKY_SIEVE_TRANSIENT).get());
            assertEquals(1, references.get(LEAKY_SIEVE_STABLE).get());
        }
        context.stopRoute("sieve-transient");
        if (isFailFast()) {
            assertEquals("Expected no service references to remain", 0, references.get(LEAKY_SIEVE_TRANSIENT));
        }
        if (isFailFast()) {
            if (isVerifyProducerServicePoolRemainsStarted()) {
                assertEquals(ServiceStatus.Started, service.getStatus());
            }
            assertEquals("Expected one stable producer to remain pooled", 1, context.getProducerServicePool().size());
            assertEquals("Expected one stable producer to remain as service", 1, references.get(LEAKY_SIEVE_STABLE).get());
        }
        // Send a body to verify behaviour of send producer after another route has been stopped
        sendBody("direct:sieve-stable", "");
        if (isFailFast()) {
            // shared pool is used despite being 'Stopped'
            if (isVerifyProducerServicePoolRemainsStarted()) {
                assertEquals(ServiceStatus.Started, service.getStatus());
            }
            assertEquals("Expected only stable producer in pool", 1, context.getProducerServicePool().size());
            assertEquals("Expected no references to transient producer", 0, references.get(LEAKY_SIEVE_TRANSIENT).get());
            assertEquals("Expected reference to stable producer", 1, references.get(LEAKY_SIEVE_STABLE).get());
        }
        context.startRoute("sieve-transient");
        // ok, back to normal
        assertEquals(ServiceStatus.Started, service.getStatus());
        if (isFailFast()) {
            assertEquals("Expected both producers in pool", 2, context.getProducerServicePool().size());
            assertEquals("Expected one transient producer as service", 1, references.get(LEAKY_SIEVE_TRANSIENT).get());
            assertEquals("Expected one stable producer as service", 1, references.get(LEAKY_SIEVE_STABLE).get());
        }
    }
    if (!isFailFast()) {
        assertEquals("Expected both producers in pool", 2, context.getProducerServicePool().size());
        // if not fixed these will equal the number of iterations in the loop + 1
        assertEquals("Expected one transient producer as service", 1, references.get(LEAKY_SIEVE_TRANSIENT).get());
        assertEquals("Expected one stable producer as service", 1, references.get(LEAKY_SIEVE_STABLE).get());
    }
}
Also used : CamelContext(org.apache.camel.CamelContext) ServiceSupport(org.apache.camel.support.ServiceSupport) LifecycleStrategySupport(org.apache.camel.support.LifecycleStrategySupport) RouteBuilder(org.apache.camel.builder.RouteBuilder) HashMap(java.util.HashMap) Service(org.apache.camel.Service) DefaultEndpoint(org.apache.camel.impl.DefaultEndpoint) Endpoint(org.apache.camel.Endpoint) AtomicLong(java.util.concurrent.atomic.AtomicLong) Route(org.apache.camel.Route)

Example 14 with Service

use of org.apache.camel.Service 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 15 with Service

use of org.apache.camel.Service in project camel by apache.

the class DefaultRouteStartupOrder method getServices.

public List<Service> getServices() {
    List<Service> answer = new ArrayList<Service>();
    Collection<Route> routes = routeService.getRoutes();
    for (Route route : routes) {
        answer.addAll(route.getServices());
    }
    return answer;
}
Also used : ArrayList(java.util.ArrayList) Service(org.apache.camel.Service) Route(org.apache.camel.Route)

Aggregations

Service (org.apache.camel.Service)32 SuspendableService (org.apache.camel.SuspendableService)8 LifecycleStrategy (org.apache.camel.spi.LifecycleStrategy)8 AbstractXmlApplicationContext (org.springframework.context.support.AbstractXmlApplicationContext)8 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)8 StatefulService (org.apache.camel.StatefulService)7 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)6 ArrayList (java.util.ArrayList)5 Processor (org.apache.camel.Processor)5 Route (org.apache.camel.Route)5 IOException (java.io.IOException)4 Endpoint (org.apache.camel.Endpoint)4 MalformedObjectNameException (javax.management.MalformedObjectNameException)3 CamelContextAware (org.apache.camel.CamelContextAware)3 FailedToStartRouteException (org.apache.camel.FailedToStartRouteException)3 NoFactoryAvailableException (org.apache.camel.NoFactoryAvailableException)3 NoSuchEndpointException (org.apache.camel.NoSuchEndpointException)3 ResolveEndpointFailedException (org.apache.camel.ResolveEndpointFailedException)3 RuntimeCamelException (org.apache.camel.RuntimeCamelException)3 VetoCamelContextStartException (org.apache.camel.VetoCamelContextStartException)3