Search in sources :

Example 1 with StandardConfigurationContext

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

the class FlowController method reload.

@Override
public void reload(final ControllerServiceNode existingNode, final String newType, final BundleCoordinate bundleCoordinate, final Set<URL> additionalUrls) throws ControllerServiceInstantiationException {
    if (existingNode == null) {
        throw new IllegalStateException("Existing ControllerServiceNode cannot be null");
    }
    final String id = existingNode.getIdentifier();
    // ghost components will have a null logger
    if (existingNode.getLogger() != null) {
        existingNode.getLogger().debug("Reloading component {} to type {} from bundle {}", new Object[] { id, newType, bundleCoordinate });
    }
    // createControllerService will create a new instance class loader for the same id so
    // save the instance class loader to use it for calling OnRemoved on the existing service
    final ClassLoader existingInstanceClassLoader = ExtensionManager.getInstanceClassLoader(id);
    // create a new node with firstTimeAdded as true so lifecycle methods get called
    // attempt the creation to make sure it works before firing the OnRemoved methods below
    final ControllerServiceNode newNode = controllerServiceProvider.createControllerService(newType, id, bundleCoordinate, additionalUrls, true);
    // call OnRemoved for the existing service using the previous instance class loader
    try (final NarCloseable x = NarCloseable.withComponentNarLoader(existingInstanceClassLoader)) {
        final ConfigurationContext configurationContext = new StandardConfigurationContext(existingNode, controllerServiceProvider, null, variableRegistry);
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnRemoved.class, existingNode.getControllerServiceImplementation(), configurationContext);
    } finally {
        ExtensionManager.closeURLClassLoader(id, existingInstanceClassLoader);
    }
    // take the invocation handler that was created for new proxy and is set to look at the new node,
    // and set it to look at the existing node
    final ControllerServiceInvocationHandler invocationHandler = newNode.getInvocationHandler();
    invocationHandler.setServiceNode(existingNode);
    // create LoggableComponents for the proxy and implementation
    final ComponentLog componentLogger = new SimpleProcessLogger(id, newNode.getControllerServiceImplementation());
    final TerminationAwareLogger terminationAwareLogger = new TerminationAwareLogger(componentLogger);
    LogRepositoryFactory.getRepository(id).setLogger(terminationAwareLogger);
    final LoggableComponent<ControllerService> loggableProxy = new LoggableComponent<>(newNode.getProxiedControllerService(), bundleCoordinate, terminationAwareLogger);
    final LoggableComponent<ControllerService> loggableImplementation = new LoggableComponent<>(newNode.getControllerServiceImplementation(), bundleCoordinate, terminationAwareLogger);
    // set the new impl, proxy, and invocation handler into the existing node
    existingNode.setControllerServiceAndProxy(loggableImplementation, loggableProxy, invocationHandler);
    existingNode.setExtensionMissing(newNode.isExtensionMissing());
    // need to refresh the properties in case we are changing from ghost component to real component
    existingNode.refreshProperties();
}
Also used : NarCloseable(org.apache.nifi.nar.NarCloseable) StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) ControllerServiceInvocationHandler(org.apache.nifi.controller.service.ControllerServiceInvocationHandler) ComponentLog(org.apache.nifi.logging.ComponentLog) StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) NarThreadContextClassLoader(org.apache.nifi.nar.NarThreadContextClassLoader) SimpleProcessLogger(org.apache.nifi.processor.SimpleProcessLogger)

Example 2 with StandardConfigurationContext

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

the class FlowController method removeRootControllerService.

