Search in sources :

Example 1 with ScheduledState

use of org.apache.nifi.controller.ScheduledState in project nifi by apache.

the class ControllerServiceResource method updateControllerServiceReferences.

/**
 * Updates the references of the specified controller service.
 *
 * @param httpServletRequest     request
 * @param requestUpdateReferenceRequest The update request
 * @return A controllerServiceReferencingComponentsEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/references")
@ApiOperation(value = "Updates a controller services references", response = ControllerServiceReferencingComponentsEntity.class, authorizations = { @Authorization(value = "Write - /{component-type}/{uuid} - For each referencing component specified") })
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "Client could not be authenticated."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 404, message = "The specified resource could not be found."), @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response updateControllerServiceReferences(@Context final HttpServletRequest httpServletRequest, @ApiParam(value = "The controller service id.", required = true) @PathParam("id") final String id, @ApiParam(value = "The controller service request update request.", required = true) final UpdateControllerServiceReferenceRequestEntity requestUpdateReferenceRequest) {
    if (requestUpdateReferenceRequest.getId() == null) {
        throw new IllegalArgumentException("The controller service identifier must be specified.");
    }
    if (requestUpdateReferenceRequest.getReferencingComponentRevisions() == null) {
        throw new IllegalArgumentException("The controller service referencing components revisions must be specified.");
    }
    // parse the state to determine the desired action
    // need to consider controller service state first as it shares a state with
    // scheduled state (disabled) which is applicable for referencing services
    // but not referencing schedulable components
    ControllerServiceState requestControllerServiceState = null;
    try {
        requestControllerServiceState = ControllerServiceState.valueOf(requestUpdateReferenceRequest.getState());
    } catch (final IllegalArgumentException iae) {
    // ignore
    }
    ScheduledState requestScheduledState = null;
    try {
        requestScheduledState = ScheduledState.valueOf(requestUpdateReferenceRequest.getState());
    } catch (final IllegalArgumentException iae) {
    // ignore
    }
    // ensure an action has been specified
    if (requestScheduledState == null && requestControllerServiceState == null) {
        throw new IllegalArgumentException("Must specify the updated state. To update referencing Processors " + "and Reporting Tasks the state should be RUNNING or STOPPED. To update the referencing Controller Services the " + "state should be ENABLED or DISABLED.");
    }
    // ensure the controller service state is not ENABLING or DISABLING
    if (requestControllerServiceState != null && (ControllerServiceState.ENABLING.equals(requestControllerServiceState) || ControllerServiceState.DISABLING.equals(requestControllerServiceState))) {
        throw new IllegalArgumentException("Cannot set the referencing services to ENABLING or DISABLING");
    }
    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestUpdateReferenceRequest);
    }
    // convert the referencing revisions
    final Map<String, Revision> requestReferencingRevisions = requestUpdateReferenceRequest.getReferencingComponentRevisions().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> {
        final RevisionDTO rev = e.getValue();
        return new Revision(rev.getVersion(), rev.getClientId(), e.getKey());
    }));
    final Set<Revision> requestRevisions = new HashSet<>(requestReferencingRevisions.values());
    final ScheduledState verifyScheduledState = requestScheduledState;
    final ControllerServiceState verifyControllerServiceState = requestControllerServiceState;
    return withWriteLock(serviceFacade, requestUpdateReferenceRequest, requestRevisions, lookup -> {
        requestReferencingRevisions.entrySet().stream().forEach(e -> {
            final Authorizable controllerService = lookup.getControllerServiceReferencingComponent(id, e.getKey());
            controllerService.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        });
    }, () -> serviceFacade.verifyUpdateControllerServiceReferencingComponents(requestUpdateReferenceRequest.getId(), verifyScheduledState, verifyControllerServiceState), (revisions, updateReferenceRequest) -> {
        ScheduledState scheduledState = null;
        try {
            scheduledState = ScheduledState.valueOf(updateReferenceRequest.getState());
        } catch (final IllegalArgumentException e) {
        // ignore
        }
        ControllerServiceState controllerServiceState = null;
        try {
            controllerServiceState = ControllerServiceState.valueOf(updateReferenceRequest.getState());
        } catch (final IllegalArgumentException iae) {
        // ignore
        }
        final Map<String, Revision> referencingRevisions = updateReferenceRequest.getReferencingComponentRevisions().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> {
            final RevisionDTO rev = e.getValue();
            return new Revision(rev.getVersion(), rev.getClientId(), e.getKey());
        }));
        // update the controller service references
        final ControllerServiceReferencingComponentsEntity entity = serviceFacade.updateControllerServiceReferencingComponents(referencingRevisions, updateReferenceRequest.getId(), scheduledState, controllerServiceState);
        return generateOkResponse(entity).build();
    });
}
Also used : Produces(javax.ws.rs.Produces) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) BundleDTO(org.apache.nifi.web.api.dto.BundleDTO) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) StringUtils(org.apache.commons.lang3.StringUtils) ClientIdParameter(org.apache.nifi.web.api.request.ClientIdParameter) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) AuthorizeControllerServiceReference(org.apache.nifi.authorization.AuthorizeControllerServiceReference) PropertyDescriptorDTO(org.apache.nifi.web.api.dto.PropertyDescriptorDTO) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) UiExtension(org.apache.nifi.ui.extension.UiExtension) DefaultValue(javax.ws.rs.DefaultValue) UiExtensionType(org.apache.nifi.web.UiExtensionType) DELETE(javax.ws.rs.DELETE) ControllerServiceReferencingComponentsEntity(org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentsEntity) Context(javax.ws.rs.core.Context) Authorizable(org.apache.nifi.authorization.resource.Authorizable) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) Set(java.util.Set) LongParameter(org.apache.nifi.web.api.request.LongParameter) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) ScheduledState(org.apache.nifi.controller.ScheduledState) UiExtensionMapping(org.apache.nifi.ui.extension.UiExtensionMapping) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) PathParam(javax.ws.rs.PathParam) Revision(org.apache.nifi.web.Revision) GET(javax.ws.rs.GET) ControllerServiceEntity(org.apache.nifi.web.api.entity.ControllerServiceEntity) PropertyDescriptorEntity(org.apache.nifi.web.api.entity.PropertyDescriptorEntity) ApiResponses(io.swagger.annotations.ApiResponses) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) HttpMethod(javax.ws.rs.HttpMethod) HashSet(java.util.HashSet) HttpServletRequest(javax.servlet.http.HttpServletRequest) UpdateControllerServiceReferenceRequestEntity(org.apache.nifi.web.api.entity.UpdateControllerServiceReferenceRequestEntity) Api(io.swagger.annotations.Api) NiFiServiceFacade(org.apache.nifi.web.NiFiServiceFacade) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) RequestAction(org.apache.nifi.authorization.RequestAction) Authorizer(org.apache.nifi.authorization.Authorizer) ApiResponse(io.swagger.annotations.ApiResponse) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) ComponentStateDTO(org.apache.nifi.web.api.dto.ComponentStateDTO) ComponentStateEntity(org.apache.nifi.web.api.entity.ComponentStateEntity) ServletContext(javax.servlet.ServletContext) PUT(javax.ws.rs.PUT) Authorization(io.swagger.annotations.Authorization) ControllerServiceReferencingComponentsEntity(org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentsEntity) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) Revision(org.apache.nifi.web.Revision) ScheduledState(org.apache.nifi.controller.ScheduledState) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) Authorizable(org.apache.nifi.authorization.resource.Authorizable) Map(java.util.Map) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Example 2 with ScheduledState

use of org.apache.nifi.controller.ScheduledState in project nifi by apache.

the class ProcessGroupResource method scheduleProcessors.

private void scheduleProcessors(final String groupId, final URI originalUri, final VariableRegistryUpdateRequest updateRequest, final Pause pause, final Collection<AffectedComponentDTO> affectedProcessors, final ScheduledState desiredState, final VariableRegistryUpdateStep updateStep) throws InterruptedException {
    final Set<String> affectedProcessorIds = affectedProcessors.stream().map(component -> component.getId()).collect(Collectors.toSet());
    final Map<String, Revision> processorRevisionMap = getRevisions(groupId, affectedProcessorIds);
    final Map<String, RevisionDTO> processorRevisionDtoMap = processorRevisionMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> dtoFactory.createRevisionDTO(entry.getValue())));
    final ScheduleComponentsEntity scheduleProcessorsEntity = new ScheduleComponentsEntity();
    scheduleProcessorsEntity.setComponents(processorRevisionDtoMap);
    scheduleProcessorsEntity.setId(groupId);
    scheduleProcessorsEntity.setState(desiredState.name());
    URI scheduleGroupUri;
    try {
        scheduleGroupUri = new URI(originalUri.getScheme(), originalUri.getUserInfo(), originalUri.getHost(), originalUri.getPort(), "/nifi-api/flow/process-groups/" + groupId, null, originalUri.getFragment());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    final Map<String, String> headers = new HashMap<>();
    headers.put("content-type", MediaType.APPLICATION_JSON);
    // Determine whether we should replicate only to the cluster coordinator, or if we should replicate directly to the cluster nodes themselves.
    final NodeResponse clusterResponse;
    if (getReplicationTarget() == ReplicationTarget.CLUSTER_NODES) {
        clusterResponse = getRequestReplicator().replicate(HttpMethod.PUT, scheduleGroupUri, scheduleProcessorsEntity, headers).awaitMergedResponse();
    } else {
        clusterResponse = getRequestReplicator().forwardToCoordinator(getClusterCoordinatorNode(), HttpMethod.PUT, scheduleGroupUri, scheduleProcessorsEntity, headers).awaitMergedResponse();
    }
    final int stopProcessorStatus = clusterResponse.getStatus();
    if (stopProcessorStatus != Status.OK.getStatusCode()) {
        updateRequest.getStopProcessorsStep().setFailureReason("Failed while " + updateStep.getDescription());
        updateStep.setComplete(true);
        updateRequest.setFailureReason("Failed while " + updateStep.getDescription());
        return;
    }
    updateRequest.setLastUpdated(new Date());
    final boolean processorsTransitioned = waitForProcessorStatus(originalUri, groupId, affectedProcessorIds, desiredState, updateRequest, pause);
    updateStep.setComplete(true);
    if (!processorsTransitioned) {
        updateStep.setFailureReason("Failed while " + updateStep.getDescription());
        updateRequest.setComplete(true);
        updateRequest.setFailureReason("Failed while " + updateStep.getDescription());
    }
}
Also used : FunnelsEntity(org.apache.nifi.web.api.entity.FunnelsEntity) Produces(javax.ws.rs.Produces) InstantiateTemplateRequestEntity(org.apache.nifi.web.api.entity.InstantiateTemplateRequestEntity) ApiParam(io.swagger.annotations.ApiParam) SiteToSiteRestApiClient(org.apache.nifi.remote.util.SiteToSiteRestApiClient) ConnectionDTO(org.apache.nifi.web.api.dto.ConnectionDTO) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) StringUtils(org.apache.commons.lang3.StringUtils) ClientIdParameter(org.apache.nifi.web.api.request.ClientIdParameter) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) AuthorizeAccess(org.apache.nifi.authorization.AuthorizeAccess) VariableRegistryUpdateStep(org.apache.nifi.registry.variable.VariableRegistryUpdateStep) PositionDTO(org.apache.nifi.web.api.dto.PositionDTO) MediaType(javax.ws.rs.core.MediaType) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) Map(java.util.Map) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) UriBuilder(javax.ws.rs.core.UriBuilder) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ConnectionsEntity(org.apache.nifi.web.api.entity.ConnectionsEntity) FunnelEntity(org.apache.nifi.web.api.entity.FunnelEntity) VariableRegistryUpdateRequest(org.apache.nifi.registry.variable.VariableRegistryUpdateRequest) ControllerServicesEntity(org.apache.nifi.web.api.entity.ControllerServicesEntity) Set(java.util.Set) InputPortsEntity(org.apache.nifi.web.api.entity.InputPortsEntity) Executors(java.util.concurrent.Executors) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) FormDataParam(org.glassfish.jersey.media.multipart.FormDataParam) ProcessGroupsEntity(org.apache.nifi.web.api.entity.ProcessGroupsEntity) FlowComparisonEntity(org.apache.nifi.web.api.entity.FlowComparisonEntity) ScheduledState(org.apache.nifi.controller.ScheduledState) LabelsEntity(org.apache.nifi.web.api.entity.LabelsEntity) UriInfo(javax.ws.rs.core.UriInfo) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) DtoFactory(org.apache.nifi.web.api.dto.DtoFactory) Entity(org.apache.nifi.web.api.entity.Entity) GET(javax.ws.rs.GET) ControllerServiceEntity(org.apache.nifi.web.api.entity.ControllerServiceEntity) ConfigurableComponent(org.apache.nifi.components.ConfigurableComponent) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) HttpMethod(javax.ws.rs.HttpMethod) HttpServletRequest(javax.servlet.http.HttpServletRequest) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) NiFiUserDetails(org.apache.nifi.authorization.user.NiFiUserDetails) Api(io.swagger.annotations.Api) VariableRegistryDTO(org.apache.nifi.web.api.dto.VariableRegistryDTO) FlowDTO(org.apache.nifi.web.api.dto.flow.FlowDTO) VersionedFlowState(org.apache.nifi.registry.flow.VersionedFlowState) NiFiServiceFacade(org.apache.nifi.web.NiFiServiceFacade) AuthorizableLookup(org.apache.nifi.authorization.AuthorizableLookup) RequestAction(org.apache.nifi.authorization.RequestAction) FlowEncodingVersion(org.apache.nifi.controller.serialization.FlowEncodingVersion) JAXBElement(javax.xml.bind.JAXBElement) RemoteProcessGroupsEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupsEntity) IOException(java.io.IOException) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) Authorizer(org.apache.nifi.authorization.Authorizer) ApiResponse(io.swagger.annotations.ApiResponse) FlowEntity(org.apache.nifi.web.api.entity.FlowEntity) AffectedComponentEntity(org.apache.nifi.web.api.entity.AffectedComponentEntity) OutputPortsEntity(org.apache.nifi.web.api.entity.OutputPortsEntity) ScheduleComponentsEntity(org.apache.nifi.web.api.entity.ScheduleComponentsEntity) XmlUtils(org.apache.nifi.security.xml.XmlUtils) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate) ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) Date(java.util.Date) ConnectableType(org.apache.nifi.connectable.ConnectableType) ProcessorStatusDTO(org.apache.nifi.web.api.dto.status.ProcessorStatusDTO) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) BundleDTO(org.apache.nifi.web.api.dto.BundleDTO) ApiOperation(io.swagger.annotations.ApiOperation) AuthorizeControllerServiceReference(org.apache.nifi.authorization.AuthorizeControllerServiceReference) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) ActivateControllerServicesEntity(org.apache.nifi.web.api.entity.ActivateControllerServicesEntity) XMLStreamReader(javax.xml.stream.XMLStreamReader) DefaultValue(javax.ws.rs.DefaultValue) URI(java.net.URI) ThreadFactory(java.util.concurrent.ThreadFactory) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Authorizable(org.apache.nifi.authorization.resource.Authorizable) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) ApiImplicitParam(io.swagger.annotations.ApiImplicitParam) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SnippetAuthorizable(org.apache.nifi.authorization.SnippetAuthorizable) UUID(java.util.UUID) BundleUtils(org.apache.nifi.util.BundleUtils) PortEntity(org.apache.nifi.web.api.entity.PortEntity) LongParameter(org.apache.nifi.web.api.request.LongParameter) JAXBException(javax.xml.bind.JAXBException) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) ProcessGroupEntity(org.apache.nifi.web.api.entity.ProcessGroupEntity) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) CopySnippetRequestEntity(org.apache.nifi.web.api.entity.CopySnippetRequestEntity) Authentication(org.springframework.security.core.Authentication) Pause(org.apache.nifi.web.util.Pause) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) PathParam(javax.ws.rs.PathParam) Bucket(org.apache.nifi.registry.bucket.Bucket) Revision(org.apache.nifi.web.Revision) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses) Function(java.util.function.Function) AffectedComponentDTO(org.apache.nifi.web.api.dto.AffectedComponentDTO) ConcurrentMap(java.util.concurrent.ConcurrentMap) FlowRegistryUtils(org.apache.nifi.registry.flow.FlowRegistryUtils) CreateTemplateRequestEntity(org.apache.nifi.web.api.entity.CreateTemplateRequestEntity) VersionControlInformationDTO(org.apache.nifi.web.api.dto.VersionControlInformationDTO) VariableRegistryUpdateRequestEntity(org.apache.nifi.web.api.entity.VariableRegistryUpdateRequestEntity) NiFiAuthenticationToken(org.apache.nifi.web.security.token.NiFiAuthenticationToken) Status(javax.ws.rs.core.Response.Status) JAXBContext(javax.xml.bind.JAXBContext) ExecutorService(java.util.concurrent.ExecutorService) Unmarshaller(javax.xml.bind.Unmarshaller) TemplateContentsAuthorizable(org.apache.nifi.authorization.TemplateContentsAuthorizable) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ProcessorsEntity(org.apache.nifi.web.api.entity.ProcessorsEntity) VariableRegistryEntity(org.apache.nifi.web.api.entity.VariableRegistryEntity) VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) LabelEntity(org.apache.nifi.web.api.entity.LabelEntity) ConnectionEntity(org.apache.nifi.web.api.entity.ConnectionEntity) ProcessGroupAuthorizable(org.apache.nifi.authorization.ProcessGroupAuthorizable) RemoteProcessGroupEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupEntity) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) PUT(javax.ws.rs.PUT) Authorization(io.swagger.annotations.Authorization) Collections(java.util.Collections) InputStream(java.io.InputStream) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) ScheduleComponentsEntity(org.apache.nifi.web.api.entity.ScheduleComponentsEntity) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) Date(java.util.Date) Revision(org.apache.nifi.web.Revision) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 3 with ScheduledState

use of org.apache.nifi.controller.ScheduledState in project nifi by apache.

the class ProcessGroupResource method isProcessorActionComplete.

private boolean isProcessorActionComplete(final Set<ProcessorEntity> processorEntities, final VariableRegistryUpdateRequest updateRequest, final Set<String> processorIds, final ScheduledState desiredState) {
    final String desiredStateName = desiredState.name();
    // update the affected processors
    processorEntities.stream().filter(entity -> updateRequest.getAffectedComponents().containsKey(entity.getId())).forEach(entity -> {
        final AffectedComponentEntity affectedComponentEntity = updateRequest.getAffectedComponents().get(entity.getId());
        affectedComponentEntity.setRevision(entity.getRevision());
        // only consider update this component if the user had permissions to it
        if (Boolean.TRUE.equals(affectedComponentEntity.getPermissions().getCanRead())) {
            final AffectedComponentDTO affectedComponent = affectedComponentEntity.getComponent();
            affectedComponent.setState(entity.getStatus().getAggregateSnapshot().getRunStatus());
            affectedComponent.setActiveThreadCount(entity.getStatus().getAggregateSnapshot().getActiveThreadCount());
            if (Boolean.TRUE.equals(entity.getPermissions().getCanRead())) {
                affectedComponent.setValidationErrors(entity.getComponent().getValidationErrors());
            }
        }
    });
    final boolean allProcessorsMatch = processorEntities.stream().filter(entity -> processorIds.contains(entity.getId())).allMatch(entity -> {
        final ProcessorStatusDTO status = entity.getStatus();
        final String runStatus = status.getAggregateSnapshot().getRunStatus();
        final boolean stateMatches = desiredStateName.equalsIgnoreCase(runStatus);
        if (!stateMatches) {
            return false;
        }
        if (desiredState == ScheduledState.STOPPED && status.getAggregateSnapshot().getActiveThreadCount() != 0) {
            return false;
        }
        return true;
    });
    if (!allProcessorsMatch) {
        return false;
    }
    return true;
}
Also used : FunnelsEntity(org.apache.nifi.web.api.entity.FunnelsEntity) Produces(javax.ws.rs.Produces) InstantiateTemplateRequestEntity(org.apache.nifi.web.api.entity.InstantiateTemplateRequestEntity) ApiParam(io.swagger.annotations.ApiParam) SiteToSiteRestApiClient(org.apache.nifi.remote.util.SiteToSiteRestApiClient) ConnectionDTO(org.apache.nifi.web.api.dto.ConnectionDTO) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) StringUtils(org.apache.commons.lang3.StringUtils) ClientIdParameter(org.apache.nifi.web.api.request.ClientIdParameter) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) AuthorizeAccess(org.apache.nifi.authorization.AuthorizeAccess) VariableRegistryUpdateStep(org.apache.nifi.registry.variable.VariableRegistryUpdateStep) PositionDTO(org.apache.nifi.web.api.dto.PositionDTO) MediaType(javax.ws.rs.core.MediaType) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) Map(java.util.Map) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) UriBuilder(javax.ws.rs.core.UriBuilder) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ConnectionsEntity(org.apache.nifi.web.api.entity.ConnectionsEntity) FunnelEntity(org.apache.nifi.web.api.entity.FunnelEntity) VariableRegistryUpdateRequest(org.apache.nifi.registry.variable.VariableRegistryUpdateRequest) ControllerServicesEntity(org.apache.nifi.web.api.entity.ControllerServicesEntity) Set(java.util.Set) InputPortsEntity(org.apache.nifi.web.api.entity.InputPortsEntity) Executors(java.util.concurrent.Executors) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) FormDataParam(org.glassfish.jersey.media.multipart.FormDataParam) ProcessGroupsEntity(org.apache.nifi.web.api.entity.ProcessGroupsEntity) FlowComparisonEntity(org.apache.nifi.web.api.entity.FlowComparisonEntity) ScheduledState(org.apache.nifi.controller.ScheduledState) LabelsEntity(org.apache.nifi.web.api.entity.LabelsEntity) UriInfo(javax.ws.rs.core.UriInfo) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) DtoFactory(org.apache.nifi.web.api.dto.DtoFactory) Entity(org.apache.nifi.web.api.entity.Entity) GET(javax.ws.rs.GET) ControllerServiceEntity(org.apache.nifi.web.api.entity.ControllerServiceEntity) ConfigurableComponent(org.apache.nifi.components.ConfigurableComponent) TemplateEntity(org.apache.nifi.web.api.entity.TemplateEntity) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) HttpMethod(javax.ws.rs.HttpMethod) HttpServletRequest(javax.servlet.http.HttpServletRequest) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) NiFiUserDetails(org.apache.nifi.authorization.user.NiFiUserDetails) Api(io.swagger.annotations.Api) VariableRegistryDTO(org.apache.nifi.web.api.dto.VariableRegistryDTO) FlowDTO(org.apache.nifi.web.api.dto.flow.FlowDTO) VersionedFlowState(org.apache.nifi.registry.flow.VersionedFlowState) NiFiServiceFacade(org.apache.nifi.web.NiFiServiceFacade) AuthorizableLookup(org.apache.nifi.authorization.AuthorizableLookup) RequestAction(org.apache.nifi.authorization.RequestAction) FlowEncodingVersion(org.apache.nifi.controller.serialization.FlowEncodingVersion) JAXBElement(javax.xml.bind.JAXBElement) RemoteProcessGroupsEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupsEntity) IOException(java.io.IOException) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) Authorizer(org.apache.nifi.authorization.Authorizer) ApiResponse(io.swagger.annotations.ApiResponse) FlowEntity(org.apache.nifi.web.api.entity.FlowEntity) AffectedComponentEntity(org.apache.nifi.web.api.entity.AffectedComponentEntity) OutputPortsEntity(org.apache.nifi.web.api.entity.OutputPortsEntity) ScheduleComponentsEntity(org.apache.nifi.web.api.entity.ScheduleComponentsEntity) XmlUtils(org.apache.nifi.security.xml.XmlUtils) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate) ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) Date(java.util.Date) ConnectableType(org.apache.nifi.connectable.ConnectableType) ProcessorStatusDTO(org.apache.nifi.web.api.dto.status.ProcessorStatusDTO) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) BundleDTO(org.apache.nifi.web.api.dto.BundleDTO) ApiOperation(io.swagger.annotations.ApiOperation) AuthorizeControllerServiceReference(org.apache.nifi.authorization.AuthorizeControllerServiceReference) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) ActivateControllerServicesEntity(org.apache.nifi.web.api.entity.ActivateControllerServicesEntity) XMLStreamReader(javax.xml.stream.XMLStreamReader) DefaultValue(javax.ws.rs.DefaultValue) URI(java.net.URI) ThreadFactory(java.util.concurrent.ThreadFactory) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Authorizable(org.apache.nifi.authorization.resource.Authorizable) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) ApiImplicitParam(io.swagger.annotations.ApiImplicitParam) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SnippetAuthorizable(org.apache.nifi.authorization.SnippetAuthorizable) UUID(java.util.UUID) BundleUtils(org.apache.nifi.util.BundleUtils) PortEntity(org.apache.nifi.web.api.entity.PortEntity) LongParameter(org.apache.nifi.web.api.request.LongParameter) JAXBException(javax.xml.bind.JAXBException) Collectors(java.util.stream.Collectors) List(java.util.List) Response(javax.ws.rs.core.Response) ProcessGroupEntity(org.apache.nifi.web.api.entity.ProcessGroupEntity) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) CopySnippetRequestEntity(org.apache.nifi.web.api.entity.CopySnippetRequestEntity) Authentication(org.springframework.security.core.Authentication) Pause(org.apache.nifi.web.util.Pause) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) PathParam(javax.ws.rs.PathParam) Bucket(org.apache.nifi.registry.bucket.Bucket) Revision(org.apache.nifi.web.Revision) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses) Function(java.util.function.Function) AffectedComponentDTO(org.apache.nifi.web.api.dto.AffectedComponentDTO) ConcurrentMap(java.util.concurrent.ConcurrentMap) FlowRegistryUtils(org.apache.nifi.registry.flow.FlowRegistryUtils) CreateTemplateRequestEntity(org.apache.nifi.web.api.entity.CreateTemplateRequestEntity) VersionControlInformationDTO(org.apache.nifi.web.api.dto.VersionControlInformationDTO) VariableRegistryUpdateRequestEntity(org.apache.nifi.web.api.entity.VariableRegistryUpdateRequestEntity) NiFiAuthenticationToken(org.apache.nifi.web.security.token.NiFiAuthenticationToken) Status(javax.ws.rs.core.Response.Status) JAXBContext(javax.xml.bind.JAXBContext) ExecutorService(java.util.concurrent.ExecutorService) Unmarshaller(javax.xml.bind.Unmarshaller) TemplateContentsAuthorizable(org.apache.nifi.authorization.TemplateContentsAuthorizable) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) ProcessorsEntity(org.apache.nifi.web.api.entity.ProcessorsEntity) VariableRegistryEntity(org.apache.nifi.web.api.entity.VariableRegistryEntity) VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) LabelEntity(org.apache.nifi.web.api.entity.LabelEntity) ConnectionEntity(org.apache.nifi.web.api.entity.ConnectionEntity) ProcessGroupAuthorizable(org.apache.nifi.authorization.ProcessGroupAuthorizable) RemoteProcessGroupEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupEntity) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) PUT(javax.ws.rs.PUT) Authorization(io.swagger.annotations.Authorization) Collections(java.util.Collections) InputStream(java.io.InputStream) ProcessorStatusDTO(org.apache.nifi.web.api.dto.status.ProcessorStatusDTO) AffectedComponentDTO(org.apache.nifi.web.api.dto.AffectedComponentDTO) AffectedComponentEntity(org.apache.nifi.web.api.entity.AffectedComponentEntity)

Example 4 with ScheduledState

use of org.apache.nifi.controller.ScheduledState in project nifi by apache.

the class StandardInputPortDAO method verifyUpdate.

private void verifyUpdate(final Port inputPort, final PortDTO portDTO) {
    if (isNotNull(portDTO.getState())) {
        final ScheduledState purposedScheduledState = ScheduledState.valueOf(portDTO.getState());
        // only attempt an action if it is changing
        if (!purposedScheduledState.equals(inputPort.getScheduledState())) {
            // perform the appropriate action
            switch(purposedScheduledState) {
                case RUNNING:
                    inputPort.verifyCanStart();
                    break;
                case STOPPED:
                    switch(inputPort.getScheduledState()) {
                        case RUNNING:
                            inputPort.verifyCanStop();
                            break;
                        case DISABLED:
                            inputPort.verifyCanEnable();
                            break;
                    }
                    break;
                case DISABLED:
                    inputPort.verifyCanDisable();
                    break;
            }
        }
    }
    // see what's be modified
    if (isAnyNotNull(portDTO.getUserAccessControl(), portDTO.getGroupAccessControl(), portDTO.getConcurrentlySchedulableTaskCount(), portDTO.getName(), portDTO.getComments())) {
        // validate the request
        final List<String> requestValidation = validateProposedConfiguration(portDTO);
        // ensure there was no validation errors
        if (!requestValidation.isEmpty()) {
            throw new ValidationException(requestValidation);
        }
        // ensure the port can be updated
        inputPort.verifyCanUpdate();
    }
}
Also used : ValidationException(org.apache.nifi.controller.exception.ValidationException) ScheduledState(org.apache.nifi.controller.ScheduledState)

Example 5 with ScheduledState

use of org.apache.nifi.controller.ScheduledState in project nifi by apache.

the class StandardProcessorDAO method verifyUpdate.

private void verifyUpdate(ProcessorNode processor, ProcessorDTO processorDTO) {
    // ensure the state, if specified, is valid
    if (isNotNull(processorDTO.getState())) {
        try {
            final ScheduledState purposedScheduledState = ScheduledState.valueOf(processorDTO.getState());
            // only attempt an action if it is changing
            if (!purposedScheduledState.equals(processor.getScheduledState())) {
                // perform the appropriate action
                switch(purposedScheduledState) {
                    case RUNNING:
                        processor.verifyCanStart();
                        break;
                    case STOPPED:
                        switch(processor.getScheduledState()) {
                            case RUNNING:
                                processor.verifyCanStop();
                                break;
                            case DISABLED:
                                processor.verifyCanEnable();
                                break;
                        }
                        break;
                    case DISABLED:
                        processor.verifyCanDisable();
                        break;
                }
            }
        } catch (IllegalArgumentException iae) {
            throw new IllegalArgumentException(String.format("The specified processor state (%s) is not valid. Valid options are 'RUNNING', 'STOPPED', and 'DISABLED'.", processorDTO.getState()));
        }
    }
    boolean modificationRequest = false;
    if (isAnyNotNull(processorDTO.getName(), processorDTO.getBundle())) {
        modificationRequest = true;
    }
    final BundleDTO bundleDTO = processorDTO.getBundle();
    if (bundleDTO != null) {
        // ensures all nodes in a cluster have the bundle, throws exception if bundle not found for the given type
        final BundleCoordinate bundleCoordinate = BundleUtils.getBundle(processor.getCanonicalClassName(), bundleDTO);
        // ensure we are only changing to a bundle with the same group and id, but different version
        processor.verifyCanUpdateBundle(bundleCoordinate);
    }
    final ProcessorConfigDTO configDTO = processorDTO.getConfig();
    if (configDTO != null) {
        if (isAnyNotNull(configDTO.getAnnotationData(), configDTO.getAutoTerminatedRelationships(), configDTO.getBulletinLevel(), configDTO.getComments(), configDTO.getConcurrentlySchedulableTaskCount(), configDTO.getPenaltyDuration(), configDTO.getProperties(), configDTO.getSchedulingPeriod(), configDTO.getSchedulingStrategy(), configDTO.getExecutionNode(), configDTO.getYieldDuration())) {
            modificationRequest = true;
        }
        // validate the request
        final List<String> requestValidation = validateProposedConfiguration(processor, configDTO);
        // ensure there was no validation errors
        if (!requestValidation.isEmpty()) {
            throw new ValidationException(requestValidation);
        }
    }
    if (modificationRequest) {
        processor.verifyCanUpdate();
    }
}
Also used : ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) ValidationException(org.apache.nifi.controller.exception.ValidationException) ScheduledState(org.apache.nifi.controller.ScheduledState) BundleDTO(org.apache.nifi.web.api.dto.BundleDTO) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate)

Aggregations

ScheduledState (org.apache.nifi.controller.ScheduledState)35 NiFiUser (org.apache.nifi.authorization.user.NiFiUser)9 Map (java.util.Map)7 Set (java.util.Set)7 Collectors (java.util.stream.Collectors)7 ControllerServiceState (org.apache.nifi.controller.service.ControllerServiceState)7 Date (java.util.Date)6 HttpMethod (javax.ws.rs.HttpMethod)6 MediaType (javax.ws.rs.core.MediaType)6 ValidationException (org.apache.nifi.controller.exception.ValidationException)6 List (java.util.List)5 HashSet (java.util.HashSet)4 NiFiServiceFacade (org.apache.nifi.web.NiFiServiceFacade)4 Revision (org.apache.nifi.web.Revision)4 BundleDTO (org.apache.nifi.web.api.dto.BundleDTO)4 ProcessorConfigDTO (org.apache.nifi.web.api.dto.ProcessorConfigDTO)4 ControllerServiceEntity (org.apache.nifi.web.api.entity.ControllerServiceEntity)4 Api (io.swagger.annotations.Api)3 ApiOperation (io.swagger.annotations.ApiOperation)3 ApiParam (io.swagger.annotations.ApiParam)3