Java Code Examples for org.apache.nifi.components.PropertyDescriptor#getControllerServiceDefinition()

The following examples show how to use org.apache.nifi.components.PropertyDescriptor#getControllerServiceDefinition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SnippetUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
private Set<ControllerServiceDTO> getControllerServices(final Map<PropertyDescriptor, String> componentProperties) {
    final Set<ControllerServiceDTO> serviceDtos = new HashSet<>();

    for (final Map.Entry<PropertyDescriptor, String> entry : componentProperties.entrySet()) {
        final PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.getControllerServiceDefinition() != null) {
            final String controllerServiceId = entry.getValue();
            if (controllerServiceId != null) {
                final ControllerServiceNode serviceNode = flowController.getFlowManager().getControllerServiceNode(controllerServiceId);
                if (serviceNode != null) {
                    serviceDtos.add(dtoFactory.createControllerServiceDto(serviceNode));

                    final Set<ControllerServiceDTO> recursiveRefs = getControllerServices(serviceNode.getEffectivePropertyValues());
                    serviceDtos.addAll(recursiveRefs);
                }
            }
        }
    }

    return serviceDtos;
}
 
Example 2
Source File: SnippetUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private Set<ControllerServiceDTO> getControllerServices(final Map<PropertyDescriptor, String> componentProperties) {
    final Set<ControllerServiceDTO> serviceDtos = new HashSet<>();

    for (final Map.Entry<PropertyDescriptor, String> entry : componentProperties.entrySet()) {
        final PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.getControllerServiceDefinition() != null) {
            final String controllerServiceId = entry.getValue();
            if (controllerServiceId != null) {
                final ControllerServiceNode serviceNode = flowController.getControllerServiceNode(controllerServiceId);
                if (serviceNode != null) {
                    serviceDtos.add(dtoFactory.createControllerServiceDto(serviceNode));

                    final Set<ControllerServiceDTO> recursiveRefs = getControllerServices(serviceNode.getProperties());
                    serviceDtos.addAll(recursiveRefs);
                }
            }
        }
    }

    return serviceDtos;
}
 
Example 3
Source File: ExtensionManager.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
private static boolean checkControllerServiceReferenceEligibility(final ConfigurableComponent component, final ClassLoader classLoader) {
    // if the extension does not require instance classloading, its eligible
    final boolean requiresInstanceClassLoading = component.getClass().isAnnotationPresent(RequiresInstanceClassLoading.class);

    final Set<Class> cobundledApis = new HashSet<>();
    try (final NarCloseable closeable = NarCloseable.withComponentNarLoader(component.getClass().getClassLoader())) {
        final List<PropertyDescriptor> descriptors = component.getPropertyDescriptors();
        if (descriptors != null && !descriptors.isEmpty()) {
            for (final PropertyDescriptor descriptor : descriptors) {
                final Class<? extends ControllerService> serviceApi = descriptor.getControllerServiceDefinition();
                if (serviceApi != null && classLoader.equals(serviceApi.getClassLoader())) {
                    cobundledApis.add(serviceApi);
                }
            }
        }
    }

    if (!cobundledApis.isEmpty()) {
        logger.warn(String.format(
                "Component %s is bundled with its referenced Controller Service APIs %s. The service APIs should not be bundled with component implementations that reference it.",
                component.getClass().getName(), StringUtils.join(cobundledApis.stream().map(cls -> cls.getName()).collect(Collectors.toSet()), ", ")));
    }

    // the component is eligible when it does not require instance classloading or when the supporting APIs are bundled in a parent NAR
    return requiresInstanceClassLoading == false || cobundledApis.isEmpty();
}
 
Example 4
Source File: StandardControllerServiceNode.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public List<ControllerServiceNode> getRequiredControllerServices() {
    Set<ControllerServiceNode> requiredServices = new HashSet<>();
    for (Entry<PropertyDescriptor, String> entry : getEffectivePropertyValues().entrySet()) {
        PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.getControllerServiceDefinition() != null && entry.getValue() != null) {
            ControllerServiceNode requiredNode = serviceProvider.getControllerServiceNode(entry.getValue());
            requiredServices.add(requiredNode);
        }
    }
    return new ArrayList<>(requiredServices);
}
 
