Search in sources :

Example 91 with ComponentLog

use of org.apache.nifi.logging.ComponentLog in project nifi by apache.

the class StandardStateManager method getLogger.

private ComponentLog getLogger(final String componentId) {
    final LogRepository repo = LogRepositoryFactory.getRepository(componentId);
    final ComponentLog logger = (repo == null) ? null : repo.getLogger();
    if (repo == null || logger == null) {
        return new SimpleProcessLogger(componentId, this);
    }
    return logger;
}
Also used : LogRepository(org.apache.nifi.logging.LogRepository) SimpleProcessLogger(org.apache.nifi.processor.SimpleProcessLogger) ComponentLog(org.apache.nifi.logging.ComponentLog)

Example 92 with ComponentLog

use of org.apache.nifi.logging.ComponentLog in project nifi by apache.

the class StandardStateManagerProvider method createStateProvider.

private static StateProvider createStateProvider(final File configFile, final Scope scope, final NiFiProperties properties, final VariableRegistry variableRegistry) throws ConfigParseException, IOException {
    final String providerId;
    final String providerIdPropertyName;
    final String providerDescription;
    final String providerXmlElementName;
    final String oppositeScopeXmlElementName;
    switch(scope) {
        case CLUSTER:
            providerId = properties.getClusterStateProviderId();
            providerIdPropertyName = NiFiProperties.STATE_MANAGEMENT_CLUSTER_PROVIDER_ID;
            providerDescription = "Cluster State Provider";
            providerXmlElementName = "cluster-provider";
            oppositeScopeXmlElementName = "local-provider";
            break;
        case LOCAL:
            providerId = properties.getLocalStateProviderId();
            providerIdPropertyName = NiFiProperties.STATE_MANAGEMENT_LOCAL_PROVIDER_ID;
            providerDescription = "Local State Provider";
            providerXmlElementName = "local-provider";
            oppositeScopeXmlElementName = "cluster-provider";
            break;
        default:
            throw new AssertionError("Attempted to create State Provider for unknown Scope: " + scope);
    }
    if (!configFile.exists()) {
        throw new IllegalStateException("Cannot create " + providerDescription + " because the State Management Configuration File " + configFile + " does not exist");
    }
    if (!configFile.canRead()) {
        throw new IllegalStateException("Cannot create " + providerDescription + " because the State Management Configuration File " + configFile + " cannot be read");
    }
    if (providerId == null) {
        if (scope == Scope.CLUSTER) {
            throw new IllegalStateException("Cannot create Cluster State Provider because the '" + providerIdPropertyName + "' property is missing from the NiFi Properties file. In order to run NiFi in a cluster, the " + providerIdPropertyName + " property must be configured in nifi.properties");
        }
        throw new IllegalStateException("Cannot create " + providerDescription + " because the '" + providerIdPropertyName + "' property is missing from the NiFi Properties file");
    }
    if (providerId.trim().isEmpty()) {
        throw new IllegalStateException("Cannot create " + providerDescription + " because the '" + providerIdPropertyName + "' property in the NiFi Properties file has no value set. This is a required property and must reference the identifier of one of the " + providerXmlElementName + " elements in the State Management Configuration File (" + configFile + ")");
    }
    final StateManagerConfiguration config = StateManagerConfiguration.parse(configFile);
    final StateProviderConfiguration providerConfig = config.getStateProviderConfiguration(providerId);
    if (providerConfig == null) {
        throw new IllegalStateException("Cannot create " + providerDescription + " because the '" + providerIdPropertyName + "' property in the NiFi Properties file is set to '" + providerId + "', but there is no " + providerXmlElementName + " entry in the State Management Configuration File (" + configFile + ") with this id");
    }
    if (providerConfig.getScope() != scope) {
        throw new IllegalStateException("Cannot create " + providerDescription + " because the '" + providerIdPropertyName + "' property in the NiFi Properties file is set to '" + providerId + "', but this id is assigned to a " + oppositeScopeXmlElementName + " entry in the State Management Configuration File (" + configFile + "), rather than a " + providerXmlElementName + " entry");
    }
    final String providerClassName = providerConfig.getClassName();
    final StateProvider provider;
    try {
        provider = instantiateStateProvider(providerClassName);
    } catch (final Exception e) {
        throw new RuntimeException("Cannot create " + providerDescription + " of type " + providerClassName, e);
    }
    if (!ArrayUtils.contains(provider.getSupportedScopes(), scope)) {
        throw new RuntimeException("Cannot use " + providerDescription + " (" + providerClassName + ") as it only supports scope(s) " + ArrayUtils.toString(provider.getSupportedScopes()) + " but " + "instance" + " is configured to use scope " + scope);
    }
    // create variable registry
    final Map<PropertyDescriptor, PropertyValue> propertyMap = new HashMap<>();
    final Map<PropertyDescriptor, String> propertyStringMap = new HashMap<>();
    for (final PropertyDescriptor descriptor : provider.getPropertyDescriptors()) {
        propertyMap.put(descriptor, new StandardPropertyValue(descriptor.getDefaultValue(), null, variableRegistry));
        propertyStringMap.put(descriptor, descriptor.getDefaultValue());
    }
    for (final Map.Entry<String, String> entry : providerConfig.getProperties().entrySet()) {
        final PropertyDescriptor descriptor = provider.getPropertyDescriptor(entry.getKey());
        propertyStringMap.put(descriptor, entry.getValue());
        propertyMap.put(descriptor, new StandardPropertyValue(entry.getValue(), null, variableRegistry));
    }
    final SSLContext sslContext = SslContextFactory.createSslContext(properties, false);
    final ComponentLog logger = new SimpleProcessLogger(providerId, provider);
    final StateProviderInitializationContext initContext = new StandardStateProviderInitializationContext(providerId, propertyMap, sslContext, logger);
    synchronized (provider) {
        provider.initialize(initContext);
    }
    final ValidationContext validationContext = new StandardValidationContext(null, propertyStringMap, null, null, null, variableRegistry);
    final Collection<ValidationResult> results = provider.validate(validationContext);
    final StringBuilder validationFailures = new StringBuilder();
    int invalidCount = 0;
    for (final ValidationResult result : results) {
        if (!result.isValid()) {
            validationFailures.append(result.toString()).append("\n");
            invalidCount++;
        }
    }
    if (invalidCount > 0) {
        throw new IllegalStateException("Could not initialize State Providers because the " + providerDescription + " is not valid. The following " + invalidCount + " Validation Errors occurred:\n" + validationFailures.toString() + "\nPlease check the configuration of the " + providerDescription + " with ID [" + providerId.trim() + "] in the file " + configFile.getAbsolutePath());
    }
    return provider;
}
Also used : StandardStateProviderInitializationContext(org.apache.nifi.controller.state.StandardStateProviderInitializationContext) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) StandardPropertyValue(org.apache.nifi.attribute.expression.language.StandardPropertyValue) ValidationResult(org.apache.nifi.components.ValidationResult) SimpleProcessLogger(org.apache.nifi.processor.SimpleProcessLogger) StateProviderInitializationContext(org.apache.nifi.components.state.StateProviderInitializationContext) StandardStateProviderInitializationContext(org.apache.nifi.controller.state.StandardStateProviderInitializationContext) StandardValidationContext(org.apache.nifi.processor.StandardValidationContext) StateManagerConfiguration(org.apache.nifi.controller.state.config.StateManagerConfiguration) StateProviderConfiguration(org.apache.nifi.controller.state.config.StateProviderConfiguration) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) StateProvider(org.apache.nifi.components.state.StateProvider) PropertyValue(org.apache.nifi.components.PropertyValue) StandardPropertyValue(org.apache.nifi.attribute.expression.language.StandardPropertyValue) SSLContext(javax.net.ssl.SSLContext) ComponentLog(org.apache.nifi.logging.ComponentLog) IOException(java.io.IOException) ConfigParseException(org.apache.nifi.controller.state.ConfigParseException) ValidationContext(org.apache.nifi.components.ValidationContext) StandardValidationContext(org.apache.nifi.processor.StandardValidationContext) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) StateMap(org.apache.nifi.components.state.StateMap)

