Search in sources :

Example 76 with ControllerServiceNode

use of org.apache.nifi.controller.service.ControllerServiceNode in project nifi by apache.

the class FlowController method shutdown.

/**
 * Triggers the controller to begin shutdown, stopping all processors and
 * terminating the scheduling engine. After calling this method, the
 * {@link #isTerminated()} method will indicate whether or not the shutdown
 * has finished.
 *
 * @param kill if <code>true</code>, attempts to stop all active threads,
 * but makes no guarantee that this will happen
 *
 * @throws IllegalStateException if the controller is already stopped or
 * currently in the processor of stopping
 */
public void shutdown(final boolean kill) {
    this.shutdown = true;
    stopAllProcessors();
    readLock.lock();
    try {
        if (isTerminated() || timerDrivenEngineRef.get().isTerminating()) {
            throw new IllegalStateException("Controller already stopped or still stopping...");
        }
        if (leaderElectionManager != null) {
            leaderElectionManager.stop();
        }
        if (heartbeatMonitor != null) {
            heartbeatMonitor.stop();
        }
        if (kill) {
            this.timerDrivenEngineRef.get().shutdownNow();
            this.eventDrivenEngineRef.get().shutdownNow();
            LOG.info("Initiated immediate shutdown of flow controller...");
        } else {
            this.timerDrivenEngineRef.get().shutdown();
            this.eventDrivenEngineRef.get().shutdown();
            LOG.info("Initiated graceful shutdown of flow controller...waiting up to " + gracefulShutdownSeconds + " seconds");
        }
        clusterTaskExecutor.shutdownNow();
        if (zooKeeperStateServer != null) {
            zooKeeperStateServer.shutdown();
        }
        // Trigger any processors' methods marked with @OnShutdown to be called
        getRootGroup().shutdown();
        stateManagerProvider.shutdown();
        // invoke any methods annotated with @OnShutdown on Controller Services
        for (final ControllerServiceNode serviceNode : getAllControllerServices()) {
            try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(serviceNode.getControllerServiceImplementation().getClass(), serviceNode.getIdentifier())) {
                final ConfigurationContext configContext = new StandardConfigurationContext(serviceNode, controllerServiceProvider, null, variableRegistry);
                ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnShutdown.class, serviceNode.getControllerServiceImplementation(), configContext);
            }
        }
        // invoke any methods annotated with @OnShutdown on Reporting Tasks
        for (final ReportingTaskNode taskNode : getAllReportingTasks()) {
            final ConfigurationContext configContext = taskNode.getConfigurationContext();
            try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(taskNode.getReportingTask().getClass(), taskNode.getIdentifier())) {
                ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnShutdown.class, taskNode.getReportingTask(), configContext);
            }
        }
        try {
            this.timerDrivenEngineRef.get().awaitTermination(gracefulShutdownSeconds / 2, TimeUnit.SECONDS);
            this.eventDrivenEngineRef.get().awaitTermination(gracefulShutdownSeconds / 2, TimeUnit.SECONDS);
        } catch (final InterruptedException ie) {
            LOG.info("Interrupted while waiting for controller termination.");
        }
        try {
            flowFileRepository.close();
        } catch (final Throwable t) {
            LOG.warn("Unable to shut down FlowFileRepository due to {}", new Object[] { t });
        }
        if (this.timerDrivenEngineRef.get().isTerminated() && eventDrivenEngineRef.get().isTerminated()) {
            LOG.info("Controller has been terminated successfully.");
        } else {
            LOG.warn("Controller hasn't terminated properly.  There exists an uninterruptable thread that " + "will take an indeterminate amount of time to stop.  Might need to kill the program manually.");
        }
        for (final RemoteSiteListener listener : externalSiteListeners) {
            listener.stop();
        }
        if (processScheduler != null) {
            processScheduler.shutdown();
        }
        if (contentRepository != null) {
            contentRepository.shutdown();
        }
        if (provenanceRepository != null) {
            try {
                provenanceRepository.close();
            } catch (final IOException ioe) {
                LOG.warn("There was a problem shutting down the Provenance Repository: " + ioe.toString());
                if (LOG.isDebugEnabled()) {
                    LOG.warn("", ioe);
                }
            }
        }
    } finally {
        readLock.unlock();
    }
}
Also used : StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) NarCloseable(org.apache.nifi.nar.NarCloseable) StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) SocketRemoteSiteListener(org.apache.nifi.remote.SocketRemoteSiteListener) RemoteSiteListener(org.apache.nifi.remote.RemoteSiteListener) HttpRemoteSiteListener(org.apache.nifi.remote.HttpRemoteSiteListener) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) StandardReportingTaskNode(org.apache.nifi.controller.reporting.StandardReportingTaskNode) IOException(java.io.IOException)

