org.apache.nifi.controller.service.ControllerServiceState Java Examples

The following examples show how to use org.apache.nifi.controller.service.ControllerServiceState. 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: StandardControllerServiceDAO.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyUpdateReferencingComponents(final String controllerServiceId, final ScheduledState scheduledState, final ControllerServiceState controllerServiceState) {
    final ControllerServiceNode controllerService = locateControllerService(controllerServiceId);

    if (controllerServiceState != null) {
        if (ControllerServiceState.ENABLED.equals(controllerServiceState)) {
            serviceProvider.verifyCanEnableReferencingServices(controllerService);
        } else {
            serviceProvider.verifyCanDisableReferencingServices(controllerService);
        }
    } else if (scheduledState != null) {
        if (ScheduledState.RUNNING.equals(scheduledState)) {
            serviceProvider.verifyCanScheduleReferencingComponents(controllerService);
        } else {
            serviceProvider.verifyCanStopReferencingComponents(controllerService);
        }
    }
}
 
Example #2
Source File: TestStandardProcessScheduler.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that service that is infinitely blocking in @OnEnabled can
 * still have DISABLE operation initiated. The service itself will be set to
 * DISABLING state at which point UI and all will know that such service can
 * not be transitioned any more into any other state until it finishes
 * enabling (which will never happen in our case thus should be addressed by
 * user). However, regardless of user's mistake NiFi will remain
 * functioning.
 */
@Test
public void validateNeverEnablingServiceCanStillBeDisabled() throws Exception {
    final StandardProcessScheduler scheduler = createScheduler();

    final ControllerServiceNode serviceNode = flowManager.createControllerService(LongEnablingService.class.getName(),
            "1", systemBundle.getBundleDetails().getCoordinate(), null, false, true);

    final LongEnablingService ts = (LongEnablingService) serviceNode.getControllerServiceImplementation();
    ts.setLimit(Long.MAX_VALUE);

    serviceNode.performValidation();
    scheduler.enableControllerService(serviceNode);

    assertTrue(serviceNode.isActive());
    final long maxTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
    while (ts.enableInvocationCount() != 1 && System.nanoTime() <= maxTime) {
        Thread.sleep(1L);
    }
    assertEquals(1, ts.enableInvocationCount());

    scheduler.disableControllerService(serviceNode);
    assertFalse(serviceNode.isActive());
    assertEquals(ControllerServiceState.DISABLING, serviceNode.getState());
    assertEquals(0, ts.disableInvocationCount());
}
 
Example #3
Source File: TestStandardProcessScheduler.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateDisablingOfTheFailedService() throws Exception {
    final StandardProcessScheduler scheduler = createScheduler();

    final ControllerServiceNode serviceNode = flowManager.createControllerService(FailingService.class.getName(),
            "1", systemBundle.getBundleDetails().getCoordinate(), null, false, true);
    serviceNode.performValidation();

    final Future<?> future = scheduler.enableControllerService(serviceNode);
    try {
        future.get();
    } catch (final Exception e) {
        // Expected behavior because the FailingService throws Exception when attempting to enable
    }

    scheduler.shutdown();

    /*
     * Because it was never disabled it will remain active since its
     * enabling is being retried. This may actually be a bug in the
     * scheduler since it probably has to shut down all components (disable
     * services, shut down processors etc) before shutting down itself
     */
    assertTrue(serviceNode.isActive());
    assertSame(serviceNode.getState(), ControllerServiceState.ENABLING);
}
 