Example 93 with ComponentLog

use of org.apache.nifi.logging.ComponentLog 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 94 with ComponentLog

use of org.apache.nifi.logging.ComponentLog in project nifi by apache.

the class FlowController method instantiateReportingTask.

private LoggableComponent<ReportingTask> instantiateReportingTask(final String type, final String id, final BundleCoordinate bundleCoordinate, final Set<URL> additionalUrls) throws ReportingTaskInstantiationException {
    final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        final Bundle reportingTaskBundle = ExtensionManager.getBundle(bundleCoordinate);
        if (reportingTaskBundle == null) {
            throw new IllegalStateException("Unable to find bundle for coordinate " + bundleCoordinate.getCoordinate());
        }
        final ClassLoader detectedClassLoader = ExtensionManager.createInstanceClassLoader(type, id, reportingTaskBundle, additionalUrls);
        final Class<?> rawClass = Class.forName(type, false, detectedClassLoader);
        Thread.currentThread().setContextClassLoader(detectedClassLoader);
        final Class<? extends ReportingTask> reportingTaskClass = rawClass.asSubclass(ReportingTask.class);
        final Object reportingTaskObj = reportingTaskClass.newInstance();
        final ReportingTask reportingTask = reportingTaskClass.cast(reportingTaskObj);
        final ComponentLog componentLog = new SimpleProcessLogger(id, reportingTask);
        final TerminationAwareLogger terminationAwareLogger = new TerminationAwareLogger(componentLog);
        return new LoggableComponent<>(reportingTask, bundleCoordinate, terminationAwareLogger);
    } catch (final Exception e) {
        throw new ReportingTaskInstantiationException(type, e);
    } finally {
        if (ctxClassLoader != null) {
            Thread.currentThread().setContextClassLoader(ctxClassLoader);
        }
    }
}
Also used : Bundle(org.apache.nifi.bundle.Bundle) ComponentLog(org.apache.nifi.logging.ComponentLog) ConfigException(org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException) IOException(java.io.IOException) ProcessorInstantiationException(org.apache.nifi.controller.exception.ProcessorInstantiationException) ComponentLifeCycleException(org.apache.nifi.controller.exception.ComponentLifeCycleException) UnknownServiceAddressException(org.apache.nifi.cluster.protocol.UnknownServiceAddressException) FlowSerializationException(org.apache.nifi.controller.serialization.FlowSerializationException) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) InitializationException(org.apache.nifi.reporting.InitializationException) ReportingTaskInstantiationException(org.apache.nifi.controller.reporting.ReportingTaskInstantiationException) CommunicationsException(org.apache.nifi.controller.exception.CommunicationsException) FlowSynchronizationException(org.apache.nifi.controller.serialization.FlowSynchronizationException) ControllerServiceInstantiationException(org.apache.nifi.controller.exception.ControllerServiceInstantiationException) ReportingTaskInstantiationException(org.apache.nifi.controller.reporting.ReportingTaskInstantiationException) NarThreadContextClassLoader(org.apache.nifi.nar.NarThreadContextClassLoader) SimpleProcessLogger(org.apache.nifi.processor.SimpleProcessLogger) ReportingTask(org.apache.nifi.reporting.ReportingTask) GhostReportingTask(org.apache.nifi.reporting.GhostReportingTask)