Example 5
Source File: StandardFlowManager.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void removeReportingTask(final ReportingTaskNode reportingTaskNode) {
    final ReportingTaskNode existing = allReportingTasks.get(reportingTaskNode.getIdentifier());
    if (existing == null || existing != reportingTaskNode) {
        throw new IllegalStateException("Reporting Task " + reportingTaskNode + " does not exist in this Flow");
    }

    reportingTaskNode.verifyCanDelete();

    final Class<?> taskClass = reportingTaskNode.getReportingTask().getClass();
    try (final NarCloseable x = NarCloseable.withComponentNarLoader(flowController.getExtensionManager(), taskClass, reportingTaskNode.getReportingTask().getIdentifier())) {
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnRemoved.class, reportingTaskNode.getReportingTask(), reportingTaskNode.getConfigurationContext());
    }

    for (final Map.Entry<PropertyDescriptor, String> entry : reportingTaskNode.getEffectivePropertyValues().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 serviceNode = flowController.getControllerServiceProvider().getControllerServiceNode(value);
                if (serviceNode != null) {
                    serviceNode.removeReference(reportingTaskNode, descriptor);
                }
            }
        }
    }

    allReportingTasks.remove(reportingTaskNode.getIdentifier());
    LogRepositoryFactory.removeRepository(reportingTaskNode.getIdentifier());
    processScheduler.onReportingTaskRemoved(reportingTaskNode);

    flowController.getExtensionManager().removeInstanceClassLoader(reportingTaskNode.getIdentifier());
}
 
Example 6
Source File: HtmlDocumentationWriter.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Interrogates a PropertyDescriptor to get a list of AllowableValues, if
 * there are none, nothing is written to the stream.
 *
 * @param xmlStreamWriter the stream writer to use
 * @param property the property to describe
 * @throws XMLStreamException thrown if there was a problem writing to the
 * XML Stream
 */
protected void writeValidValues(XMLStreamWriter xmlStreamWriter, PropertyDescriptor property)
        throws XMLStreamException {
    if (property.getAllowableValues() != null && property.getAllowableValues().size() > 0) {
        xmlStreamWriter.writeStartElement("ul");
        for (AllowableValue value : property.getAllowableValues()) {
            xmlStreamWriter.writeStartElement("li");
            xmlStreamWriter.writeCharacters(value.getDisplayName());

            if (value.getDescription() != null) {
                writeValidValueDescription(xmlStreamWriter, value.getDescription());
            }
            xmlStreamWriter.writeEndElement();

        }
        xmlStreamWriter.writeEndElement();
    } else if (property.getControllerServiceDefinition() != null) {
        Class<? extends ControllerService> controllerServiceClass = property.getControllerServiceDefinition();

        writeSimpleElement(xmlStreamWriter, "strong", "Controller Service API: ");
        xmlStreamWriter.writeEmptyElement("br");
        xmlStreamWriter.writeCharacters(controllerServiceClass.getSimpleName());

        final List<Class<? extends ControllerService>> implementationList = lookupControllerServiceImpls(controllerServiceClass);

        // Convert it into an array before proceeding
        Class<? extends ControllerService>[] implementations = implementationList.stream().toArray(Class[]::new);

        xmlStreamWriter.writeEmptyElement("br");
        if (implementations.length > 0) {
            final String title = implementations.length > 1 ? "Implementations: " : "Implementation: ";
            writeSimpleElement(xmlStreamWriter, "strong", title);
            iterateAndLinkComponents(xmlStreamWriter, implementations, null, "<br>", controllerServiceClass.getSimpleName());
        } else {
            xmlStreamWriter.writeCharacters("No implementations found.");
        }
    }
}
 
Example 7
Source File: AbstractComponentNode.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected final Collection<ValidationResult> validateReferencedControllerServices(final ValidationContext validationContext) {
    final Set<PropertyDescriptor> propertyDescriptors = validationContext.getProperties().keySet();
    if (propertyDescriptors == null) {
        return Collections.emptyList();
    }

    final Collection<ValidationResult> validationResults = new ArrayList<>();
    for (final PropertyDescriptor descriptor : propertyDescriptors) {
        if (descriptor.getControllerServiceDefinition() == null) {
            // skip properties that aren't for a controller service
            continue;
        }

        final String controllerServiceId = validationContext.getProperty(descriptor).getValue();
        if (controllerServiceId == null) {
            continue;
        }

        final ControllerServiceNode controllerServiceNode = getControllerServiceProvider().getControllerServiceNode(controllerServiceId);
        if (controllerServiceNode == null) {
            final ValidationResult result = createInvalidResult(controllerServiceId, descriptor.getDisplayName(),
                "Invalid Controller Service: " + controllerServiceId + " is not a valid Controller Service Identifier");

            validationResults.add(result);
            continue;
        }

        final ValidationResult apiResult = validateControllerServiceApi(descriptor, controllerServiceNode);
        if (apiResult != null) {
            validationResults.add(apiResult);
            continue;
        }

        if (!controllerServiceNode.isActive()) {
            validationResults.add(new DisabledServiceValidationResult(descriptor.getDisplayName(), controllerServiceId));
        }
    }

    return validationResults;
}
 