Example #4
Source File: ComponentCountTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void countControllerServices(final Collection<ControllerServiceNode> services, final List<String> details) {
    final Map<String, Map<ControllerServiceState, Integer>> typeMap = new HashMap<>();

    for (final ControllerServiceNode serviceNode : services) {
        final String componentType = serviceNode.getComponentType();

        final ControllerServiceState serviceState = serviceNode.getState();
        final Map<ControllerServiceState, Integer> stateCounts = typeMap.computeIfAbsent(componentType, key -> new HashMap<>());
        final Integer count = stateCounts.computeIfAbsent(serviceState, key -> 0);
        stateCounts.put(serviceState, count + 1);
    }

    for (final Map.Entry<String, Map<ControllerServiceState, Integer>> typeEntry : typeMap.entrySet()) {
        final String type = typeEntry.getKey();
        final Map<ControllerServiceState, Integer> stateMap = typeEntry.getValue();

        final int total = stateMap.values().stream().mapToInt(Integer::intValue).sum();
        details.add(type + " : " + total + " total, " + stateMap.toString().toLowerCase());
    }

    if (typeMap.isEmpty()) {
        details.add("No Controller Services");
    }
}
 
Example #5
Source File: StandardFlowSerializer.java    From nifi with Apache License 2.0 6 votes vote down vote up
public void addControllerService(final Element element, final ControllerServiceNode serviceNode) {
    final Element serviceElement = element.getOwnerDocument().createElement("controllerService");
    addTextElement(serviceElement, "id", serviceNode.getIdentifier());
    addTextElement(serviceElement, "versionedComponentId", serviceNode.getVersionedComponentId());
    addTextElement(serviceElement, "name", serviceNode.getName());
    addTextElement(serviceElement, "comment", serviceNode.getComments());
    addTextElement(serviceElement, "class", serviceNode.getCanonicalClassName());

    addBundle(serviceElement, serviceNode.getBundleCoordinate());

    final ControllerServiceState state = serviceNode.getState();
    final boolean enabled = (state == ControllerServiceState.ENABLED || state == ControllerServiceState.ENABLING);
    addTextElement(serviceElement, "enabled", String.valueOf(enabled));

    addConfiguration(serviceElement, serviceNode.getRawPropertyValues(), serviceNode.getAnnotationData(), encryptor);

    element.appendChild(serviceElement);
}
 
Example #6
Source File: FlowFromDOMFactory.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static ControllerServiceDTO getControllerService(final Element element, final StringEncryptor encryptor, final FlowEncodingVersion flowEncodingVersion) {
    final ControllerServiceDTO dto = new ControllerServiceDTO();

    dto.setId(getString(element, "id"));
    dto.setVersionedComponentId(getString(element, "versionedComponentId"));
    dto.setName(getString(element, "name"));
    dto.setComments(getString(element, "comment"));
    dto.setType(getString(element, "class"));
    dto.setBundle(getBundle(DomUtils.getChild(element, "bundle")));

    final boolean enabled = getBoolean(element, "enabled");
    dto.setState(enabled ? ControllerServiceState.ENABLED.name() : ControllerServiceState.DISABLED.name());

    dto.setProperties(getProperties(element, encryptor, flowEncodingVersion));
    dto.setAnnotationData(getString(element, "annotationData"));

    return dto;
}
 
Example #7
Source File: StandardParameterContext.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void validateReferencingComponents(final String parameterName, final Parameter parameter, final String parameterAction) {
    for (final ProcessorNode procNode : parameterReferenceManager.getProcessorsReferencing(this, parameterName)) {
        if (procNode.isRunning()) {
            throw new IllegalStateException("Cannot " + parameterAction + " parameter '" + parameterName + "' because it is referenced by " + procNode + ", which is currently running");
        }

        if (parameter != null) {
            validateParameterSensitivity(parameter, procNode);
        }
    }

    for (final ControllerServiceNode serviceNode : parameterReferenceManager.getControllerServicesReferencing(this, parameterName)) {
        final ControllerServiceState serviceState = serviceNode.getState();
        if (serviceState != ControllerServiceState.DISABLED) {
            throw new IllegalStateException("Cannot " + parameterAction + " parameter '" + parameterName + "' because it is referenced by "
                + serviceNode + ", which currently has a state of " + serviceState);
        }

        if (parameter != null) {
            validateParameterSensitivity(parameter, serviceNode);
        }
    }
}
 