public void removeRootControllerService(final ControllerServiceNode service) {
    final ControllerServiceNode existing = rootControllerServices.get(requireNonNull(service).getIdentifier());
    if (existing == null) {
        throw new IllegalStateException(service + " is not a member of this Process Group");
    }
    service.verifyCanDelete();
    try (final NarCloseable x = NarCloseable.withComponentNarLoader(service.getControllerServiceImplementation().getClass(), service.getIdentifier())) {
        final ConfigurationContext configurationContext = new StandardConfigurationContext(service, controllerServiceProvider, null, variableRegistry);
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnRemoved.class, service.getControllerServiceImplementation(), configurationContext);
    }
    for (final Map.Entry<PropertyDescriptor, String> entry : service.getProperties().entrySet()) {
        final PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.getControllerServiceDefinition() != null) {
            final String value = entry.getValue() == null ? descriptor.getDefaultValue() : entry.getValue();
            if (value != null) {
                final ControllerServiceNode referencedNode = getRootControllerService(value);
                if (referencedNode != null) {
                    referencedNode.removeReference(service);
                }
            }
        }
    }
    rootControllerServices.remove(service.getIdentifier());
    getStateManagerProvider().onComponentRemoved(service.getIdentifier());
    ExtensionManager.removeInstanceClassLoader(service.getIdentifier());
    LOG.info("{} removed from Flow Controller", service, this);
}
Also used : StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) NarCloseable(org.apache.nifi.nar.NarCloseable) StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashMap(java.util.HashMap)

Example 3 with StandardConfigurationContext

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

the class StandardProcessGroup method removeControllerService.