Example 8
Source File: StandardFlowManager.java    From nifi with Apache License 2.0 5 votes vote down vote up
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();

    final ExtensionManager extensionManager = flowController.getExtensionManager();
    final VariableRegistry variableRegistry = flowController.getVariableRegistry();

    try (final NarCloseable x = NarCloseable.withComponentNarLoader(extensionManager, service.getControllerServiceImplementation().getClass(), service.getIdentifier())) {
        final ConfigurationContext configurationContext = new StandardConfigurationContext(service, flowController.getControllerServiceProvider(), null, variableRegistry);
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnRemoved.class, service.getControllerServiceImplementation(), configurationContext);
    }

    for (final Map.Entry<PropertyDescriptor, String> entry : service.getEffectivePropertyValues().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, descriptor);
                }
            }
        }
    }

    rootControllerServices.remove(service.getIdentifier());
    flowController.getStateManagerProvider().onComponentRemoved(service.getIdentifier());

    extensionManager.removeInstanceClassLoader(service.getIdentifier());

    logger.info("{} removed from Flow Controller", service);
}
 
Example 9
Source File: AbstractComponentNode.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void setProperty(final String name, final PropertyConfiguration propertyConfiguration, final Function<PropertyDescriptor, PropertyConfiguration> valueToCompareFunction) {
    if (name == null || propertyConfiguration == null || propertyConfiguration.getRawValue() == null) {
        throw new IllegalArgumentException("Name or Value can not be null");
    }

    final PropertyDescriptor descriptor = getComponent().getPropertyDescriptor(name);
    final PropertyConfiguration propertyModComparisonValue = valueToCompareFunction.apply(descriptor);
    final PropertyConfiguration oldConfiguration = properties.put(descriptor, propertyConfiguration);
    final String effectiveValue = propertyConfiguration.getEffectiveValue(getParameterContext());

    if (!propertyConfiguration.equals(oldConfiguration)) {
        if (descriptor.getControllerServiceDefinition() != null) {
            if (oldConfiguration != null) {
                final ControllerServiceNode oldNode = serviceProvider.getControllerServiceNode(effectiveValue);
                if (oldNode != null) {
                    oldNode.removeReference(this, descriptor);
                }
            }

            final ControllerServiceNode newNode = serviceProvider.getControllerServiceNode(effectiveValue);
            if (newNode != null) {
                newNode.addReference(this, descriptor);
            }
        }
    }

    // In the case of a component "reload", we want to call onPropertyModified when the value is changed from the descriptor's default.
    // However, we do not want to update any controller service references because those are tied to the ComponentNode. We only want to
    // allow the newly created component's internal state to be updated.
    if (!propertyConfiguration.equals(propertyModComparisonValue)) {
        try {
            final String oldValue = oldConfiguration == null ? null : oldConfiguration.getEffectiveValue(getParameterContext());
            onPropertyModified(descriptor, oldValue, effectiveValue);
        } catch (final Exception e) {
            // nothing really to do here...
            logger.error("Failed to notify {} that property {} changed", this, descriptor, e);
        }
    }
}
 