Example 77 with ControllerServiceNode

use of org.apache.nifi.controller.service.ControllerServiceNode in project nifi by apache.

the class AbstractConfiguredComponent method setProperty.

// Keep setProperty/removeProperty private so that all calls go through setProperties
private void setProperty(final String name, final String value) {
    if (null == name || null == value) {
        throw new IllegalArgumentException("Name or Value can not be null");
    }
    final PropertyDescriptor descriptor = getComponent().getPropertyDescriptor(name);
    final String oldValue = properties.put(descriptor, value);
    if (!value.equals(oldValue)) {
        if (descriptor.getControllerServiceDefinition() != null) {
            if (oldValue != null) {
                final ControllerServiceNode oldNode = serviceProvider.getControllerServiceNode(oldValue);
                if (oldNode != null) {
                    oldNode.removeReference(this);
                }
            }
            final ControllerServiceNode newNode = serviceProvider.getControllerServiceNode(value);
            if (newNode != null) {
                newNode.addReference(this);
            }
        }
        try {
            onPropertyModified(descriptor, oldValue, value);
        } catch (final Exception e) {
        // nothing really to do here...
        }
    }
}
Also used : PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) MalformedURLException(java.net.MalformedURLException)

Example 78 with ControllerServiceNode

use of org.apache.nifi.controller.service.ControllerServiceNode in project nifi by apache.

the class AbstractConfiguredComponent method validate.

@Override
public Collection<ValidationResult> validate(final ValidationContext context) {
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(getComponent().getClass(), getComponent().getIdentifier())) {
        final Collection<ValidationResult> validationResults = getComponent().validate(context);
        // validate selected controller services implement the API required by the processor
        final List<PropertyDescriptor> supportedDescriptors = getComponent().getPropertyDescriptors();
        if (null != supportedDescriptors) {
            for (final PropertyDescriptor descriptor : supportedDescriptors) {
                if (descriptor.getControllerServiceDefinition() == null) {
                    // skip properties that aren't for a controller service
                    continue;
                }
                final String controllerServiceId = context.getProperty(descriptor).getValue();
                if (controllerServiceId == null) {
                    // if the property value is null we should already have a validation error
                    continue;
                }
                final ControllerServiceNode controllerServiceNode = getControllerServiceProvider().getControllerServiceNode(controllerServiceId);
                if (controllerServiceNode == null) {
                    // if the node was null we should already have a validation error
                    continue;
                }
                final Class<? extends ControllerService> controllerServiceApiClass = descriptor.getControllerServiceDefinition();
                final ClassLoader controllerServiceApiClassLoader = controllerServiceApiClass.getClassLoader();
                final Consumer<String> addValidationError = explanation -> validationResults.add(new ValidationResult.Builder().input(controllerServiceId).subject(descriptor.getDisplayName()).valid(false).explanation(explanation).build());
                final Bundle controllerServiceApiBundle = ExtensionManager.getBundle(controllerServiceApiClassLoader);
                if (controllerServiceApiBundle == null) {
                    addValidationError.accept(String.format("Unable to find bundle for ControllerService API class %s.", controllerServiceApiClass.getCanonicalName()));
                    continue;
                }
                final BundleCoordinate controllerServiceApiCoordinate = controllerServiceApiBundle.getBundleDetails().getCoordinate();
                final Bundle controllerServiceBundle = ExtensionManager.getBundle(controllerServiceNode.getBundleCoordinate());
                if (controllerServiceBundle == null) {
                    addValidationError.accept(String.format("Unable to find bundle for coordinate %s.", controllerServiceNode.getBundleCoordinate()));
                    continue;
                }
                final BundleCoordinate controllerServiceCoordinate = controllerServiceBundle.getBundleDetails().getCoordinate();
                final boolean matchesApi = matchesApi(controllerServiceBundle, controllerServiceApiCoordinate);
                if (!matchesApi) {
                    final String controllerServiceType = controllerServiceNode.getComponentType();
                    final String controllerServiceApiType = controllerServiceApiClass.getSimpleName();
                    final String explanation = new StringBuilder().append(controllerServiceType).append(" - ").append(controllerServiceCoordinate.getVersion()).append(" from ").append(controllerServiceCoordinate.getGroup()).append(" - ").append(controllerServiceCoordinate.getId()).append(" is not compatible with ").append(controllerServiceApiType).append(" - ").append(controllerServiceApiCoordinate.getVersion()).append(" from ").append(controllerServiceApiCoordinate.getGroup()).append(" - ").append(controllerServiceApiCoordinate.getId()).toString();
                    addValidationError.accept(explanation);
                }
            }
        }
        return validationResults;
    }
}
Also used : Bundle(org.apache.nifi.bundle.Bundle) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate) URL(java.net.URL) ValidationContext(org.apache.nifi.components.ValidationContext) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConfigurableComponent(org.apache.nifi.components.ConfigurableComponent) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils(org.apache.commons.lang3.StringUtils) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ClassLoaderUtils(org.apache.nifi.util.file.classloader.ClassLoaderUtils) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ControllerServiceProvider(org.apache.nifi.controller.service.ControllerServiceProvider) NarCloseable(org.apache.nifi.nar.NarCloseable) LinkedHashSet(java.util.LinkedHashSet) ValidationResult(org.apache.nifi.components.ValidationResult) CharacterFilterUtils(org.apache.nifi.util.CharacterFilterUtils) StandardPropertyValue(org.apache.nifi.attribute.expression.language.StandardPropertyValue) Logger(org.slf4j.Logger) ReentrantLock(java.util.concurrent.locks.ReentrantLock) MalformedURLException(java.net.MalformedURLException) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Objects(java.util.Objects) Consumer(java.util.function.Consumer) List(java.util.List) Lock(java.util.concurrent.locks.Lock) ComponentVariableRegistry(org.apache.nifi.registry.ComponentVariableRegistry) ExtensionManager(org.apache.nifi.nar.ExtensionManager) Collections(java.util.Collections) NarCloseable(org.apache.nifi.nar.NarCloseable) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) Bundle(org.apache.nifi.bundle.Bundle) ValidationResult(org.apache.nifi.components.ValidationResult) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode)