Example #8
Source File: ProcessGroupAuditor.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Audits the update of controller serivce state
 *
 * @param proceedingJoinPoint join point
 * @param groupId group id
 * @param state controller service state
 * @throws Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.ProcessGroupDAO+) && "
    + "execution(java.util.concurrent.Future<Void> activateControllerServices(String, org.apache.nifi.controller.service.ControllerServiceState, java.util.Collection<String>)) && "
    + "args(groupId, state, serviceIds)")
public Future<Void> activateControllerServicesAdvice(ProceedingJoinPoint proceedingJoinPoint, String groupId, ControllerServiceState state, Collection<String> serviceIds) throws Throwable {
    final Operation operation;

    final Future<Void> result = (Future<Void>) proceedingJoinPoint.proceed();

    // determine the service state
    if (ControllerServiceState.ENABLED.equals(state)) {
        operation = Operation.Enable;
    } else {
        operation = Operation.Disable;
    }

    saveUpdateAction(groupId, operation);

    return result;
}
 
Example #9
Source File: LocalComponentLifecycle.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Set<AffectedComponentEntity> activateControllerServices(final URI exampleUri, final String groupId, final Set<AffectedComponentEntity> services,
    final ControllerServiceState desiredState, final Pause pause, final InvalidComponentAction invalidComponentAction) throws LifecycleManagementException {

    final Map<String, Revision> serviceRevisions = services.stream()
        .collect(Collectors.toMap(AffectedComponentEntity::getId, entity -> revisionManager.getRevision(entity.getId())));

    final Map<String, AffectedComponentEntity> affectedServiceMap = services.stream()
        .collect(Collectors.toMap(AffectedComponentEntity::getId, Function.identity()));

    if (desiredState == ControllerServiceState.ENABLED) {
        enableControllerServices(groupId, serviceRevisions, affectedServiceMap, pause, invalidComponentAction);
    } else {
        disableControllerServices(groupId, serviceRevisions, affectedServiceMap, pause, invalidComponentAction);
    }

    return services.stream()
        .map(componentEntity -> serviceFacade.getControllerService(componentEntity.getId()))
        .map(dtoFactory::createAffectedComponentEntity)
        .collect(Collectors.toSet());
}
 
Example #10
Source File: StandardProcessGroupDAO.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyActivateControllerServices(final ControllerServiceState state, final Collection<String> serviceIds) {
    final FlowManager flowManager = flowController.getFlowManager();

    final Set<ControllerServiceNode> serviceNodes = serviceIds.stream()
        .map(flowManager::getControllerServiceNode)
        .collect(Collectors.toSet());

    for (final ControllerServiceNode serviceNode : serviceNodes) {
        if (state == ControllerServiceState.ENABLED) {
            serviceNode.verifyCanEnable(serviceNodes);
        } else {
            serviceNode.verifyCanDisable(serviceNodes);
        }
    }
}
 
Example #11
Source File: StandardParameterContextDAO.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyDelete(final String parameterContextId) {
    // Find all Process Groups that are bound to the Parameter Context
    final List<ProcessGroup> groupsReferencingParameterContext = getBoundProcessGroups(parameterContextId);

    // If any component is referencing a Parameter and is running/enabled then fail
    for (final ProcessGroup group : groupsReferencingParameterContext) {
        for (final ProcessorNode processor : group.getProcessors()) {
            if (processor.isReferencingParameter() && processor.isRunning()) {
                throw new IllegalStateException("Cannot delete Parameter Context with ID " + parameterContextId + " because it is in use by at least one Processor that is running");
            }
        }

        for (final ControllerServiceNode service : group.getControllerServices(false)) {
            if (service.isReferencingParameter() && service.getState() != ControllerServiceState.DISABLED) {
                throw new IllegalStateException("Cannot delete Parameter Context with ID " + parameterContextId + " because it is in use by at least one Controller Service that is enabled");
            }
        }
    }
}
 
