use of org.apache.nifi.nar.NarCloseable in project nifi by apache.
the class StandardProcessorNode method onTrigger.
@Override
public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) {
final Processor processor = processorRef.get().getProcessor();
activateThread();
try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(processor.getClass(), processor.getIdentifier())) {
processor.onTrigger(context, sessionFactory);
} finally {
deactivateThread();
}
}
use of org.apache.nifi.nar.NarCloseable in project nifi by apache.
the class StandardProcessScheduler method unschedule.
@Override
public void unschedule(final ReportingTaskNode taskNode) {
final LifecycleState lifecycleState = getLifecycleState(requireNonNull(taskNode), false);
if (!lifecycleState.isScheduled()) {
return;
}
taskNode.verifyCanStop();
final SchedulingAgent agent = getSchedulingAgent(taskNode.getSchedulingStrategy());
final ReportingTask reportingTask = taskNode.getReportingTask();
taskNode.setScheduledState(ScheduledState.STOPPED);
final Runnable unscheduleReportingTaskRunnable = new Runnable() {
@Override
public void run() {
final ConfigurationContext configurationContext = taskNode.getConfigurationContext();
synchronized (lifecycleState) {
lifecycleState.setScheduled(false);
try {
try (final NarCloseable x = NarCloseable.withComponentNarLoader(reportingTask.getClass(), reportingTask.getIdentifier())) {
ReflectionUtils.invokeMethodsWithAnnotation(OnUnscheduled.class, reportingTask, configurationContext);
}
} catch (final Exception e) {
final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e;
final ComponentLog componentLog = new SimpleProcessLogger(reportingTask.getIdentifier(), reportingTask);
componentLog.error("Failed to invoke @OnUnscheduled method due to {}", cause);
LOG.error("Failed to invoke the @OnUnscheduled methods of {} due to {}; administratively yielding this ReportingTask and will attempt to schedule it again after {}", reportingTask, cause.toString(), administrativeYieldDuration);
LOG.error("", cause);
try {
Thread.sleep(administrativeYieldMillis);
} catch (final InterruptedException ie) {
}
}
agent.unschedule(taskNode, lifecycleState);
if (lifecycleState.getActiveThreadCount() == 0 && lifecycleState.mustCallOnStoppedMethods()) {
ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnStopped.class, reportingTask, configurationContext);
}
}
}
};
componentLifeCycleThreadPool.execute(unscheduleReportingTaskRunnable);
}
use of org.apache.nifi.nar.NarCloseable in project nifi by apache.
the class StandardControllerServiceProvider method createControllerService.
@Override
public ControllerServiceNode createControllerService(final String type, final String id, final BundleCoordinate bundleCoordinate, final Set<URL> additionalUrls, final boolean firstTimeAdded) {
if (type == null || id == null || bundleCoordinate == null) {
throw new NullPointerException();
}
ClassLoader cl = null;
final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();
try {
final Class<?> rawClass;
try {
final Bundle csBundle = ExtensionManager.getBundle(bundleCoordinate);
if (csBundle == null) {
throw new ControllerServiceInstantiationException("Unable to find bundle for coordinate " + bundleCoordinate.getCoordinate());
}
cl = ExtensionManager.createInstanceClassLoader(type, id, csBundle, additionalUrls);
Thread.currentThread().setContextClassLoader(cl);
rawClass = Class.forName(type, false, cl);
} catch (final Exception e) {
logger.error("Could not create Controller Service of type " + type + " for ID " + id + "; creating \"Ghost\" implementation", e);
Thread.currentThread().setContextClassLoader(currentContextClassLoader);
return createGhostControllerService(type, id, bundleCoordinate);
}
final Class<? extends ControllerService> controllerServiceClass = rawClass.asSubclass(ControllerService.class);
final ControllerService originalService = controllerServiceClass.newInstance();
final StandardControllerServiceInvocationHandler invocationHandler = new StandardControllerServiceInvocationHandler(originalService);
// extract all interfaces... controllerServiceClass is non null so getAllInterfaces is non null
final List<Class<?>> interfaceList = ClassUtils.getAllInterfaces(controllerServiceClass);
final Class<?>[] interfaces = interfaceList.toArray(new Class<?>[interfaceList.size()]);
final ControllerService proxiedService;
if (cl == null) {
proxiedService = (ControllerService) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, invocationHandler);
} else {
proxiedService = (ControllerService) Proxy.newProxyInstance(cl, interfaces, invocationHandler);
}
logger.info("Created Controller Service of type {} with identifier {}", type, id);
final ComponentLog serviceLogger = new SimpleProcessLogger(id, originalService);
final TerminationAwareLogger terminationAwareLogger = new TerminationAwareLogger(serviceLogger);
originalService.initialize(new StandardControllerServiceInitializationContext(id, terminationAwareLogger, this, getStateManager(id), nifiProperties));
final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(this, variableRegistry);
final LoggableComponent<ControllerService> originalLoggableComponent = new LoggableComponent<>(originalService, bundleCoordinate, terminationAwareLogger);
final LoggableComponent<ControllerService> proxiedLoggableComponent = new LoggableComponent<>(proxiedService, bundleCoordinate, terminationAwareLogger);
final ComponentVariableRegistry componentVarRegistry = new StandardComponentVariableRegistry(this.variableRegistry);
final ControllerServiceNode serviceNode = new StandardControllerServiceNode(originalLoggableComponent, proxiedLoggableComponent, invocationHandler, id, validationContextFactory, this, componentVarRegistry, flowController);
serviceNode.setName(rawClass.getSimpleName());
invocationHandler.setServiceNode(serviceNode);
if (firstTimeAdded) {
try (final NarCloseable x = NarCloseable.withComponentNarLoader(originalService.getClass(), originalService.getIdentifier())) {
ReflectionUtils.invokeMethodsWithAnnotation(OnAdded.class, originalService);
} catch (final Exception e) {
throw new ComponentLifeCycleException("Failed to invoke On-Added Lifecycle methods of " + originalService, e);
}
}
serviceCache.putIfAbsent(id, serviceNode);
return serviceNode;
} catch (final Throwable t) {
throw new ControllerServiceInstantiationException(t);
} finally {
if (currentContextClassLoader != null) {
Thread.currentThread().setContextClassLoader(currentContextClassLoader);
}
}
}
use of org.apache.nifi.nar.NarCloseable in project nifi by apache.
the class AbstractConfiguredComponent method getValidationErrors.
public Collection<ValidationResult> getValidationErrors(final Set<String> serviceIdentifiersNotToValidate) {
final List<ValidationResult> results = new ArrayList<>();
lock.lock();
try {
final ValidationContext validationContext;
if (serviceIdentifiersNotToValidate == null || serviceIdentifiersNotToValidate.isEmpty()) {
validationContext = getValidationContext();
} else {
validationContext = getValidationContextFactory().newValidationContext(serviceIdentifiersNotToValidate, getProperties(), getAnnotationData(), getProcessGroupIdentifier(), getIdentifier());
}
final Collection<ValidationResult> validationResults;
try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(getComponent().getClass(), getComponent().getIdentifier())) {
validationResults = getComponent().validate(validationContext);
}
for (final ValidationResult result : validationResults) {
if (!result.isValid()) {
results.add(result);
}
}
} catch (final Throwable t) {
logger.error("Failed to perform validation of " + this, t);
results.add(new ValidationResult.Builder().explanation("Failed to run validation due to " + t.toString()).valid(false).build());
} finally {
lock.unlock();
}
return results;
}
use of org.apache.nifi.nar.NarCloseable in project nifi by apache.
the class FlowController method createProcessor.
/**
* <p>
* Creates a new ProcessorNode with the given type and identifier and
* optionally initializes it.
* </p>
*
* @param type the fully qualified Processor class name
* @param id the unique ID of the Processor
* @param coordinate the bundle coordinate for this processor
* @param firstTimeAdded whether or not this is the first time this
* Processor is added to the graph. If {@code true}, will invoke methods
* annotated with the {@link OnAdded} annotation.
* @return new processor node
* @throws NullPointerException if either arg is null
* @throws ProcessorInstantiationException if the processor cannot be
* instantiated for any reason
*/
public ProcessorNode createProcessor(final String type, String id, final BundleCoordinate coordinate, final Set<URL> additionalUrls, final boolean firstTimeAdded, final boolean registerLogObserver) throws ProcessorInstantiationException {
id = id.intern();
boolean creationSuccessful;
LoggableComponent<Processor> processor;
try {
processor = instantiateProcessor(type, id, coordinate, additionalUrls);
creationSuccessful = true;
} catch (final ProcessorInstantiationException pie) {
LOG.error("Could not create Processor of type " + type + " for ID " + id + "; creating \"Ghost\" implementation", pie);
final GhostProcessor ghostProc = new GhostProcessor();
ghostProc.setIdentifier(id);
ghostProc.setCanonicalClassName(type);
processor = new LoggableComponent<>(ghostProc, coordinate, null);
creationSuccessful = false;
}
final ComponentVariableRegistry componentVarRegistry = new StandardComponentVariableRegistry(this.variableRegistry);
final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(controllerServiceProvider, componentVarRegistry);
final ProcessorNode procNode;
if (creationSuccessful) {
procNode = new StandardProcessorNode(processor, id, validationContextFactory, processScheduler, controllerServiceProvider, nifiProperties, componentVarRegistry, this);
} else {
final String simpleClassName = type.contains(".") ? StringUtils.substringAfterLast(type, ".") : type;
final String componentType = "(Missing) " + simpleClassName;
procNode = new StandardProcessorNode(processor, id, validationContextFactory, processScheduler, controllerServiceProvider, componentType, type, nifiProperties, componentVarRegistry, this, true);
}
final LogRepository logRepository = LogRepositoryFactory.getRepository(id);
if (registerLogObserver) {
logRepository.addObserver(StandardProcessorNode.BULLETIN_OBSERVER_ID, LogLevel.WARN, new ProcessorLogObserver(getBulletinRepository(), procNode));
}
try {
final Class<?> procClass = procNode.getProcessor().getClass();
if (procClass.isAnnotationPresent(DefaultSettings.class)) {
DefaultSettings ds = procClass.getAnnotation(DefaultSettings.class);
try {
procNode.setYieldPeriod(ds.yieldDuration());
} catch (Throwable ex) {
LOG.error(String.format("Error while setting yield period from DefaultSettings annotation:%s", ex.getMessage()), ex);
}
try {
procNode.setPenalizationPeriod(ds.penaltyDuration());
} catch (Throwable ex) {
LOG.error(String.format("Error while setting penalty duration from DefaultSettings annotation:%s", ex.getMessage()), ex);
}
// the caller said to register the log observer, otherwise we could be changing the level when we didn't mean to
if (registerLogObserver) {
try {
procNode.setBulletinLevel(ds.bulletinLevel());
} catch (Throwable ex) {
LOG.error(String.format("Error while setting bulletin level from DefaultSettings annotation:%s", ex.getMessage()), ex);
}
}
}
} catch (Throwable ex) {
LOG.error(String.format("Error while setting default settings from DefaultSettings annotation: %s", ex.getMessage()), ex);
}
if (firstTimeAdded) {
try (final NarCloseable x = NarCloseable.withComponentNarLoader(procNode.getProcessor().getClass(), procNode.getProcessor().getIdentifier())) {
ReflectionUtils.invokeMethodsWithAnnotation(OnAdded.class, procNode.getProcessor());
} catch (final Exception e) {
if (registerLogObserver) {
logRepository.removeObserver(StandardProcessorNode.BULLETIN_OBSERVER_ID);
}
throw new ComponentLifeCycleException("Failed to invoke @OnAdded methods of " + procNode.getProcessor(), e);
}
if (firstTimeAdded) {
try (final NarCloseable nc = NarCloseable.withComponentNarLoader(procNode.getProcessor().getClass(), procNode.getProcessor().getIdentifier())) {
ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, procNode.getProcessor());
}
}
}
return procNode;
}
Aggregations