Example 79 with ControllerServiceNode

use of org.apache.nifi.controller.service.ControllerServiceNode in project nifi by apache.

the class StandardNiFiServiceFacade method findControllerServiceReferencingComponentIdentifiers.

/**
 * Finds the identifiers for all components referencing a ControllerService.
 *
 * @param reference      ControllerServiceReference
 * @param visited        ControllerServices we've already visited
 */
private void findControllerServiceReferencingComponentIdentifiers(final ControllerServiceReference reference, final Set<ControllerServiceNode> visited) {
    for (final ConfiguredComponent component : reference.getReferencingComponents()) {
        // if this is a ControllerService consider it's referencing components
        if (component instanceof ControllerServiceNode) {
            final ControllerServiceNode node = (ControllerServiceNode) component;
            if (!visited.contains(node)) {
                findControllerServiceReferencingComponentIdentifiers(node.getReferences(), visited);
            }
            visited.add(node);
        }
    }
}
Also used : ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) ConfiguredComponent(org.apache.nifi.controller.ConfiguredComponent)

Example 80 with ControllerServiceNode

use of org.apache.nifi.controller.service.ControllerServiceNode in project nifi by apache.

the class DtoFactory method createPropertyDescriptorDto.

/**
 * Creates a PropertyDesriptorDTO from the specified PropertyDesriptor.
 *
 * @param propertyDescriptor descriptor
 * @param groupId the Identifier of the Process Group that the component belongs to
 * @return dto
 */
