Search in sources :

Example 41 with ProcessorEntity

use of org.apache.nifi.web.api.entity.ProcessorEntity in project nifi by apache.

the class ProcessorsEndpointMerger method merge.

@Override
public final NodeResponse merge(final URI uri, final String method, final Set<NodeResponse> successfulResponses, final Set<NodeResponse> problematicResponses, final NodeResponse clientResponse) {
    if (!canHandle(uri, method)) {
        throw new IllegalArgumentException("Cannot use Endpoint Mapper of type " + getClass().getSimpleName() + " to map responses for URI " + uri + ", HTTP Method " + method);
    }
    final ProcessorsEntity responseEntity = clientResponse.getClientResponse().readEntity(ProcessorsEntity.class);
    final Set<ProcessorEntity> processorEntities = responseEntity.getProcessors();
    final Map<String, Map<NodeIdentifier, ProcessorEntity>> entityMap = new HashMap<>();
    for (final NodeResponse nodeResponse : successfulResponses) {
        final ProcessorsEntity nodeResponseEntity = nodeResponse == clientResponse ? responseEntity : nodeResponse.getClientResponse().readEntity(ProcessorsEntity.class);
        final Set<ProcessorEntity> nodeProcessorEntities = nodeResponseEntity.getProcessors();
        for (final ProcessorEntity nodeProcessorEntity : nodeProcessorEntities) {
            final NodeIdentifier nodeId = nodeResponse.getNodeId();
            Map<NodeIdentifier, ProcessorEntity> innerMap = entityMap.get(nodeId);
            if (innerMap == null) {
                innerMap = new HashMap<>();
                entityMap.put(nodeProcessorEntity.getId(), innerMap);
            }
            innerMap.put(nodeResponse.getNodeId(), nodeProcessorEntity);
        }
    }
    ProcessorsEntityMerger.mergeProcessors(processorEntities, entityMap);
    // create a new client response
    return new NodeResponse(clientResponse, responseEntity);
}
Also used : HashMap(java.util.HashMap) ProcessorsEntity(org.apache.nifi.web.api.entity.ProcessorsEntity) NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) Map(java.util.Map) HashMap(java.util.HashMap)

Example 42 with ProcessorEntity

use of org.apache.nifi.web.api.entity.ProcessorEntity in project nifi by apache.

the class ProcessGroupResource method getProcessors.

/**
 * Retrieves all the processors in this NiFi.
 *
 * @param groupId group id
 * @return A processorsEntity.
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/processors")
@ApiOperation(value = "Gets all processors", response = ProcessorsEntity.class, authorizations = { @Authorization(value = "Read - /process-groups/{uuid}") })
@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 getProcessors(@ApiParam(value = "The process group id.", required = true) @PathParam("id") final String groupId, @ApiParam("Whether or not to include processors from descendant process groups") @QueryParam("includeDescendantGroups") @DefaultValue("false") boolean includeDescendantGroups) {
    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }
    // authorize access
    serviceFacade.authorizeAccess(lookup -> {
        final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
        processGroup.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
    });
    // get the processors
    final Set<ProcessorEntity> processors = serviceFacade.getProcessors(groupId, includeDescendantGroups);
    // create the response entity
    final ProcessorsEntity entity = new ProcessorsEntity();
    entity.setProcessors(processorResource.populateRemainingProcessorEntitiesContent(processors));
    // generate the response
    return generateOkResponse(entity).build();
}
Also used : ProcessorsEntity(org.apache.nifi.web.api.entity.ProcessorsEntity) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) Authorizable(org.apache.nifi.authorization.resource.Authorizable) SnippetAuthorizable(org.apache.nifi.authorization.SnippetAuthorizable) TemplateContentsAuthorizable(org.apache.nifi.authorization.TemplateContentsAuthorizable) ProcessGroupAuthorizable(org.apache.nifi.authorization.ProcessGroupAuthorizable) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 43 with ProcessorEntity

use of org.apache.nifi.web.api.entity.ProcessorEntity in project nifi by apache.

the class ProcessGroupResource method waitForProcessorStatus.

/**
 * Periodically polls the process group with the given ID, waiting for all processors whose ID's are given to have the given Scheduled State.
 *
 * @param groupId the ID of the Process Group to poll
 * @param processorIds the ID of all Processors whose state should be equal to the given desired state
 * @param desiredState the desired state for all processors with the ID's given
 * @param pause the Pause that can be used to wait between polling
 * @return <code>true</code> if successful, <code>false</code> if unable to wait for processors to reach the desired state
 */
private boolean waitForProcessorStatus(final URI originalUri, final String groupId, final Set<String> processorIds, final ScheduledState desiredState, final VariableRegistryUpdateRequest updateRequest, final Pause pause) throws InterruptedException {
    URI groupUri;
    try {
        groupUri = new URI(originalUri.getScheme(), originalUri.getUserInfo(), originalUri.getHost(), originalUri.getPort(), "/nifi-api/process-groups/" + groupId + "/processors", "includeDescendantGroups=true", originalUri.getFragment());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    final Map<String, String> headers = new HashMap<>();
    final MultivaluedMap<String, String> requestEntity = new MultivaluedHashMap<>();
    boolean continuePolling = true;
    while (continuePolling) {
        // 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.GET, groupUri, requestEntity, headers).awaitMergedResponse();
        } else {
            clusterResponse = getRequestReplicator().forwardToCoordinator(getClusterCoordinatorNode(), HttpMethod.GET, groupUri, requestEntity, headers).awaitMergedResponse();
        }
        if (clusterResponse.getStatus() != Status.OK.getStatusCode()) {
            return false;
        }
        final ProcessorsEntity processorsEntity = getResponseEntity(clusterResponse, ProcessorsEntity.class);
        final Set<ProcessorEntity> processorEntities = processorsEntity.getProcessors();
        if (isProcessorActionComplete(processorEntities, updateRequest, processorIds, desiredState)) {
            logger.debug("All {} processors of interest now have the desired state of {}", processorIds.size(), desiredState);
            return true;
        }
        // Not all of the processors are in the desired state. Pause for a bit and poll again.
        continuePolling = pause.pause();
    }
    return false;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) URISyntaxException(java.net.URISyntaxException) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) URI(java.net.URI) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ProcessorsEntity(org.apache.nifi.web.api.entity.ProcessorsEntity)

