use of org.apache.camel.Service 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.Service in project camel by apache.
the class TransactedDefinition method createProcessor.
@Override
public Processor createProcessor(RouteContext routeContext) throws Exception {
Policy policy = resolvePolicy(routeContext);
ObjectHelper.notNull(policy, "policy", this);
// before wrap
policy.beforeWrap(routeContext, this);
// create processor after the before wrap
Processor childProcessor = this.createChildProcessor(routeContext, true);
// wrap
Processor target = policy.wrap(routeContext, childProcessor);
if (!(target instanceof Service)) {
// wrap the target so it becomes a service and we can manage its lifecycle
target = new WrapProcessor(target, childProcessor);
}
return target;
}
use of org.apache.camel.Service in project camel by apache.
the class ProcessDefinition method createProcessor.
@Override
public Processor createProcessor(RouteContext routeContext) {
Processor answer = processor;
if (processor == null) {
ObjectHelper.notNull(ref, "ref", this);
answer = routeContext.mandatoryLookup(getRef(), Processor.class);
}
// (a Processor must be a Service to be enlisted in JMX)
if (!(answer instanceof Service)) {
if (answer instanceof AsyncProcessor) {
// the processor is async by nature so use the async delegate
answer = new DelegateAsyncProcessor(answer);
} else {
// the processor is sync by nature so use the sync delegate
answer = new DelegateSyncProcessor(answer);
}
}
return answer;
}
use of org.apache.camel.Service in project camel by apache.
the class DefaultCamelContext method doStartCamel.
private void doStartCamel() throws Exception {
// custom properties may use property placeholders so resolve those early on
if (globalOptions != null && !globalOptions.isEmpty()) {
for (Map.Entry<String, String> entry : globalOptions.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (value != null) {
String replaced = resolvePropertyPlaceholders(value);
if (!value.equals(replaced)) {
if (log.isDebugEnabled()) {
log.debug("Camel property with key {} replaced value from {} -> {}", new Object[] { key, value, replaced });
}
entry.setValue(replaced);
}
}
}
}
if (classResolver instanceof CamelContextAware) {
((CamelContextAware) classResolver).setCamelContext(this);
}
if (log.isDebugEnabled()) {
log.debug("Using ClassResolver={}, PackageScanClassResolver={}, ApplicationContextClassLoader={}", new Object[] { getClassResolver(), getPackageScanClassResolver(), getApplicationContextClassLoader() });
}
if (isStreamCaching()) {
log.info("StreamCaching is enabled on CamelContext: {}", getName());
}
if (isTracing()) {
// tracing is added in the DefaultChannel so we can enable it on the fly
log.info("Tracing is enabled on CamelContext: {}", getName());
}
if (isUseMDCLogging()) {
// log if MDC has been enabled
log.info("MDC logging is enabled on CamelContext: {}", getName());
}
if (isHandleFault()) {
// only add a new handle fault if not already configured
if (HandleFault.getHandleFault(this) == null) {
log.info("HandleFault is enabled on CamelContext: {}", getName());
addInterceptStrategy(new HandleFault());
}
}
if (getDelayer() != null && getDelayer() > 0) {
log.info("Delayer is enabled with: {} ms. on CamelContext: {}", getDelayer(), getName());
}
// register debugger
if (getDebugger() != null) {
log.info("Debugger: {} is enabled on CamelContext: {}", getDebugger(), getName());
// register this camel context on the debugger
getDebugger().setCamelContext(this);
startService(getDebugger());
addInterceptStrategy(new Debug(getDebugger()));
}
// start management strategy before lifecycles are started
ManagementStrategy managementStrategy = getManagementStrategy();
// inject CamelContext if aware
if (managementStrategy instanceof CamelContextAware) {
((CamelContextAware) managementStrategy).setCamelContext(this);
}
ServiceHelper.startService(managementStrategy);
// start lifecycle strategies
ServiceHelper.startServices(lifecycleStrategies);
Iterator<LifecycleStrategy> it = lifecycleStrategies.iterator();
while (it.hasNext()) {
LifecycleStrategy strategy = it.next();
try {
strategy.onContextStart(this);
} catch (VetoCamelContextStartException e) {
// okay we should not start Camel since it was vetoed
log.warn("Lifecycle strategy vetoed starting CamelContext ({}) due: {}", getName(), e.getMessage());
throw e;
} catch (Exception e) {
log.warn("Lifecycle strategy " + strategy + " failed starting CamelContext ({}) due: {}", getName(), e.getMessage());
throw e;
}
}
// start notifiers as services
for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
if (notifier instanceof Service) {
Service service = (Service) notifier;
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onServiceAdd(this, service, null);
}
}
if (notifier instanceof Service) {
startService((Service) notifier);
}
}
// must let some bootstrap service be started before we can notify the starting event
EventHelper.notifyCamelContextStarting(this);
forceLazyInitialization();
// re-create endpoint registry as the cache size limit may be set after the constructor of this instance was called.
// and we needed to create endpoints up-front as it may be accessed before this context is started
endpoints = new DefaultEndpointRegistry(this, endpoints);
// add this as service and force pre-start them
addService(endpoints, true, true);
// special for executorServiceManager as want to stop it manually so false in stopOnShutdown
addService(executorServiceManager, false, true);
addService(producerServicePool, true, true);
addService(pollingConsumerServicePool, true, true);
addService(inflightRepository, true, true);
addService(asyncProcessorAwaitManager, true, true);
addService(shutdownStrategy, true, true);
addService(packageScanClassResolver, true, true);
addService(restRegistry, true, true);
addService(messageHistoryFactory, true, true);
addService(runtimeCamelCatalog, true, true);
if (reloadStrategy != null) {
log.info("Using ReloadStrategy: {}", reloadStrategy);
addService(reloadStrategy, true, true);
}
// Initialize declarative transformer/validator registry
transformerRegistry = new DefaultTransformerRegistry(this, transformers);
addService(transformerRegistry, true, true);
validatorRegistry = new DefaultValidatorRegistry(this, validators);
addService(validatorRegistry, true, true);
if (runtimeEndpointRegistry != null) {
if (runtimeEndpointRegistry instanceof EventNotifier) {
getManagementStrategy().addEventNotifier((EventNotifier) runtimeEndpointRegistry);
}
addService(runtimeEndpointRegistry, true, true);
}
// eager lookup any configured properties component to avoid subsequent lookup attempts which may impact performance
// due we use properties component for property placeholder resolution at runtime
Component existing = CamelContextHelper.lookupPropertiesComponent(this, false);
if (existing != null) {
// store reference to the existing properties component
if (existing instanceof PropertiesComponent) {
propertiesComponent = (PropertiesComponent) existing;
} else {
// properties component must be expected type
throw new IllegalArgumentException("Found properties component of type: " + existing.getClass() + " instead of expected: " + PropertiesComponent.class);
}
}
// start components
startServices(components.values());
// start the route definitions before the routes is started
startRouteDefinitions(routeDefinitions);
// is there any stream caching enabled then log an info about this and its limit of spooling to disk, so people is aware of this
boolean streamCachingInUse = isStreamCaching();
if (!streamCachingInUse) {
for (RouteDefinition route : routeDefinitions) {
Boolean routeCache = CamelContextHelper.parseBoolean(this, route.getStreamCache());
if (routeCache != null && routeCache) {
streamCachingInUse = true;
break;
}
}
}
if (streamCachingInUse) {
// stream caching is in use so enable the strategy
getStreamCachingStrategy().setEnabled(true);
addService(getStreamCachingStrategy(), true, true);
} else {
// log if stream caching is not in use as this can help people to enable it if they use streams
log.info("StreamCaching is not in use. If using streams then its recommended to enable stream caching." + " See more details at http://camel.apache.org/stream-caching.html");
}
if (isAllowUseOriginalMessage()) {
log.debug("AllowUseOriginalMessage enabled because UseOriginalMessage is in use");
}
// start routes
if (doNotStartRoutesOnFirstStart) {
log.debug("Skip starting of routes as CamelContext has been configured with autoStartup=false");
}
// invoke this logic to warmup the routes and if possible also start the routes
doStartOrResumeRoutes(routeServices, true, !doNotStartRoutesOnFirstStart, false, true);
// starting will continue in the start method
}
use of org.apache.camel.Service in project camel by apache.
the class DefaultCamelContext method initComponent.
/**
* Function to initialize a component and auto start. Returns null if the autoCreateComponents is disabled
*/
private Component initComponent(String name, boolean autoCreateComponents, boolean autoStart) {
Component component = null;
if (autoCreateComponents) {
try {
if (log.isDebugEnabled()) {
log.debug("Using ComponentResolver: {} to resolve component with name: {}", getComponentResolver(), name);
}
component = getComponentResolver().resolveComponent(name, this);
if (component != null) {
component.setCamelContext(this);
postInitComponent(name, component);
if (autoStart && (isStarted() || isStarting())) {
// If the component is looked up after the context is started, lets start it up.
if (component instanceof Service) {
startService((Service) component);
}
}
}
} catch (Exception e) {
throw new RuntimeCamelException("Cannot auto create component: " + name, e);
}
}
return component;
}
Aggregations