Example 10
Source File: XmlDocumentationWriter.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void writeProperty(final PropertyDescriptor property, Map<String,ServiceAPI> propertyServices) throws IOException {
    writeStartElement("property");

    writeTextElement("name", property.getName());
    writeTextElement("displayName", property.getDisplayName());
    writeTextElement("description", property.getDescription());
    writeTextElement("defaultValue", property.getDefaultValue());

    if (property.getControllerServiceDefinition() != null) {
        writeStartElement("controllerServiceDefinition");

        final ServiceAPI serviceAPI = propertyServices.get(property.getName());
        if (serviceAPI != null) {
            writeTextElement("className", serviceAPI.getClassName());
            writeTextElement("groupId", serviceAPI.getGroupId());
            writeTextElement("artifactId", serviceAPI.getArtifactId());
            writeTextElement("version", serviceAPI.getVersion());
        } else {
            writeTextElement("className", property.getControllerServiceDefinition().getName());
            writeTextElement("groupId", "unknown");
            writeTextElement("artifactId", "unknown");
            writeTextElement("version", "unknown");
        }

        writeEndElement();
    }

    writeArray("allowableValues", property.getAllowableValues(), this::writeAllowableValue);
    writeBooleanElement("required", property.isRequired());
    writeBooleanElement("sensitive", property.isSensitive());
    writeBooleanElement("expressionLanguageSupported", property.isExpressionLanguageSupported());
    writeTextElement("expressionLanguageScope", property.getExpressionLanguageScope() == null ? null : property.getExpressionLanguageScope().name());
    writeBooleanElement("dynamicallyModifiesClasspath", property.isDynamicClasspathModifier());
    writeBooleanElement("dynamic", property.isDynamic());

    writeEndElement();
}
 
Example 11
Source File: AbstractConfiguredComponent.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
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 = component.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 {
            component.onPropertyModified(descriptor, oldValue, value);
        } catch (final Exception e) {
            // nothing really to do here...
        }
    }
}
 
Example 12
Source File: FlowController.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
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.removeInstanceClassLoaderIfExists(service.getIdentifier());

    LOG.info("{} removed from Flow Controller", service, this);
}
 
Example 13
Source File: FlowController.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void removeReportingTask(final ReportingTaskNode reportingTaskNode) {
    final ReportingTaskNode existing = reportingTasks.get(reportingTaskNode.getIdentifier());
    if (existing == null || existing != reportingTaskNode) {
        throw new IllegalStateException("Reporting Task " + reportingTaskNode + " does not exist in this Flow");
    }

    reportingTaskNode.verifyCanDelete();

    try (final NarCloseable x = NarCloseable.withComponentNarLoader(reportingTaskNode.getReportingTask().getClass(), reportingTaskNode.getReportingTask().getIdentifier())) {
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnRemoved.class, reportingTaskNode.getReportingTask(), reportingTaskNode.getConfigurationContext());
    }

    for (final Map.Entry<PropertyDescriptor, String> entry : reportingTaskNode.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 serviceNode = controllerServiceProvider.getControllerServiceNode(value);
                if (serviceNode != null) {
                    serviceNode.removeReference(reportingTaskNode);
                }
            }
        }
    }

    reportingTasks.remove(reportingTaskNode.getIdentifier());
    ExtensionManager.removeInstanceClassLoaderIfExists(reportingTaskNode.getIdentifier());
}
 
Example 14
Source File: StandardControllerServiceNode.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public List<ControllerServiceNode> getRequiredControllerServices() {
    Set<ControllerServiceNode> requiredServices = new HashSet<>();
    for (Entry<PropertyDescriptor, String> entry : getProperties().entrySet()) {
        PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.getControllerServiceDefinition() != null && entry.getValue() != null) {
            ControllerServiceNode requiredNode = serviceProvider.getControllerServiceNode(entry.getValue());
            requiredServices.add(requiredNode);
            requiredServices.addAll(requiredNode.getRequiredControllerServices());
        }
    }
    return new ArrayList<>(requiredServices);
}
 
Example 15
Source File: AuthorizeControllerServiceReference.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes the proposed properties for the specified authorizable.
 *
 * @param proposedProperties proposed properties
 * @param authorizable authorizable that may reference a controller service
 * @param authorizer authorizer
 * @param lookup lookup
 */