@Override
public void removeControllerService(final ControllerServiceNode service) {
    boolean removed = false;
    writeLock.lock();
    try {
        final ControllerServiceNode existing = controllerServices.get(requireNonNull(service).getIdentifier());
        if (existing == null) {
            throw new IllegalStateException("ControllerService " + service.getIdentifier() + " is not a member of this Process Group");
        }
        service.verifyCanDelete();
        try (final NarCloseable x = NarCloseable.withComponentNarLoader(service.getControllerServiceImplementation().getClass(), service.getIdentifier())) {
            final ConfigurationContext configurationContext = new StandardConfigurationContext(service, controllerServiceProvider, null, variableRegistry);
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnRemoved.class, service.getControllerServiceImplementation(), configurationContext);
        }
        for (final Map.Entry<PropertyDescriptor, String> entry : service.getProperties().entrySet()) {
            final PropertyDescriptor descriptor = entry.getKey();
            if (descriptor.getControllerServiceDefinition() != null) {
                final String value = entry.getValue() == null ? descriptor.getDefaultValue() : entry.getValue();
                if (value != null) {
                    final ControllerServiceNode referencedNode = getControllerService(value);
                    if (referencedNode != null) {
                        referencedNode.removeReference(service);
                    }
                }
            }
        }
        controllerServices.remove(service.getIdentifier());
        onComponentModified();
        // For any component that references this Controller Service, find the component's Process Group
        // and notify the Process Group that a component has been modified. This way, we know to re-calculate
        // whether or not the Process Group has local modifications.
        service.getReferences().getReferencingComponents().stream().map(ConfiguredComponent::getProcessGroupIdentifier).filter(id -> !id.equals(getIdentifier())).forEach(groupId -> {
            final ProcessGroup descendant = findProcessGroup(groupId);
            if (descendant != null) {
                descendant.onComponentModified();
            }
        });
        flowController.getStateManagerProvider().onComponentRemoved(service.getIdentifier());
        removed = true;
        LOG.info("{} removed from {}", service, this);
    } finally {
        if (removed) {
            try {
                ExtensionManager.removeInstanceClassLoader(service.getIdentifier());
            } catch (Throwable t) {
            }
        }
        writeLock.unlock();
    }
}
Also used : OnRemoved(org.apache.nifi.annotation.lifecycle.OnRemoved) ConfigurationContext(org.apache.nifi.controller.ConfigurationContext) Size(org.apache.nifi.connectable.Size) FlowComparison(org.apache.nifi.registry.flow.diff.FlowComparison) StringUtils(org.apache.commons.lang3.StringUtils) ReflectionUtils(org.apache.nifi.util.ReflectionUtils) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) SecureRandom(java.security.SecureRandom) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) ComponentType(org.apache.nifi.registry.flow.ComponentType) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) SnippetUtils(org.apache.nifi.util.SnippetUtils) Map(java.util.Map) HashCodeBuilder(org.apache.commons.lang3.builder.HashCodeBuilder) RootGroupPort(org.apache.nifi.remote.RootGroupPort) Connectable(org.apache.nifi.connectable.Connectable) Connection(org.apache.nifi.connectable.Connection) Bundle(org.apache.nifi.registry.flow.Bundle) FlowFilePrioritizer(org.apache.nifi.flowfile.FlowFilePrioritizer) FlowDifferenceFilters(org.apache.nifi.util.FlowDifferenceFilters) VersionedFlowStatus(org.apache.nifi.registry.flow.VersionedFlowStatus) Set(java.util.Set) VersionedFlowCoordinates(org.apache.nifi.registry.flow.VersionedFlowCoordinates) VersionedRemoteGroupPort(org.apache.nifi.registry.flow.VersionedRemoteGroupPort) FlowController(org.apache.nifi.controller.FlowController) StandardCharsets(java.nio.charset.StandardCharsets) StateManagerProvider(org.apache.nifi.components.state.StateManagerProvider) Position(org.apache.nifi.connectable.Position) ScheduledState(org.apache.nifi.controller.ScheduledState) ControllerService(org.apache.nifi.controller.ControllerService) ExtensionManager(org.apache.nifi.nar.ExtensionManager) StandardVersionControlInformation(org.apache.nifi.registry.flow.StandardVersionControlInformation) Resource(org.apache.nifi.authorization.Resource) FlowComparator(org.apache.nifi.registry.flow.diff.FlowComparator) StaticDifferenceDescriptor(org.apache.nifi.registry.flow.diff.StaticDifferenceDescriptor) StandardComparableDataFlow(org.apache.nifi.registry.flow.diff.StandardComparableDataFlow) SiteToSiteTransportProtocol(org.apache.nifi.remote.protocol.SiteToSiteTransportProtocol) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ArrayList(java.util.ArrayList) Relationship(org.apache.nifi.processor.Relationship) ControllerServiceReference(org.apache.nifi.controller.service.ControllerServiceReference) ControllerServiceProvider(org.apache.nifi.controller.service.ControllerServiceProvider) VersionedLabel(org.apache.nifi.registry.flow.VersionedLabel) LinkedHashSet(java.util.LinkedHashSet) VersionedFlowState(org.apache.nifi.registry.flow.VersionedFlowState) EvolvingDifferenceDescriptor(org.apache.nifi.registry.flow.diff.EvolvingDifferenceDescriptor) ConfiguredComponent(org.apache.nifi.controller.ConfiguredComponent) Positionable(org.apache.nifi.connectable.Positionable) ExecutionNode(org.apache.nifi.scheduling.ExecutionNode) IOException(java.io.IOException) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) NiFiRegistryFlowMapper(org.apache.nifi.registry.flow.mapping.NiFiRegistryFlowMapper) Lock(java.util.concurrent.locks.Lock) NiFiProperties(org.apache.nifi.util.NiFiProperties) VariableImpact(org.apache.nifi.attribute.expression.language.VariableImpact) FlowFileQueue(org.apache.nifi.controller.queue.FlowFileQueue) ProcessorInstantiationException(org.apache.nifi.controller.exception.ProcessorInstantiationException) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate) URL(java.net.URL) ConnectableType(org.apache.nifi.connectable.ConnectableType) ConnectableComponent(org.apache.nifi.registry.flow.ConnectableComponent) VariableDescriptor(org.apache.nifi.registry.VariableDescriptor) LoggerFactory(org.slf4j.LoggerFactory) Port(org.apache.nifi.connectable.Port) StandardFlowComparator(org.apache.nifi.registry.flow.diff.StandardFlowComparator) Query(org.apache.nifi.attribute.expression.language.Query) ResourceType(org.apache.nifi.authorization.resource.ResourceType) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) SchedulingStrategy(org.apache.nifi.scheduling.SchedulingStrategy) VersionedPort(org.apache.nifi.registry.flow.VersionedPort) VersionedRemoteProcessGroup(org.apache.nifi.registry.flow.VersionedRemoteProcessGroup) StandardProcessScheduler(org.apache.nifi.controller.scheduling.StandardProcessScheduler) VersionedComponent(org.apache.nifi.registry.flow.VersionedComponent) DifferenceType(org.apache.nifi.registry.flow.diff.DifferenceType) VersionedConnection(org.apache.nifi.registry.flow.VersionedConnection) Template(org.apache.nifi.controller.Template) Label(org.apache.nifi.controller.label.Label) FlowRegistryClient(org.apache.nifi.registry.flow.FlowRegistryClient) OnShutdown(org.apache.nifi.annotation.lifecycle.OnShutdown) MutableVariableRegistry(org.apache.nifi.registry.variable.MutableVariableRegistry) Authorizable(org.apache.nifi.authorization.resource.Authorizable) UUID(java.util.UUID) ComponentLifeCycleException(org.apache.nifi.controller.exception.ComponentLifeCycleException) Snippet(org.apache.nifi.controller.Snippet) Collectors(java.util.stream.Collectors) ResourceFactory(org.apache.nifi.authorization.resource.ResourceFactory) Objects(java.util.Objects) List(java.util.List) BatchSize(org.apache.nifi.registry.flow.BatchSize) VersionedFunnel(org.apache.nifi.registry.flow.VersionedFunnel) ToStringBuilder(org.apache.commons.lang3.builder.ToStringBuilder) VersionControlInformation(org.apache.nifi.registry.flow.VersionControlInformation) Optional(java.util.Optional) LocalPort(org.apache.nifi.connectable.LocalPort) StandardProcessContext(org.apache.nifi.processor.StandardProcessContext) ProcessorNode(org.apache.nifi.controller.ProcessorNode) Revision(org.apache.nifi.web.Revision) Funnel(org.apache.nifi.connectable.Funnel) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) ToStringStyle(org.apache.commons.lang3.builder.ToStringStyle) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) FlowRegistry(org.apache.nifi.registry.flow.FlowRegistry) HashSet(java.util.HashSet) StringEncryptor(org.apache.nifi.encrypt.StringEncryptor) ComparableDataFlow(org.apache.nifi.registry.flow.diff.ComparableDataFlow) Objects.requireNonNull(java.util.Objects.requireNonNull) StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) NarCloseable(org.apache.nifi.nar.NarCloseable) LogLevel(org.apache.nifi.logging.LogLevel) VersionedProcessor(org.apache.nifi.registry.flow.VersionedProcessor) Logger(org.slf4j.Logger) StateManager(org.apache.nifi.components.state.StateManager) RemoteGroupPort(org.apache.nifi.remote.RemoteGroupPort) StandardRemoteProcessGroupPortDescriptor(org.apache.nifi.remote.StandardRemoteProcessGroupPortDescriptor) VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) VersionedControllerService(org.apache.nifi.registry.flow.VersionedControllerService) TimeUnit(java.util.concurrent.TimeUnit) ComponentVariableRegistry(org.apache.nifi.registry.ComponentVariableRegistry) FlowDifference(org.apache.nifi.registry.flow.diff.FlowDifference) VersionedPropertyDescriptor(org.apache.nifi.registry.flow.VersionedPropertyDescriptor) Collections(java.util.Collections) LogRepositoryFactory(org.apache.nifi.logging.LogRepositoryFactory) NarCloseable(org.apache.nifi.nar.NarCloseable) ConfigurationContext(org.apache.nifi.controller.ConfigurationContext) StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) VersionedPropertyDescriptor(org.apache.nifi.registry.flow.VersionedPropertyDescriptor) ConfiguredComponent(org.apache.nifi.controller.ConfiguredComponent) StandardConfigurationContext(org.apache.nifi.controller.service.StandardConfigurationContext) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) VersionedRemoteProcessGroup(org.apache.nifi.registry.flow.VersionedRemoteProcessGroup) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with StandardConfigurationContext

use of org.apache.nifi.controller.service.StandardConfigurationContext 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)

Aggregations

ControllerServiceNode (org.apache.nifi.controller.service.ControllerServiceNode)4 StandardConfigurationContext (org.apache.nifi.controller.service.StandardConfigurationContext)4 NarCloseable (org.apache.nifi.nar.NarCloseable)4 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 PropertyDescriptor (org.apache.nifi.components.PropertyDescriptor)2 URL (java.net.URL)1 StandardCharsets (java.nio.charset.StandardCharsets)1 SecureRandom (java.security.SecureRandom)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 Objects (java.util.Objects)1 Objects.requireNonNull (java.util.Objects.requireNonNull)1 Optional (java.util.Optional)1 Set (java.util.Set)1 UUID (java.util.UUID)1