public PropertyDescriptorDTO createPropertyDescriptorDto(final PropertyDescriptor propertyDescriptor, final String groupId) {
    if (propertyDescriptor == null) {
        return null;
    }
    final PropertyDescriptorDTO dto = new PropertyDescriptorDTO();
    dto.setName(propertyDescriptor.getName());
    dto.setDisplayName(propertyDescriptor.getDisplayName());
    dto.setRequired(propertyDescriptor.isRequired());
    dto.setSensitive(propertyDescriptor.isSensitive());
    dto.setDynamic(propertyDescriptor.isDynamic());
    dto.setDescription(propertyDescriptor.getDescription());
    dto.setDefaultValue(propertyDescriptor.getDefaultValue());
    dto.setSupportsEl(propertyDescriptor.isExpressionLanguageSupported());
    // set the identifies controller service is applicable
    if (propertyDescriptor.getControllerServiceDefinition() != null) {
        final Class serviceClass = propertyDescriptor.getControllerServiceDefinition();
        final Bundle serviceBundle = ExtensionManager.getBundle(serviceClass.getClassLoader());
        dto.setIdentifiesControllerService(serviceClass.getName());
        dto.setIdentifiesControllerServiceBundle(createBundleDto(serviceBundle.getBundleDetails().getCoordinate()));
    }
    final Class<? extends ControllerService> serviceDefinition = propertyDescriptor.getControllerServiceDefinition();
    if (propertyDescriptor.getAllowableValues() == null) {
        if (serviceDefinition == null) {
            dto.setAllowableValues(null);
        } else {
            final List<AllowableValueEntity> allowableValues = new ArrayList<>();
            final List<String> controllerServiceIdentifiers = new ArrayList<>(controllerServiceProvider.getControllerServiceIdentifiers(serviceDefinition, groupId));
            Collections.sort(controllerServiceIdentifiers, Collator.getInstance(Locale.US));
            for (final String serviceIdentifier : controllerServiceIdentifiers) {
                final ControllerServiceNode service = controllerServiceProvider.getControllerServiceNode(serviceIdentifier);
                final boolean isServiceAuthorized = service.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
                final String displayName = isServiceAuthorized ? service.getName() : serviceIdentifier;
                final AllowableValueDTO allowableValue = new AllowableValueDTO();
                allowableValue.setDisplayName(displayName);
                allowableValue.setValue(serviceIdentifier);
                allowableValues.add(entityFactory.createAllowableValueEntity(allowableValue, isServiceAuthorized));
            }
            dto.setAllowableValues(allowableValues);
        }
    } else {
        final List<AllowableValueEntity> allowableValues = new ArrayList<>();
        for (final AllowableValue allowableValue : propertyDescriptor.getAllowableValues()) {
            final AllowableValueDTO allowableValueDto = new AllowableValueDTO();
            allowableValueDto.setDisplayName(allowableValue.getDisplayName());
            allowableValueDto.setValue(allowableValue.getValue());
            allowableValueDto.setDescription(allowableValue.getDescription());
            allowableValues.add(entityFactory.createAllowableValueEntity(allowableValueDto, true));
        }
        dto.setAllowableValues(allowableValues);
    }
    return dto;
}
Also used : Bundle(org.apache.nifi.bundle.Bundle) ArrayList(java.util.ArrayList) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) AllowableValue(org.apache.nifi.components.AllowableValue) AllowableValueEntity(org.apache.nifi.web.api.entity.AllowableValueEntity)

Aggregations

ControllerServiceNode (org.apache.nifi.controller.service.ControllerServiceNode)88 HashSet (java.util.HashSet)29 ProcessGroup (org.apache.nifi.groups.ProcessGroup)26 HashMap (java.util.HashMap)25 PropertyDescriptor (org.apache.nifi.components.PropertyDescriptor)25 ArrayList (java.util.ArrayList)24 Map (java.util.Map)24 LinkedHashSet (java.util.LinkedHashSet)22 Test (org.junit.Test)19 BundleCoordinate (org.apache.nifi.bundle.BundleCoordinate)18 ProcessorNode (org.apache.nifi.controller.ProcessorNode)18 ConfiguredComponent (org.apache.nifi.controller.ConfiguredComponent)17 VersionedProcessGroup (org.apache.nifi.registry.flow.VersionedProcessGroup)17 Set (java.util.Set)16 Connection (org.apache.nifi.connectable.Connection)16 List (java.util.List)15 Port (org.apache.nifi.connectable.Port)15 Label (org.apache.nifi.controller.label.Label)15 RemoteProcessGroup (org.apache.nifi.groups.RemoteProcessGroup)15 RemoteGroupPort (org.apache.nifi.remote.RemoteGroupPort)15