Example #12
Source File: StandardParameterContextDAO.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyUpdate(final ParameterContextDTO parameterContextDto, final boolean verifyComponentStates) {
    verifyNoNamingConflict(parameterContextDto.getName(), parameterContextDto.getId());

    final ParameterContext currentContext = getParameterContext(parameterContextDto.getId());
    for (final ParameterEntity parameterEntity : parameterContextDto.getParameters()) {
        final ParameterDTO parameterDto = parameterEntity.getParameter();
        final String parameterName = parameterDto.getName();
        final ParameterReferenceManager referenceManager = currentContext.getParameterReferenceManager();

        for (final ProcessorNode processor : referenceManager.getProcessorsReferencing(currentContext, parameterName)) {
            verifyParameterUpdate(parameterDto, processor, currentContext.getName(), verifyComponentStates, processor.isRunning(), "Processor that is running");
        }

        for (final ControllerServiceNode serviceNode : referenceManager.getControllerServicesReferencing(currentContext, parameterName)) {
            verifyParameterUpdate(parameterDto, serviceNode, currentContext.getName(), verifyComponentStates,
                serviceNode.getState() != ControllerServiceState.DISABLED, "Controller Service that is enabled");
        }
    }
}
 
Example #13
Source File: StandardControllerServiceDAO.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Set<ComponentNode> updateControllerServiceReferencingComponents(
        final String controllerServiceId, final ScheduledState scheduledState, final ControllerServiceState controllerServiceState) {
    // get the controller service
    final ControllerServiceNode controllerService = locateControllerService(controllerServiceId);

    // this request is either acting upon referencing services or schedulable components
    if (controllerServiceState != null) {
        if (ControllerServiceState.ENABLED.equals(controllerServiceState)) {
            return serviceProvider.enableReferencingServices(controllerService);
        } else {
            return serviceProvider.disableReferencingServices(controllerService);
        }
    } else if (scheduledState != null) {
        if (ScheduledState.RUNNING.equals(scheduledState)) {
            return serviceProvider.scheduleReferencingComponents(controllerService);
        } else {
            return serviceProvider.unscheduleReferencingComponents(controllerService);
        }
    }

    return Collections.emptySet();
}
 