Example 44 with ProcessorEntity

use of org.apache.nifi.web.api.entity.ProcessorEntity in project nifi by apache.

the class ProcessorResource method terminateProcessor.

@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/threads")
@ApiOperation(value = "Terminates a processor, essentially \"deleting\" its threads and any active tasks", response = ProcessorEntity.class, authorizations = { @Authorization(value = "Write - /processors/{uuid}") })
@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 terminateProcessor(@ApiParam(value = "The processor id.", required = true) @PathParam("id") final String id) {
    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST);
    }
    final ProcessorEntity requestProcessorEntity = new ProcessorEntity();
    requestProcessorEntity.setId(id);
    return withWriteLock(serviceFacade, requestProcessorEntity, lookup -> {
        final Authorizable authorizable = lookup.getProcessor(id).getAuthorizable();
        authorizable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
    }, () -> serviceFacade.verifyTerminateProcessor(id), processorEntity -> {
        final ProcessorEntity entity = serviceFacade.terminateProcessor(processorEntity.getId());
        populateRemainingProcessorEntityContent(entity);
        return generateOkResponse(entity).build();
    });
}
Also used : ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) Authorizable(org.apache.nifi.authorization.resource.Authorizable) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 45 with ProcessorEntity

use of org.apache.nifi.web.api.entity.ProcessorEntity in project nifi by apache.

the class ClusterReplicationComponentLifecycle method isProcessorActionComplete.

private boolean isProcessorActionComplete(final Set<ProcessorEntity> processorEntities, final Map<String, AffectedComponentEntity> affectedComponents, final ScheduledState desiredState) {
    final String desiredStateName = desiredState.name();
    // update the affected processors
    processorEntities.stream().filter(entity -> affectedComponents.containsKey(entity.getId())).forEach(entity -> {
        final AffectedComponentEntity affectedComponentEntity = affectedComponents.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 -> affectedComponents.containsKey(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 : NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier) Revision(org.apache.nifi.web.Revision) ProcessorStatusDTO(org.apache.nifi.web.api.dto.status.ProcessorStatusDTO) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) ControllerServiceEntity(org.apache.nifi.web.api.entity.ControllerServiceEntity) HashMap(java.util.HashMap) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) Function(java.util.function.Function) AffectedComponentDTO(org.apache.nifi.web.api.dto.AffectedComponentDTO) HttpMethod(javax.ws.rs.HttpMethod) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) MediaType(javax.ws.rs.core.MediaType) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) ActivateControllerServicesEntity(org.apache.nifi.web.api.entity.ActivateControllerServicesEntity) Map(java.util.Map) ClusterCoordinator(org.apache.nifi.cluster.coordination.ClusterCoordinator) RequestReplicator(org.apache.nifi.cluster.coordination.http.replication.RequestReplicator) URI(java.net.URI) Status(javax.ws.rs.core.Response.Status) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) NiFiServiceFacade(org.apache.nifi.web.NiFiServiceFacade) NoClusterCoordinatorException(org.apache.nifi.cluster.exception.NoClusterCoordinatorException) Logger(org.slf4j.Logger) ControllerServicesEntity(org.apache.nifi.web.api.entity.ControllerServicesEntity) Set(java.util.Set) ProcessorsEntity(org.apache.nifi.web.api.entity.ProcessorsEntity) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Collectors(java.util.stream.Collectors) ReplicationTarget(org.apache.nifi.web.api.ApplicationResource.ReplicationTarget) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ScheduledState(org.apache.nifi.controller.ScheduledState) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) AffectedComponentEntity(org.apache.nifi.web.api.entity.AffectedComponentEntity) DtoFactory(org.apache.nifi.web.api.dto.DtoFactory) ScheduleComponentsEntity(org.apache.nifi.web.api.entity.ScheduleComponentsEntity) 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)

Aggregations

ProcessorEntity (org.apache.nifi.web.api.entity.ProcessorEntity)60 Response (javax.ws.rs.core.Response)29 Test (org.junit.Test)26 HashMap (java.util.HashMap)20 NodeIdentifier (org.apache.nifi.cluster.protocol.NodeIdentifier)19 HashSet (java.util.HashSet)17 ProcessorDTO (org.apache.nifi.web.api.dto.ProcessorDTO)17 URI (java.net.URI)16 RevisionDTO (org.apache.nifi.web.api.dto.RevisionDTO)16 Map (java.util.Map)15 NodeResponse (org.apache.nifi.cluster.manager.NodeResponse)12 NiFiUserDetails (org.apache.nifi.authorization.user.NiFiUserDetails)11 NiFiAuthenticationToken (org.apache.nifi.web.security.token.NiFiAuthenticationToken)11 Authentication (org.springframework.security.core.Authentication)11 Set (java.util.Set)10 Authorizable (org.apache.nifi.authorization.resource.Authorizable)10 NiFiUser (org.apache.nifi.authorization.user.NiFiUser)10 List (java.util.List)8 Collectors (java.util.stream.Collectors)8 ClusterCoordinator (org.apache.nifi.cluster.coordination.ClusterCoordinator)8