Example 95 with ComponentLog

use of org.apache.nifi.logging.ComponentLog in project nifi by apache.

the class FlowController method instantiateProcessor.

private LoggableComponent<Processor> instantiateProcessor(final String type, final String identifier, final BundleCoordinate bundleCoordinate, final Set<URL> additionalUrls) throws ProcessorInstantiationException {
    final Bundle processorBundle = ExtensionManager.getBundle(bundleCoordinate);
    if (processorBundle == null) {
        throw new ProcessorInstantiationException("Unable to find bundle for coordinate " + bundleCoordinate.getCoordinate());
    }
    final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        final ClassLoader detectedClassLoaderForInstance = ExtensionManager.createInstanceClassLoader(type, identifier, processorBundle, additionalUrls);
        final Class<?> rawClass = Class.forName(type, true, detectedClassLoaderForInstance);
        Thread.currentThread().setContextClassLoader(detectedClassLoaderForInstance);
        final Class<? extends Processor> processorClass = rawClass.asSubclass(Processor.class);
        final Processor processor = processorClass.newInstance();
        final ComponentLog componentLogger = new SimpleProcessLogger(identifier, processor);
        final TerminationAwareLogger terminationAwareLogger = new TerminationAwareLogger(componentLogger);
        final ProcessorInitializationContext ctx = new StandardProcessorInitializationContext(identifier, terminationAwareLogger, this, this, nifiProperties);
        processor.initialize(ctx);
        LogRepositoryFactory.getRepository(identifier).setLogger(terminationAwareLogger);
        return new LoggableComponent<>(processor, bundleCoordinate, terminationAwareLogger);
    } catch (final Throwable t) {
        throw new ProcessorInstantiationException(type, t);
    } finally {
        if (ctxClassLoader != null) {
            Thread.currentThread().setContextClassLoader(ctxClassLoader);
        }
    }
}
Also used : GhostProcessor(org.apache.nifi.processor.GhostProcessor) Processor(org.apache.nifi.processor.Processor) Bundle(org.apache.nifi.bundle.Bundle) StandardProcessorInitializationContext(org.apache.nifi.processor.StandardProcessorInitializationContext) ComponentLog(org.apache.nifi.logging.ComponentLog) StandardProcessorInitializationContext(org.apache.nifi.processor.StandardProcessorInitializationContext) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) ProcessorInstantiationException(org.apache.nifi.controller.exception.ProcessorInstantiationException) NarThreadContextClassLoader(org.apache.nifi.nar.NarThreadContextClassLoader) SimpleProcessLogger(org.apache.nifi.processor.SimpleProcessLogger)

Aggregations

ComponentLog (org.apache.nifi.logging.ComponentLog)211 FlowFile (org.apache.nifi.flowfile.FlowFile)111 ProcessException (org.apache.nifi.processor.exception.ProcessException)95 IOException (java.io.IOException)94 HashMap (java.util.HashMap)51 Map (java.util.Map)47 InputStream (java.io.InputStream)46 ArrayList (java.util.ArrayList)44 PropertyDescriptor (org.apache.nifi.components.PropertyDescriptor)40 HashSet (java.util.HashSet)33 ProcessSession (org.apache.nifi.processor.ProcessSession)32 List (java.util.List)28 ProcessContext (org.apache.nifi.processor.ProcessContext)28 Relationship (org.apache.nifi.processor.Relationship)28 StopWatch (org.apache.nifi.util.StopWatch)28 OutputStream (java.io.OutputStream)27 InputStreamCallback (org.apache.nifi.processor.io.InputStreamCallback)27 Set (java.util.Set)23 Collections (java.util.Collections)21 AtomicReference (java.util.concurrent.atomic.AtomicReference)21