Example #14
Source File: ParameterContextResource.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void enableControllerServices(final Set<AffectedComponentEntity> controllerServices, final AsynchronousWebRequest<?, ?> asyncRequest, final ComponentLifecycle componentLifecycle,
                                      final URI uri) throws LifecycleManagementException, ResumeFlowException {
    if (logger.isDebugEnabled()) {
        logger.debug("Re-Enabling {} Controller Services: {}", controllerServices.size(), controllerServices);
    } else {
        logger.info("Re-Enabling {} Controller Services after having updated Parameter Context", controllerServices.size());
    }

    // Step 13. Re-enable all disabled controller services
    final CancellableTimedPause enableServicesPause = new CancellableTimedPause(250, Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    asyncRequest.setCancelCallback(enableServicesPause::cancel);
    final Set<AffectedComponentEntity> servicesToEnable = getUpdatedEntities(controllerServices);

    try {
        componentLifecycle.activateControllerServices(uri, "root", servicesToEnable, ControllerServiceState.ENABLED, enableServicesPause, InvalidComponentAction.SKIP);
        asyncRequest.markStepComplete();
    } catch (final IllegalStateException ise) {
        // Component Lifecycle will re-enable the Controller Services only if they are valid. If IllegalStateException gets thrown, we need to provide
        // a more intelligent error message as to exactly what happened, rather than indicate that the Parameter Context could not be updated.
        throw new ResumeFlowException("Failed to re-enable Controller Services because " + ise.getMessage(), ise);
    }
}
 
Example #15
Source File: TestStandardProcessScheduler.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that the service that is currently in ENABLING state can be
 * disabled and that its @OnDisabled operation will be invoked as soon as
 *
 * @OnEnable finishes.
 */
@Test
public void validateLongEnablingServiceCanStillBeDisabled() throws Exception {
    final ProcessScheduler scheduler = createScheduler();
    final StandardControllerServiceProvider provider = new StandardControllerServiceProvider(controller, scheduler, null, stateMgrProvider, variableRegistry, nifiProperties);
    final ControllerServiceNode serviceNode = provider.createControllerService(LongEnablingService.class.getName(),
            "1", false);
    final LongEnablingService ts = (LongEnablingService) serviceNode.getControllerServiceImplementation();
    ts.setLimit(3000);
    scheduler.enableControllerService(serviceNode);
    Thread.sleep(2000);
    assertTrue(serviceNode.isActive());
    assertEquals(1, ts.enableInvocationCount());

    Thread.sleep(500);
    scheduler.disableControllerService(serviceNode);
    assertFalse(serviceNode.isActive());
    assertEquals(ControllerServiceState.DISABLING, serviceNode.getState());
    assertEquals(0, ts.disableInvocationCount());
    // wait a bit. . . Enabling will finish and @OnDisabled will be invoked
    // automatically
    Thread.sleep(4000);
    assertEquals(ControllerServiceState.DISABLED, serviceNode.getState());
    assertEquals(1, ts.disableInvocationCount());
}
 
Example #16
Source File: TestStandardProcessScheduler.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that service that is infinitely blocking in @OnEnabled can
 * still have DISABLE operation initiated. The service itself will be set to
 * DISABLING state at which point UI and all will know that such service can
 * not be transitioned any more into any other state until it finishes
 * enabling (which will never happen in our case thus should be addressed by
 * user). However, regardless of user's mistake NiFi will remain
 * functioning.
 */
@Test
public void validateNeverEnablingServiceCanStillBeDisabled() throws Exception {
    final ProcessScheduler scheduler = createScheduler();
    final StandardControllerServiceProvider provider = new StandardControllerServiceProvider(controller, scheduler, null, stateMgrProvider, variableRegistry, nifiProperties);
    final ControllerServiceNode serviceNode = provider.createControllerService(LongEnablingService.class.getName(),
            "1", false);
    final LongEnablingService ts = (LongEnablingService) serviceNode.getControllerServiceImplementation();
    ts.setLimit(Long.MAX_VALUE);
    scheduler.enableControllerService(serviceNode);
    Thread.sleep(100);
    assertTrue(serviceNode.isActive());
    assertEquals(1, ts.enableInvocationCount());

    Thread.sleep(1000);
    scheduler.disableControllerService(serviceNode);
    assertFalse(serviceNode.isActive());
    assertEquals(ControllerServiceState.DISABLING, serviceNode.getState());
    assertEquals(0, ts.disableInvocationCount());
}
 
Example #17
Source File: TestStandardProcessScheduler.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateDisablingOfTheFailedService() throws Exception {
    final ProcessScheduler scheduler = createScheduler();
    final StandardControllerServiceProvider provider = new StandardControllerServiceProvider(controller, scheduler, null, stateMgrProvider, variableRegistry, nifiProperties);
    final ControllerServiceNode serviceNode = provider.createControllerService(FailingService.class.getName(),
            "1", false);
    scheduler.enableControllerService(serviceNode);
    Thread.sleep(1000);
    scheduler.shutdown();
    /*
     * Because it was never disabled it will remain active since its
     * enabling is being retried. This may actually be a bug in the
     * scheduler since it probably has to shut down all components (disable
     * services, shut down processors etc) before shutting down itself
     */
    assertTrue(serviceNode.isActive());
    assertTrue(serviceNode.getState() == ControllerServiceState.ENABLING);
}
 
Example #18
Source File: StandardControllerServiceDAO.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void verifyUpdateReferencingComponents(final String controllerServiceId, final ScheduledState scheduledState, final ControllerServiceState controllerServiceState) {
    final ControllerServiceNode controllerService = locateControllerService(controllerServiceId);

    if (controllerServiceState != null) {
        if (ControllerServiceState.ENABLED.equals(controllerServiceState)) {
            serviceProvider.verifyCanEnableReferencingServices(controllerService);
        } else {
            serviceProvider.verifyCanDisableReferencingServices(controllerService);
        }
    } else if (scheduledState != null) {
        if (ScheduledState.RUNNING.equals(scheduledState)) {
            serviceProvider.verifyCanScheduleReferencingComponents(controllerService);
        } else {
            serviceProvider.verifyCanStopReferencingComponents(controllerService);
        }
    }
}
 
Example #19
Source File: StandardControllerServiceDAO.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Set<ConfiguredComponent> updateControllerServiceReferencingComponents(
        final String controllerServiceId, final ScheduledState scheduledState, final ControllerServiceState controllerServiceState) {
    // get the controller service
    final ControllerServiceNode controllerService = locateControllerService(controllerServiceId);

    // this request is either acting upon referencing services or schedulable components
    if (controllerServiceState != null) {
        if (ControllerServiceState.ENABLED.equals(controllerServiceState)) {
            return serviceProvider.enableReferencingServices(controllerService);
        } else {
            return serviceProvider.disableReferencingServices(controllerService);
        }
    } else if (scheduledState != null) {
        if (ScheduledState.RUNNING.equals(scheduledState)) {
            return serviceProvider.scheduleReferencingComponents(controllerService);
        } else {
            return serviceProvider.unscheduleReferencingComponents(controllerService);
        }
    }

    return Collections.emptySet();
}
 
Example #20
Source File: StandardSchedulingContext.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void leaseControllerService(final String identifier) {
    final ControllerServiceNode serviceNode = serviceProvider.getControllerServiceNode(identifier);
    if (serviceNode == null) {
        throw new IllegalArgumentException("Cannot lease Controller Service because no Controller Service exists with identifier " + identifier);
    }

    if (serviceNode.getState() != ControllerServiceState.ENABLED) {
        throw new IllegalStateException("Cannot lease Controller Service because Controller Service " + serviceNode.getProxiedControllerService().getIdentifier() + " is not currently enabled");
    }

    if (!serviceNode.isValid()) {
        throw new IllegalStateException("Cannot lease Controller Service because Controller Service " + serviceNode.getProxiedControllerService().getIdentifier() + " is not currently valid");
    }

    serviceNode.addReference(processorNode);
}
 
Example #21
Source File: FlowFromDOMFactory.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static ControllerServiceDTO getControllerService(final Element element, final StringEncryptor encryptor) {
    final ControllerServiceDTO dto = new ControllerServiceDTO();

    dto.setId(getString(element, "id"));
    dto.setName(getString(element, "name"));
    dto.setComments(getString(element, "comment"));
    dto.setType(getString(element, "class"));

    final boolean enabled = getBoolean(element, "enabled");
    dto.setState(enabled ? ControllerServiceState.ENABLED.name() : ControllerServiceState.DISABLED.name());

    dto.setProperties(getProperties(element, encryptor));
    dto.setAnnotationData(getString(element, "annotationData"));

    return dto;
}
 
Example #22
Source File: StandardFlowSerializer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public void addControllerService(final Element element, final ControllerServiceNode serviceNode) {
    final Element serviceElement = element.getOwnerDocument().createElement("controllerService");
    addTextElement(serviceElement, "id", serviceNode.getIdentifier());
    addTextElement(serviceElement, "name", serviceNode.getName());
    addTextElement(serviceElement, "comment", serviceNode.getComments());
    addTextElement(serviceElement, "class", serviceNode.getCanonicalClassName());

    final ControllerServiceState state = serviceNode.getState();
    final boolean enabled = (state == ControllerServiceState.ENABLED || state == ControllerServiceState.ENABLING);
    addTextElement(serviceElement, "enabled", String.valueOf(enabled));

    addConfiguration(serviceElement, serviceNode.getProperties(), serviceNode.getAnnotationData(), encryptor);

    element.appendChild(serviceElement);
}
 
Example #23
Source File: LocalComponentLifecycle.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void disableControllerServices(final String processGroupId, final Map<String, Revision> serviceRevisions, final Map<String, AffectedComponentEntity> affectedServices, final Pause pause,
                                       final InvalidComponentAction invalidComponentAction) throws LifecycleManagementException {

    if (serviceRevisions.isEmpty()) {
        return;
    }

    logger.debug("Disabling Controller Services with ID's {} from Process Group {}", serviceRevisions.keySet(), processGroupId);

    serviceFacade.verifyActivateControllerServices(processGroupId, ControllerServiceState.DISABLED, affectedServices.keySet());
    serviceFacade.activateControllerServices(processGroupId, ControllerServiceState.DISABLED, serviceRevisions);
    waitForControllerServiceState(processGroupId, affectedServices, ControllerServiceState.DISABLED, pause, invalidComponentAction);
}
 
Example #24
Source File: LocalComponentLifecycle.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void enableControllerServices(final String processGroupId, final Map<String, Revision> serviceRevisions, final Map<String, AffectedComponentEntity> affectedServices, final Pause pause,
                                      final InvalidComponentAction invalidComponentAction) throws LifecycleManagementException {

    if (serviceRevisions.isEmpty()) {
        return;
    }

    logger.debug("Enabling Controller Services with ID's {} from Process Group {}", serviceRevisions.keySet(), processGroupId);

    waitForControllerServiceValidation(processGroupId, affectedServices, pause);

    serviceFacade.verifyActivateControllerServices(processGroupId, ControllerServiceState.ENABLED, affectedServices.keySet());
    serviceFacade.activateControllerServices(processGroupId, ControllerServiceState.ENABLED, serviceRevisions);
    waitForControllerServiceState(processGroupId, affectedServices, ControllerServiceState.ENABLED, pause, invalidComponentAction);
}
 
Example #25
Source File: StandardFlowSynchronizer.java    From nifi with Apache License 2.0 5 votes vote down vote up
private ControllerServiceState getFinalTransitionState(final ControllerServiceState state) {
    switch (state) {
        case DISABLED:
        case DISABLING:
            return ControllerServiceState.DISABLED;
        case ENABLED:
        case ENABLING:
            return ControllerServiceState.ENABLED;
        default:
            throw new AssertionError();
    }
}
 
Example #26
Source File: StandardValidationContext.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidationRequired(final ControllerService service) {
    // No need to validate services that are already enabled.
    final ControllerServiceState serviceState = controllerServiceProvider.getControllerServiceNode(service.getIdentifier()).getState();
    if (serviceState == ControllerServiceState.ENABLED || serviceState == ControllerServiceState.ENABLING) {
        return false;
    }

    return true;
}
 
Example #27
Source File: StandardProcessGroupDAO.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Future<Void> activateControllerServices(final String groupId, final ControllerServiceState state, final Collection<String> serviceIds) {
    final FlowManager flowManager = flowController.getFlowManager();
    final List<ControllerServiceNode> serviceNodes = serviceIds.stream()
        .map(flowManager::getControllerServiceNode)
        .collect(Collectors.toList());

    if (state == ControllerServiceState.ENABLED) {
        return flowController.getControllerServiceProvider().enableControllerServicesAsync(serviceNodes);
    } else {
        return flowController.getControllerServiceProvider().disableControllerServicesAsync(serviceNodes);
    }
}
 
Example #28
Source File: StandardControllerServiceDAO.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ControllerServiceNode updateControllerService(final ControllerServiceDTO controllerServiceDTO) {
    // get the controller service
    final ControllerServiceNode controllerService = locateControllerService(controllerServiceDTO.getId());

    // ensure we can perform the update
    verifyUpdate(controllerService, controllerServiceDTO);

    // perform the update
    configureControllerService(controllerService, controllerServiceDTO);

    // enable or disable as appropriate
    if (isNotNull(controllerServiceDTO.getState())) {
        final ControllerServiceState purposedControllerServiceState = ControllerServiceState.valueOf(controllerServiceDTO.getState());

        // only attempt an action if it is changing
        if (!purposedControllerServiceState.equals(controllerService.getState())) {
            if (ControllerServiceState.ENABLED.equals(purposedControllerServiceState)) {
                serviceProvider.enableControllerService(controllerService);
            } else if (ControllerServiceState.DISABLED.equals(purposedControllerServiceState)) {
                serviceProvider.disableControllerService(controllerService);
            }
        }
    }

    return controllerService;
}
 
Example #29
Source File: TestStandardProcessScheduler.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testDisableControllerServiceWithProcessorTryingToStartUsingIt() throws InterruptedException, ExecutionException {
    final String uuid = UUID.randomUUID().toString();
    final Processor proc = new ServiceReferencingProcessor();
    proc.initialize(new StandardProcessorInitializationContext(uuid, null, null, null, KerberosConfig.NOT_CONFIGURED));

    final ReloadComponent reloadComponent = Mockito.mock(ReloadComponent.class);

    final ControllerServiceNode service = flowManager.createControllerService(NoStartServiceImpl.class.getName(), "service",
            systemBundle.getBundleDetails().getCoordinate(), null, true, true);

    rootGroup.addControllerService(service);

    final LoggableComponent<Processor> loggableComponent = new LoggableComponent<>(proc, systemBundle.getBundleDetails().getCoordinate(), null);
    final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(serviceProvider, variableRegistry);
    final ProcessorNode procNode = new StandardProcessorNode(loggableComponent, uuid, validationContextFactory, scheduler,
        serviceProvider, new StandardComponentVariableRegistry(VariableRegistry.EMPTY_REGISTRY), reloadComponent, extensionManager, new SynchronousValidationTrigger());

    rootGroup.addProcessor(procNode);

    Map<String, String> procProps = new HashMap<>();
    procProps.put(ServiceReferencingProcessor.SERVICE_DESC.getName(), service.getIdentifier());
    procNode.setProperties(procProps);

    service.performValidation();
    scheduler.enableControllerService(service);

    procNode.performValidation();
    scheduler.startProcessor(procNode, true);

    Thread.sleep(25L);

    scheduler.stopProcessor(procNode);
    assertTrue(service.isActive());
    assertSame(service.getState(), ControllerServiceState.ENABLING);
    scheduler.disableControllerService(service).get();
    assertFalse(service.isActive());
    assertSame(service.getState(), ControllerServiceState.DISABLED);
}
 
Example #30
Source File: TestStandardProcessScheduler.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Validates that in multi threaded environment enabling service can still
 * be disabled. This test is set up in such way that disabling of the
 * service could be initiated by both disable and enable methods. In other
 * words it tests two conditions in
 * {@link StandardControllerServiceNode#disable(ScheduledExecutorService)}
 * where the disabling of the service can be initiated right there (if
 * ENABLED), or if service is still enabling its disabling will be deferred
 * to the logic in
 * {@link StandardControllerServiceNode#enable(ScheduledExecutorService, long)}
 * IN any even the resulting state of the service is DISABLED
 */
@Test
@Ignore
public void validateEnabledDisableMultiThread() throws Exception {
    final StandardProcessScheduler scheduler = createScheduler();
    final StandardControllerServiceProvider provider = new StandardControllerServiceProvider(controller, scheduler, null);
    final ExecutorService executor = Executors.newCachedThreadPool();
    for (int i = 0; i < 200; i++) {
        final ControllerServiceNode serviceNode = flowManager.createControllerService(RandomShortDelayEnablingService.class.getName(), "1",
                systemBundle.getBundleDetails().getCoordinate(), null, false, true);

        executor.execute(new Runnable() {
            @Override
            public void run() {
                scheduler.enableControllerService(serviceNode);
            }
        });
        Thread.sleep(10); // ensure that enable gets initiated before disable
        executor.execute(new Runnable() {
            @Override
            public void run() {
                scheduler.disableControllerService(serviceNode);
            }
        });
        Thread.sleep(100);
        assertFalse(serviceNode.isActive());
        assertEquals(ControllerServiceState.DISABLED, serviceNode.getState());
    }

    // need to sleep a while since we are emulating async invocations on
    // method that is also internally async
    Thread.sleep(500);
    executor.shutdown();
    executor.awaitTermination(5000, TimeUnit.MILLISECONDS);
}