public static void authorizeControllerServiceReferences(final Map<String, String> proposedProperties, final ConfigurableComponentAuthorizable authorizable,
                                                        final Authorizer authorizer, final AuthorizableLookup lookup) {

    // only attempt to authorize if properties are changing
    if (proposedProperties != null) {
        final NiFiUser user = NiFiUserUtils.getNiFiUser();

        for (final Map.Entry<String, String> entry : proposedProperties.entrySet()) {
            final String propertyName = entry.getKey();
            final PropertyDescriptor propertyDescriptor = authorizable.getPropertyDescriptor(propertyName);

            // if this descriptor identifies a controller service
            if (propertyDescriptor.getControllerServiceDefinition() != null) {
                final String currentValue = authorizable.getValue(propertyDescriptor);
                final String proposedValue = entry.getValue();

                // if the value is changing
                if (!Objects.equals(currentValue, proposedValue)) {
                    // ensure access to the old service
                    if (currentValue != null) {
                        try {
                            final Authorizable currentServiceAuthorizable = lookup.getControllerService(currentValue).getAuthorizable();
                            currentServiceAuthorizable.authorize(authorizer, RequestAction.READ, user);
                        } catch (ResourceNotFoundException e) {
                            // ignore if the resource is not found, if currentValue was previously deleted, it should not stop assignment of proposedValue
                        }
                    }

                    // ensure access to the new service
                    if (proposedValue != null) {
                        final Authorizable newServiceAuthorizable = lookup.getControllerService(proposedValue).getAuthorizable();
                        newServiceAuthorizable.authorize(authorizer, RequestAction.READ, user);
                    }
                }
            }
        }
    }
}
 
Example 16
Source File: HtmlDocumentationWriter.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Interrogates a PropertyDescriptor to get a list of AllowableValues, if
 * there are none, nothing is written to the stream.
 *
 * @param xmlStreamWriter the stream writer to use
 * @param property the property to describe
 * @throws XMLStreamException thrown if there was a problem writing to the
 * XML Stream
 */
protected void writeValidValues(XMLStreamWriter xmlStreamWriter, PropertyDescriptor property)
        throws XMLStreamException {
    if (property.getAllowableValues() != null && property.getAllowableValues().size() > 0) {
        xmlStreamWriter.writeStartElement("ul");
        for (AllowableValue value : property.getAllowableValues()) {
            xmlStreamWriter.writeStartElement("li");
            xmlStreamWriter.writeCharacters(value.getDisplayName());

            if (value.getDescription() != null) {
                writeValidValueDescription(xmlStreamWriter, value.getDescription());
            }
            xmlStreamWriter.writeEndElement();

        }
        xmlStreamWriter.writeEndElement();
    } else if (property.getControllerServiceDefinition() != null) {
        Class<? extends ControllerService> controllerServiceClass = property.getControllerServiceDefinition();

        writeSimpleElement(xmlStreamWriter, "strong", "Controller Service API: ");
        xmlStreamWriter.writeEmptyElement("br");
        xmlStreamWriter.writeCharacters(controllerServiceClass.getSimpleName());

        final List<Class<? extends ControllerService>> implementations = lookupControllerServiceImpls(controllerServiceClass);
        xmlStreamWriter.writeEmptyElement("br");
        if (implementations.size() > 0) {
            final String title = implementations.size() > 1 ? "Implementations: " : "Implementation:";
            writeSimpleElement(xmlStreamWriter, "strong", title);
            for (int i = 0; i < implementations.size(); i++) {
                xmlStreamWriter.writeEmptyElement("br");
                writeLinkForComponent(xmlStreamWriter, implementations.get(i));
            }
        } else {
            xmlStreamWriter.writeCharacters("No implementations found.");
        }
    }
}
 
Example 17
Source File: AbstractConfiguredComponent.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the property and value for the given property name if a
 * descriptor and value exists for the given name. If the property is
 * optional its value might be reset to default or will be removed entirely
 * if was a dynamic property.
 *
 * @param name the property to remove
 * @return true if removed; false otherwise
 * @throws java.lang.IllegalArgumentException if the name is null
 */
private boolean removeProperty(final String name) {
    if (null == name) {
        throw new IllegalArgumentException("Name can not be null");
    }

    final PropertyDescriptor descriptor = component.getPropertyDescriptor(name);
    String value = null;
    if (!descriptor.isRequired() && (value = properties.remove(descriptor)) != null) {

        if (descriptor.getControllerServiceDefinition() != null) {
            if (value != null) {
                final ControllerServiceNode oldNode = serviceProvider.getControllerServiceNode(value);
                if (oldNode != null) {
                    oldNode.removeReference(this);
                }
            }
        }

        try {
            component.onPropertyModified(descriptor, value, null);
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
        }

        return true;
    }

    return false;
}
 
Example 18
Source File: StandardProcessGroup.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@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());
        flowController.getStateManagerProvider().onComponentRemoved(service.getIdentifier());

        removed = true;
        LOG.info("{} removed from {}", service, this);

    } finally {
        if (removed) {
            try {
                ExtensionManager.removeInstanceClassLoaderIfExists(service.getIdentifier());
            } catch (Throwable t) {
            }
        }
        writeLock.unlock();
    }
}
 
Example 19
Source File: AbstractComponentNode.java    From nifi with Apache License 2.0 4 votes vote down vote up
private ValidationResult validateControllerServiceApi(final PropertyDescriptor descriptor, final ControllerServiceNode controllerServiceNode) {
    final Class<? extends ControllerService> controllerServiceApiClass = descriptor.getControllerServiceDefinition();
    // If a processor accepts any service don't validate it.
    if (controllerServiceApiClass.equals(ControllerService.class)) {
        return null;
    }
    final ClassLoader controllerServiceApiClassLoader = controllerServiceApiClass.getClassLoader();
    final ExtensionManager extensionManager = serviceProvider.getExtensionManager();

    final String serviceId = controllerServiceNode.getIdentifier();
    final String propertyName = descriptor.getDisplayName();

    final Bundle controllerServiceApiBundle = extensionManager.getBundle(controllerServiceApiClassLoader);
    if (controllerServiceApiBundle == null) {
        return createInvalidResult(serviceId, propertyName, "Unable to find bundle for ControllerService API class " + controllerServiceApiClass.getCanonicalName());
    }
    final BundleCoordinate controllerServiceApiCoordinate = controllerServiceApiBundle.getBundleDetails().getCoordinate();

    final Bundle controllerServiceBundle = extensionManager.getBundle(controllerServiceNode.getBundleCoordinate());
    if (controllerServiceBundle == null) {
        return createInvalidResult(serviceId, propertyName, "Unable to find bundle for coordinate " + controllerServiceNode.getBundleCoordinate());
    }
    final BundleCoordinate controllerServiceCoordinate = controllerServiceBundle.getBundleDetails().getCoordinate();

    final boolean matchesApi = matchesApi(extensionManager, 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();

        return createInvalidResult(serviceId, propertyName, explanation);
    }

    return null;
}
 
Example 20
Source File: AuthorizeControllerServiceReference.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Authorizes the proposed properties for the specified authorizable.
 *
 * @param proposedProperties proposed properties
 * @param authorizable authorizable that may reference a controller service
 * @param authorizer authorizer
 * @param lookup lookup
 */
public static void authorizeControllerServiceReferences(final Map<String, String> proposedProperties, final ComponentAuthorizable authorizable,
                                                        final Authorizer authorizer, final AuthorizableLookup lookup) {

    // only attempt to authorize if properties are changing
    if (proposedProperties != null) {
        final NiFiUser user = NiFiUserUtils.getNiFiUser();

        for (final Map.Entry<String, String> entry : proposedProperties.entrySet()) {
            final String propertyName = entry.getKey();
            final PropertyDescriptor propertyDescriptor = authorizable.getPropertyDescriptor(propertyName);

            // if this descriptor identifies a controller service
            if (propertyDescriptor.getControllerServiceDefinition() != null) {
                final String currentValue = authorizable.getValue(propertyDescriptor);
                final String proposedValue = entry.getValue();

                // if the value is changing
                if (!Objects.equals(currentValue, proposedValue)) {
                    // ensure access to the old service
                    if (currentValue != null) {
                        try {
                            final Authorizable currentServiceAuthorizable = lookup.getControllerService(currentValue).getAuthorizable();
                            currentServiceAuthorizable.authorize(authorizer, RequestAction.READ, user);
                        } catch (ResourceNotFoundException e) {
                            // ignore if the resource is not found, if currentValue was previously deleted, it should not stop assignment of proposedValue
                        }
                    }

                    // ensure access to the new service
                    if (proposedValue != null) {
                        final ParameterParser parser = new ExpressionLanguageAgnosticParameterParser();
                        final ParameterTokenList tokenList = parser.parseTokens(proposedValue);
                        final boolean referencesParameter = !tokenList.toReferenceList().isEmpty();
                        if (referencesParameter) {
                            throw new IllegalArgumentException("The property '" + propertyDescriptor.getDisplayName() + "' cannot reference a Parameter because the property is a " +
                                "Controller Service reference. Allowing Controller Service references to make use of Parameters could result in security issues and a poor user experience. " +
                                "As a result, this is not allowed.");
                        }

                        final Authorizable newServiceAuthorizable = lookup.getControllerService(proposedValue).getAuthorizable();
                        newServiceAuthorizable.authorize(authorizer, RequestAction.READ, user);
                    }
                }
            }
        }
    }
}