Search in sources :

Example 1 with VersionedFlowSnapshot

use of org.apache.nifi.registry.flow.VersionedFlowSnapshot in project nifi by apache.

the class StandardNiFiServiceFacade method getLocalModifications.

@Override
public FlowComparisonEntity getLocalModifications(final String processGroupId) {
    final ProcessGroup processGroup = processGroupDAO.getProcessGroup(processGroupId);
    final VersionControlInformation versionControlInfo = processGroup.getVersionControlInformation();
    if (versionControlInfo == null) {
        throw new IllegalStateException("Process Group with ID " + processGroupId + " is not under Version Control");
    }
    final FlowRegistry flowRegistry = flowRegistryClient.getFlowRegistry(versionControlInfo.getRegistryIdentifier());
    if (flowRegistry == null) {
        throw new IllegalStateException("Process Group with ID " + processGroupId + " is tracking to a flow in Flow Registry with ID " + versionControlInfo.getRegistryIdentifier() + " but cannot find a Flow Registry with that identifier");
    }
    final VersionedFlowSnapshot versionedFlowSnapshot;
    try {
        versionedFlowSnapshot = flowRegistry.getFlowContents(versionControlInfo.getBucketIdentifier(), versionControlInfo.getFlowIdentifier(), versionControlInfo.getVersion(), true, NiFiUserUtils.getNiFiUser());
    } catch (final IOException | NiFiRegistryException e) {
        throw new NiFiCoreException("Failed to retrieve flow with Flow Registry in order to calculate local differences due to " + e.getMessage(), e);
    }
    final NiFiRegistryFlowMapper mapper = new NiFiRegistryFlowMapper();
    final VersionedProcessGroup localGroup = mapper.mapProcessGroup(processGroup, controllerFacade.getControllerServiceProvider(), flowRegistryClient, true);
    final VersionedProcessGroup registryGroup = versionedFlowSnapshot.getFlowContents();
    final ComparableDataFlow localFlow = new StandardComparableDataFlow("Local Flow", localGroup);
    final ComparableDataFlow registryFlow = new StandardComparableDataFlow("Versioned Flow", registryGroup);
    final Set<String> ancestorServiceIds = getAncestorGroupServiceIds(processGroup);
    final FlowComparator flowComparator = new StandardFlowComparator(registryFlow, localFlow, ancestorServiceIds, new ConciseEvolvingDifferenceDescriptor());
    final FlowComparison flowComparison = flowComparator.compare();
    final Set<ComponentDifferenceDTO> differenceDtos = dtoFactory.createComponentDifferenceDtos(flowComparison);
    final FlowComparisonEntity entity = new FlowComparisonEntity();
    entity.setComponentDifferences(differenceDtos);
    return entity;
}
Also used : FlowRegistry(org.apache.nifi.registry.flow.FlowRegistry) NiFiRegistryFlowMapper(org.apache.nifi.registry.flow.mapping.NiFiRegistryFlowMapper) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) InstantiatedVersionedProcessGroup(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedProcessGroup) FlowComparison(org.apache.nifi.registry.flow.diff.FlowComparison) IOException(java.io.IOException) ConciseEvolvingDifferenceDescriptor(org.apache.nifi.registry.flow.diff.ConciseEvolvingDifferenceDescriptor) StandardFlowComparator(org.apache.nifi.registry.flow.diff.StandardFlowComparator) StandardComparableDataFlow(org.apache.nifi.registry.flow.diff.StandardComparableDataFlow) ComparableDataFlow(org.apache.nifi.registry.flow.diff.ComparableDataFlow) ComponentDifferenceDTO(org.apache.nifi.web.api.dto.ComponentDifferenceDTO) VersionControlInformation(org.apache.nifi.registry.flow.VersionControlInformation) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) ProcessGroup(org.apache.nifi.groups.ProcessGroup) InstantiatedVersionedProcessGroup(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedProcessGroup) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) FlowComparisonEntity(org.apache.nifi.web.api.entity.FlowComparisonEntity) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) StandardComparableDataFlow(org.apache.nifi.registry.flow.diff.StandardComparableDataFlow) StandardFlowComparator(org.apache.nifi.registry.flow.diff.StandardFlowComparator) FlowComparator(org.apache.nifi.registry.flow.diff.FlowComparator)

Example 2 with VersionedFlowSnapshot

use of org.apache.nifi.registry.flow.VersionedFlowSnapshot in project nifi by apache.

the class StandardNiFiServiceFacade method registerFlowWithFlowRegistry.

@Override
public VersionControlComponentMappingEntity registerFlowWithFlowRegistry(final String groupId, final StartVersionControlRequestEntity requestEntity) {
    final ProcessGroup processGroup = processGroupDAO.getProcessGroup(groupId);
    final VersionControlInformation currentVci = processGroup.getVersionControlInformation();
    final int expectedVersion = currentVci == null ? 1 : currentVci.getVersion() + 1;
    // Create a VersionedProcessGroup snapshot of the flow as it is currently.
    final InstantiatedVersionedProcessGroup versionedProcessGroup = createFlowSnapshot(groupId);
    final VersionedFlowDTO versionedFlowDto = requestEntity.getVersionedFlow();
    final String flowId = versionedFlowDto.getFlowId() == null ? UUID.randomUUID().toString() : versionedFlowDto.getFlowId();
    final VersionedFlow versionedFlow = new VersionedFlow();
    versionedFlow.setBucketIdentifier(versionedFlowDto.getBucketId());
    versionedFlow.setCreatedTimestamp(System.currentTimeMillis());
    versionedFlow.setDescription(versionedFlowDto.getDescription());
    versionedFlow.setModifiedTimestamp(versionedFlow.getCreatedTimestamp());
    versionedFlow.setName(versionedFlowDto.getFlowName());
    versionedFlow.setIdentifier(flowId);
    // Add the Versioned Flow and first snapshot to the Flow Registry
    final String registryId = requestEntity.getVersionedFlow().getRegistryId();
    final VersionedFlowSnapshot registeredSnapshot;
    final VersionedFlow registeredFlow;
    String action = "create the flow";
    try {
        // first, create the flow in the registry, if necessary
        if (versionedFlowDto.getFlowId() == null) {
            registeredFlow = registerVersionedFlow(registryId, versionedFlow);
        } else {
            registeredFlow = getVersionedFlow(registryId, versionedFlowDto.getBucketId(), versionedFlowDto.getFlowId());
        }
        action = "add the local flow to the Flow Registry as the first Snapshot";
        // add first snapshot to the flow in the registry
        registeredSnapshot = registerVersionedFlowSnapshot(registryId, registeredFlow, versionedProcessGroup, versionedFlowDto.getComments(), expectedVersion);
    } catch (final NiFiRegistryException e) {
        throw new IllegalArgumentException(e.getLocalizedMessage());
    } catch (final IOException ioe) {
        throw new IllegalStateException("Failed to communicate with Flow Registry when attempting to " + action);
    }
    final Bucket bucket = registeredSnapshot.getBucket();
    final VersionedFlow flow = registeredSnapshot.getFlow();
    // Update the Process Group with the new VersionControlInformation. (Send this to all nodes).
    final VersionControlInformationDTO vci = new VersionControlInformationDTO();
    vci.setBucketId(bucket.getIdentifier());
    vci.setBucketName(bucket.getName());
    vci.setFlowId(flow.getIdentifier());
    vci.setFlowName(flow.getName());
    vci.setFlowDescription(flow.getDescription());
    vci.setGroupId(groupId);
    vci.setRegistryId(registryId);
    vci.setRegistryName(getFlowRegistryName(registryId));
    vci.setVersion(registeredSnapshot.getSnapshotMetadata().getVersion());
    vci.setState(VersionedFlowState.UP_TO_DATE.name());
    final Map<String, String> mapping = dtoFactory.createVersionControlComponentMappingDto(versionedProcessGroup);
    final Revision groupRevision = revisionManager.getRevision(groupId);
    final RevisionDTO groupRevisionDto = dtoFactory.createRevisionDTO(groupRevision);
    final VersionControlComponentMappingEntity entity = new VersionControlComponentMappingEntity();
    entity.setVersionControlInformation(vci);
    entity.setProcessGroupRevision(groupRevisionDto);
    entity.setVersionControlComponentMapping(mapping);
    return entity;
}
Also used : VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) InstantiatedVersionedProcessGroup(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedProcessGroup) IOException(java.io.IOException) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) VersionControlInformationDTO(org.apache.nifi.web.api.dto.VersionControlInformationDTO) VersionControlInformation(org.apache.nifi.registry.flow.VersionControlInformation) VersionedFlowDTO(org.apache.nifi.web.api.dto.VersionedFlowDTO) Bucket(org.apache.nifi.registry.bucket.Bucket) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) ProcessGroup(org.apache.nifi.groups.ProcessGroup) InstantiatedVersionedProcessGroup(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedProcessGroup) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) VersionControlComponentMappingEntity(org.apache.nifi.web.api.entity.VersionControlComponentMappingEntity)

Example 3 with VersionedFlowSnapshot

use of org.apache.nifi.registry.flow.VersionedFlowSnapshot in project nifi by apache.

the class VersionsResource method updateFlowVersion.

private VersionControlInformationEntity updateFlowVersion(final String groupId, final ComponentLifecycle componentLifecycle, final URI exampleUri, final Set<AffectedComponentEntity> affectedComponents, final NiFiUser user, final boolean replicateRequest, final Revision revision, final VersionControlInformationEntity requestEntity, final VersionedFlowSnapshot flowSnapshot, final AsynchronousWebRequest<VersionControlInformationEntity> asyncRequest, final String idGenerationSeed, final boolean verifyNotModified, final boolean updateDescendantVersionedFlows) throws LifecycleManagementException, ResumeFlowException {
    // Steps 6-7: Determine which components must be stopped and stop them.
    final Set<String> stoppableReferenceTypes = new HashSet<>();
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_PROCESSOR);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_REMOTE_INPUT_PORT);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_REMOTE_OUTPUT_PORT);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_INPUT_PORT);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_OUTPUT_PORT);
    final Set<AffectedComponentEntity> runningComponents = affectedComponents.stream().filter(dto -> stoppableReferenceTypes.contains(dto.getComponent().getReferenceType())).filter(dto -> "Running".equalsIgnoreCase(dto.getComponent().getState())).collect(Collectors.toSet());
    logger.info("Stopping {} Processors", runningComponents.size());
    final CancellableTimedPause stopComponentsPause = new CancellableTimedPause(250, Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    asyncRequest.setCancelCallback(stopComponentsPause::cancel);
    componentLifecycle.scheduleComponents(exampleUri, user, groupId, runningComponents, ScheduledState.STOPPED, stopComponentsPause);
    if (asyncRequest.isCancelled()) {
        return null;
    }
    asyncRequest.update(new Date(), "Disabling Affected Controller Services", 20);
    // Steps 8-9. Disable enabled controller services that are affected
    final Set<AffectedComponentEntity> enabledServices = affectedComponents.stream().filter(dto -> AffectedComponentDTO.COMPONENT_TYPE_CONTROLLER_SERVICE.equals(dto.getComponent().getReferenceType())).filter(dto -> "Enabled".equalsIgnoreCase(dto.getComponent().getState())).collect(Collectors.toSet());
    logger.info("Disabling {} Controller Services", enabledServices.size());
    final CancellableTimedPause disableServicesPause = new CancellableTimedPause(250, Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    asyncRequest.setCancelCallback(disableServicesPause::cancel);
    componentLifecycle.activateControllerServices(exampleUri, user, groupId, enabledServices, ControllerServiceState.DISABLED, disableServicesPause);
    if (asyncRequest.isCancelled()) {
        return null;
    }
    asyncRequest.update(new Date(), "Updating Flow", 40);
    logger.info("Updating Process Group with ID {} to version {} of the Versioned Flow", groupId, flowSnapshot.getSnapshotMetadata().getVersion());
    // by replicating a PUT to /nifi-api/versions/process-groups/{groupId}
    try {
        if (replicateRequest) {
            final URI updateUri;
            try {
                updateUri = new URI(exampleUri.getScheme(), exampleUri.getUserInfo(), exampleUri.getHost(), exampleUri.getPort(), "/nifi-api/versions/process-groups/" + groupId, null, exampleUri.getFragment());
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }
            final Map<String, String> headers = new HashMap<>();
            headers.put("content-type", MediaType.APPLICATION_JSON);
            final VersionedFlowSnapshotEntity snapshotEntity = new VersionedFlowSnapshotEntity();
            snapshotEntity.setProcessGroupRevision(dtoFactory.createRevisionDTO(revision));
            snapshotEntity.setRegistryId(requestEntity.getVersionControlInformation().getRegistryId());
            snapshotEntity.setVersionedFlow(flowSnapshot);
            snapshotEntity.setUpdateDescendantVersionedFlows(updateDescendantVersionedFlows);
            final NodeResponse clusterResponse;
            try {
                logger.debug("Replicating PUT request to {} for user {}", updateUri, user);
                if (getReplicationTarget() == ReplicationTarget.CLUSTER_NODES) {
                    clusterResponse = getRequestReplicator().replicate(user, HttpMethod.PUT, updateUri, snapshotEntity, headers).awaitMergedResponse();
                } else {
                    clusterResponse = getRequestReplicator().forwardToCoordinator(getClusterCoordinatorNode(), user, HttpMethod.PUT, updateUri, snapshotEntity, headers).awaitMergedResponse();
                }
            } catch (final InterruptedException ie) {
                logger.warn("Interrupted while replicating PUT request to {} for user {}", updateUri, user);
                Thread.currentThread().interrupt();
                throw new LifecycleManagementException("Interrupted while updating flows across cluster", ie);
            }
            final int updateFlowStatus = clusterResponse.getStatus();
            if (updateFlowStatus != Status.OK.getStatusCode()) {
                final String explanation = getResponseEntity(clusterResponse, String.class);
                logger.error("Failed to update flow across cluster when replicating PUT request to {} for user {}. Received {} response with explanation: {}", updateUri, user, updateFlowStatus, explanation);
                throw new LifecycleManagementException("Failed to update Flow on all nodes in cluster due to " + explanation);
            }
        } else {
            // Step 10: Ensure that if any connection exists in the flow and does not exist in the proposed snapshot,
            // that it has no data in it. Ensure that no Input Port was removed, unless it currently has no incoming connections.
            // Ensure that no Output Port was removed, unless it currently has no outgoing connections.
            serviceFacade.verifyCanUpdate(groupId, flowSnapshot, true, verifyNotModified);
            // Step 11-12. Update Process Group to the new flow and update variable registry with any Variables that were added or removed
            final VersionControlInformationDTO requestVci = requestEntity.getVersionControlInformation();
            final Bucket bucket = flowSnapshot.getBucket();
            final VersionedFlow flow = flowSnapshot.getFlow();
            final VersionedFlowSnapshotMetadata metadata = flowSnapshot.getSnapshotMetadata();
            final VersionControlInformationDTO vci = new VersionControlInformationDTO();
            vci.setBucketId(metadata.getBucketIdentifier());
            vci.setBucketName(bucket.getName());
            vci.setFlowDescription(flow.getDescription());
            vci.setFlowId(flow.getIdentifier());
            vci.setFlowName(flow.getName());
            vci.setGroupId(groupId);
            vci.setRegistryId(requestVci.getRegistryId());
            vci.setRegistryName(serviceFacade.getFlowRegistryName(requestVci.getRegistryId()));
            vci.setVersion(metadata.getVersion());
            vci.setState(flowSnapshot.isLatest() ? VersionedFlowState.UP_TO_DATE.name() : VersionedFlowState.STALE.name());
            serviceFacade.updateProcessGroupContents(user, revision, groupId, vci, flowSnapshot, idGenerationSeed, verifyNotModified, false, updateDescendantVersionedFlows);
        }
    } finally {
        if (!asyncRequest.isCancelled()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Re-Enabling {} Controller Services: {}", enabledServices.size(), enabledServices);
            }
            asyncRequest.update(new Date(), "Re-Enabling Controller Services", 60);
            // 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(enabledServices, user);
            logger.info("Successfully updated flow; re-enabling {} Controller Services", servicesToEnable.size());
            try {
                componentLifecycle.activateControllerServices(exampleUri, user, groupId, servicesToEnable, ControllerServiceState.ENABLED, enableServicesPause);
            } catch (final IllegalStateException ise) {
                // a more intelligent error message as to exactly what happened, rather than indicate that the flow could not be updated.
                throw new ResumeFlowException("Failed to re-enable Controller Services because " + ise.getMessage(), ise);
            }
        }
        if (!asyncRequest.isCancelled()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Restart {} Processors: {}", runningComponents.size(), runningComponents);
            }
            asyncRequest.update(new Date(), "Restarting Processors", 80);
            // Step 14. Restart all components
            final Set<AffectedComponentEntity> componentsToStart = getUpdatedEntities(runningComponents, user);
            // If there are any Remote Group Ports that are supposed to be started and have no connections, we want to remove those from our Set.
            // This will happen if the Remote Group Port is transmitting when the version change happens but the new flow version does not have
            // a connection to the port. In such a case, the Port still is included in the Updated Entities because we do not remove them
            // when updating the flow (they are removed in the background).
            final Set<AffectedComponentEntity> avoidStarting = new HashSet<>();
            for (final AffectedComponentEntity componentEntity : componentsToStart) {
                final AffectedComponentDTO componentDto = componentEntity.getComponent();
                final String referenceType = componentDto.getReferenceType();
                if (!AffectedComponentDTO.COMPONENT_TYPE_REMOTE_INPUT_PORT.equals(referenceType) && !AffectedComponentDTO.COMPONENT_TYPE_REMOTE_OUTPUT_PORT.equals(referenceType)) {
                    continue;
                }
                boolean startComponent;
                try {
                    startComponent = serviceFacade.isRemoteGroupPortConnected(componentDto.getProcessGroupId(), componentDto.getId());
                } catch (final ResourceNotFoundException rnfe) {
                    // Could occur if RPG is refreshed at just the right time.
                    startComponent = false;
                }
                // rather than removing the component here, because doing so would result in a ConcurrentModificationException.
                if (!startComponent) {
                    avoidStarting.add(componentEntity);
                }
            }
            componentsToStart.removeAll(avoidStarting);
            final CancellableTimedPause startComponentsPause = new CancellableTimedPause(250, Long.MAX_VALUE, TimeUnit.MILLISECONDS);
            asyncRequest.setCancelCallback(startComponentsPause::cancel);
            logger.info("Restarting {} Processors", componentsToStart.size());
            try {
                componentLifecycle.scheduleComponents(exampleUri, user, groupId, componentsToStart, ScheduledState.RUNNING, startComponentsPause);
            } catch (final IllegalStateException ise) {
                // a more intelligent error message as to exactly what happened, rather than indicate that the flow could not be updated.
                throw new ResumeFlowException("Failed to restart components because " + ise.getMessage(), ise);
            }
        }
    }
    asyncRequest.setCancelCallback(null);
    if (asyncRequest.isCancelled()) {
        return null;
    }
    asyncRequest.update(new Date(), "Complete", 100);
    return serviceFacade.getVersionControlInformation(groupId);
}
Also used : Produces(javax.ws.rs.Produces) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) StringUtils(org.apache.commons.lang3.StringUtils) ClientIdParameter(org.apache.nifi.web.api.request.ClientIdParameter) VersionedFlowSnapshotMetadata(org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) Map(java.util.Map) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) DefaultValue(javax.ws.rs.DefaultValue) AsyncRequestManager(org.apache.nifi.web.api.concurrent.AsyncRequestManager) URI(java.net.URI) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) VersionedFlowUpdateRequestDTO(org.apache.nifi.web.api.dto.VersionedFlowUpdateRequestDTO) DELETE(javax.ws.rs.DELETE) LifecycleManagementException(org.apache.nifi.web.util.LifecycleManagementException) Authorizable(org.apache.nifi.authorization.resource.Authorizable) VersionedFlowDTO(org.apache.nifi.web.api.dto.VersionedFlowDTO) Set(java.util.Set) UUID(java.util.UUID) BundleUtils(org.apache.nifi.util.BundleUtils) LongParameter(org.apache.nifi.web.api.request.LongParameter) Collectors(java.util.stream.Collectors) FlowController(org.apache.nifi.controller.FlowController) CreateActiveRequestEntity(org.apache.nifi.web.api.entity.CreateActiveRequestEntity) Response(javax.ws.rs.core.Response) ScheduledState(org.apache.nifi.controller.ScheduledState) ProcessGroupEntity(org.apache.nifi.web.api.entity.ProcessGroupEntity) VersionedFlowSnapshotEntity(org.apache.nifi.web.api.entity.VersionedFlowSnapshotEntity) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) DtoFactory(org.apache.nifi.web.api.dto.DtoFactory) Entity(org.apache.nifi.web.api.entity.Entity) PathParam(javax.ws.rs.PathParam) Bucket(org.apache.nifi.registry.bucket.Bucket) Revision(org.apache.nifi.web.Revision) GET(javax.ws.rs.GET) AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) ConfigurableComponent(org.apache.nifi.components.ConfigurableComponent) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) AffectedComponentDTO(org.apache.nifi.web.api.dto.AffectedComponentDTO) ComponentLifecycle(org.apache.nifi.web.util.ComponentLifecycle) HttpMethod(javax.ws.rs.HttpMethod) HashSet(java.util.HashSet) FlowRegistryUtils(org.apache.nifi.registry.flow.FlowRegistryUtils) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) VersionControlInformationDTO(org.apache.nifi.web.api.dto.VersionControlInformationDTO) Api(io.swagger.annotations.Api) VersionControlComponentMappingEntity(org.apache.nifi.web.api.entity.VersionControlComponentMappingEntity) CancellableTimedPause(org.apache.nifi.web.util.CancellableTimedPause) Status(javax.ws.rs.core.Response.Status) LinkedHashSet(java.util.LinkedHashSet) ResumeFlowException(org.apache.nifi.web.ResumeFlowException) VersionedFlowState(org.apache.nifi.registry.flow.VersionedFlowState) AffectedComponentUtils(org.apache.nifi.web.util.AffectedComponentUtils) NiFiServiceFacade(org.apache.nifi.web.NiFiServiceFacade) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) RequestAction(org.apache.nifi.authorization.RequestAction) IOException(java.io.IOException) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) StandardAsynchronousWebRequest(org.apache.nifi.web.api.concurrent.StandardAsynchronousWebRequest) VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) StartVersionControlRequestEntity(org.apache.nifi.web.api.entity.StartVersionControlRequestEntity) Authorizer(org.apache.nifi.authorization.Authorizer) VersionControlInformationEntity(org.apache.nifi.web.api.entity.VersionControlInformationEntity) ProcessGroupAuthorizable(org.apache.nifi.authorization.ProcessGroupAuthorizable) ApiResponse(io.swagger.annotations.ApiResponse) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) PUT(javax.ws.rs.PUT) AffectedComponentEntity(org.apache.nifi.web.api.entity.AffectedComponentEntity) VersionedFlowUpdateRequestEntity(org.apache.nifi.web.api.entity.VersionedFlowUpdateRequestEntity) Authorization(io.swagger.annotations.Authorization) RequestManager(org.apache.nifi.web.api.concurrent.RequestManager) Collections(java.util.Collections) AsynchronousWebRequest(org.apache.nifi.web.api.concurrent.AsynchronousWebRequest) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) NodeResponse(org.apache.nifi.cluster.manager.NodeResponse) VersionedFlowSnapshotEntity(org.apache.nifi.web.api.entity.VersionedFlowSnapshotEntity) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) VersionControlInformationDTO(org.apache.nifi.web.api.dto.VersionControlInformationDTO) CancellableTimedPause(org.apache.nifi.web.util.CancellableTimedPause) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) AffectedComponentEntity(org.apache.nifi.web.api.entity.AffectedComponentEntity) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) ResumeFlowException(org.apache.nifi.web.ResumeFlowException) Date(java.util.Date) VersionedFlowSnapshotMetadata(org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata) LifecycleManagementException(org.apache.nifi.web.util.LifecycleManagementException) Bucket(org.apache.nifi.registry.bucket.Bucket) AffectedComponentDTO(org.apache.nifi.web.api.dto.AffectedComponentDTO)

Example 4 with VersionedFlowSnapshot

use of org.apache.nifi.registry.flow.VersionedFlowSnapshot in project nifi by apache.

the class StandardNiFiServiceFacade method updateProcessGroupContents.

@Override
public ProcessGroupEntity updateProcessGroupContents(final NiFiUser user, final Revision revision, final String groupId, final VersionControlInformationDTO versionControlInfo, final VersionedFlowSnapshot proposedFlowSnapshot, final String componentIdSeed, final boolean verifyNotModified, final boolean updateSettings, final boolean updateDescendantVersionedFlows) {
    final ProcessGroup processGroup = processGroupDAO.getProcessGroup(groupId);
    final List<Revision> revisions = getComponentRevisions(processGroup, false);
    revisions.add(revision);
    final RevisionClaim revisionClaim = new StandardRevisionClaim(revisions);
    final RevisionUpdate<ProcessGroupDTO> revisionUpdate = revisionManager.updateRevision(revisionClaim, user, new UpdateRevisionTask<ProcessGroupDTO>() {

        @Override
        public RevisionUpdate<ProcessGroupDTO> update() {
            // update the Process Group
            processGroupDAO.updateProcessGroupFlow(groupId, user, proposedFlowSnapshot, versionControlInfo, componentIdSeed, verifyNotModified, updateSettings, updateDescendantVersionedFlows);
            // update the revisions
            final Set<Revision> updatedRevisions = revisions.stream().map(rev -> revisionManager.getRevision(rev.getComponentId()).incrementRevision(revision.getClientId())).collect(Collectors.toSet());
            // save
            controllerFacade.save();
            // gather details for response
            final ProcessGroupDTO dto = dtoFactory.createProcessGroupDto(processGroup);
            final Revision updatedRevision = revisionManager.getRevision(groupId).incrementRevision(revision.getClientId());
            final FlowModification lastModification = new FlowModification(updatedRevision, user.getIdentity());
            return new StandardRevisionUpdate<>(dto, lastModification, updatedRevisions);
        }
    });
    final FlowModification lastModification = revisionUpdate.getLastModification();
    final PermissionsDTO permissions = dtoFactory.createPermissionsDto(processGroup);
    final RevisionDTO updatedRevision = dtoFactory.createRevisionDTO(lastModification);
    final ProcessGroupStatusDTO status = dtoFactory.createConciseProcessGroupStatusDto(controllerFacade.getProcessGroupStatus(processGroup.getIdentifier()));
    final List<BulletinDTO> bulletins = dtoFactory.createBulletinDtos(bulletinRepository.findBulletinsForSource(processGroup.getIdentifier()));
    final List<BulletinEntity> bulletinEntities = bulletins.stream().map(bulletin -> entityFactory.createBulletinEntity(bulletin, permissions.getCanRead())).collect(Collectors.toList());
    return entityFactory.createProcessGroupEntity(revisionUpdate.getComponent(), updatedRevision, permissions, status, bulletinEntities);
}
Also used : EnforcePolicyPermissionsThroughBaseResource(org.apache.nifi.authorization.resource.EnforcePolicyPermissionsThroughBaseResource) ConnectionDiagnosticsDTO(org.apache.nifi.web.api.dto.diagnostics.ConnectionDiagnosticsDTO) FlowComparison(org.apache.nifi.registry.flow.diff.FlowComparison) ConnectionDTO(org.apache.nifi.web.api.dto.ConnectionDTO) ProcessorEntity(org.apache.nifi.web.api.entity.ProcessorEntity) AuthorizeAccess(org.apache.nifi.authorization.AuthorizeAccess) VersionedFlowSnapshotMetadata(org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata) SnippetEntity(org.apache.nifi.web.api.entity.SnippetEntity) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) NiFiRegistryException(org.apache.nifi.registry.client.NiFiRegistryException) Scope(org.apache.nifi.components.state.Scope) ControllerFacade(org.apache.nifi.web.controller.ControllerFacade) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) Map(java.util.Map) UserGroupDAO(org.apache.nifi.web.dao.UserGroupDAO) CurrentUserEntity(org.apache.nifi.web.api.entity.CurrentUserEntity) Connection(org.apache.nifi.connectable.Connection) RevisionUpdate(org.apache.nifi.web.revision.RevisionUpdate) BulletinDTO(org.apache.nifi.web.api.dto.BulletinDTO) FlowDifferenceFilters(org.apache.nifi.util.FlowDifferenceFilters) NodeEvent(org.apache.nifi.cluster.event.NodeEvent) VersionedFlowDTO(org.apache.nifi.web.api.dto.VersionedFlowDTO) RemoteProcessGroupPortDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupPortDTO) ComponentReferenceEntity(org.apache.nifi.web.api.entity.ComponentReferenceEntity) PortDTO(org.apache.nifi.web.api.dto.PortDTO) UserDTO(org.apache.nifi.web.api.dto.UserDTO) Stream(java.util.stream.Stream) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) InstantiatedVersionedProcessor(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedProcessor) ProcessGroupDAO(org.apache.nifi.web.dao.ProcessGroupDAO) ProcessorDiagnosticsEntity(org.apache.nifi.web.api.entity.ProcessorDiagnosticsEntity) RegistryDAO(org.apache.nifi.web.dao.RegistryDAO) UserEntity(org.apache.nifi.web.api.entity.UserEntity) CountersSnapshotDTO(org.apache.nifi.web.api.dto.CountersSnapshotDTO) SnippetUtils(org.apache.nifi.web.util.SnippetUtils) RemoteProcessGroupStatusEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupStatusEntity) PreviousValue(org.apache.nifi.history.PreviousValue) StandardComparableDataFlow(org.apache.nifi.registry.flow.diff.StandardComparableDataFlow) ConnectionDAO(org.apache.nifi.web.dao.ConnectionDAO) ProvenanceEventDTO(org.apache.nifi.web.api.dto.provenance.ProvenanceEventDTO) 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) Supplier(java.util.function.Supplier) CollectionUtils(org.apache.commons.collections4.CollectionUtils) LineageDTO(org.apache.nifi.web.api.dto.provenance.lineage.LineageDTO) LinkedHashMap(java.util.LinkedHashMap) FlowChangeAction(org.apache.nifi.action.FlowChangeAction) ProcessGroupCounts(org.apache.nifi.groups.ProcessGroupCounts) VariableRegistryDTO(org.apache.nifi.web.api.dto.VariableRegistryDTO) FlowDTO(org.apache.nifi.web.api.dto.flow.FlowDTO) RegistryDTO(org.apache.nifi.web.api.dto.RegistryDTO) ProvenanceDTO(org.apache.nifi.web.api.dto.provenance.ProvenanceDTO) ClusterRoles(org.apache.nifi.cluster.coordination.node.ClusterRoles) VersionedFlowState(org.apache.nifi.registry.flow.VersionedFlowState) FlowConfigurationEntity(org.apache.nifi.web.api.entity.FlowConfigurationEntity) ContentDirection(org.apache.nifi.controller.repository.claim.ContentDirection) PortDAO(org.apache.nifi.web.dao.PortDAO) AuthorizableLookup(org.apache.nifi.authorization.AuthorizableLookup) RequestAction(org.apache.nifi.authorization.RequestAction) IOException(java.io.IOException) CountersDTO(org.apache.nifi.web.api.dto.CountersDTO) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) NiFiRegistryFlowMapper(org.apache.nifi.registry.flow.mapping.NiFiRegistryFlowMapper) HistoryDTO(org.apache.nifi.web.api.dto.action.HistoryDTO) SystemDiagnosticsDTO(org.apache.nifi.web.api.dto.SystemDiagnosticsDTO) ControllerServiceDiagnosticsDTO(org.apache.nifi.web.api.dto.diagnostics.ControllerServiceDiagnosticsDTO) BulletinFactory(org.apache.nifi.events.BulletinFactory) VersionedFlowSnapshotMetadataEntity(org.apache.nifi.web.api.entity.VersionedFlowSnapshotMetadataEntity) ProcessorStatusEntity(org.apache.nifi.web.api.entity.ProcessorStatusEntity) ComponentStateDTO(org.apache.nifi.web.api.dto.ComponentStateDTO) UserDAO(org.apache.nifi.web.dao.UserDAO) RemoteProcessGroupDAO(org.apache.nifi.web.dao.RemoteProcessGroupDAO) UnknownNodeException(org.apache.nifi.cluster.manager.exception.UnknownNodeException) FlowEntity(org.apache.nifi.web.api.entity.FlowEntity) AffectedComponentEntity(org.apache.nifi.web.api.entity.AffectedComponentEntity) BucketEntity(org.apache.nifi.web.api.entity.BucketEntity) ScheduleComponentsEntity(org.apache.nifi.web.api.entity.ScheduleComponentsEntity) DisconnectionCode(org.apache.nifi.cluster.coordination.node.DisconnectionCode) ProcessGroup(org.apache.nifi.groups.ProcessGroup) BulletinQueryDTO(org.apache.nifi.web.api.dto.BulletinQueryDTO) ListIterator(java.util.ListIterator) Date(java.util.Date) ProcessorStatusDTO(org.apache.nifi.web.api.dto.status.ProcessorStatusDTO) RegistryClientEntity(org.apache.nifi.web.api.entity.RegistryClientEntity) SnippetDAO(org.apache.nifi.web.dao.SnippetDAO) StandardFlowComparator(org.apache.nifi.registry.flow.diff.StandardFlowComparator) ControllerConfigurationEntity(org.apache.nifi.web.api.entity.ControllerConfigurationEntity) LabelDTO(org.apache.nifi.web.api.dto.LabelDTO) ControllerConfigurationDTO(org.apache.nifi.web.api.dto.ControllerConfigurationDTO) InstantiatedVersionedRemoteGroupPort(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedRemoteGroupPort) ControllerStatusDTO(org.apache.nifi.web.api.dto.status.ControllerStatusDTO) UpdateRevisionTask(org.apache.nifi.web.revision.UpdateRevisionTask) VersionedComponent(org.apache.nifi.registry.flow.VersionedComponent) Label(org.apache.nifi.controller.label.Label) RevisionClaim(org.apache.nifi.web.revision.RevisionClaim) Authorizable(org.apache.nifi.authorization.resource.Authorizable) ControllerServiceReferencingComponentDTO(org.apache.nifi.web.api.dto.ControllerServiceReferencingComponentDTO) RequiredPermission(org.apache.nifi.components.RequiredPermission) EntityFactory(org.apache.nifi.web.api.dto.EntityFactory) Collection(java.util.Collection) RemoteProcessGroupPortEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupPortEntity) RevisionManager(org.apache.nifi.web.revision.RevisionManager) UUID(java.util.UUID) Snippet(org.apache.nifi.controller.Snippet) PortEntity(org.apache.nifi.web.api.entity.PortEntity) Collectors(java.util.stream.Collectors) ResourceFactory(org.apache.nifi.authorization.resource.ResourceFactory) StateMap(org.apache.nifi.components.state.StateMap) Objects(java.util.Objects) Response(javax.ws.rs.core.Response) ComponentReferenceDTO(org.apache.nifi.web.api.dto.ComponentReferenceDTO) ProcessGroupEntity(org.apache.nifi.web.api.entity.ProcessGroupEntity) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) ConnectionStatusDTO(org.apache.nifi.web.api.dto.status.ConnectionStatusDTO) ReportingTaskDTO(org.apache.nifi.web.api.dto.ReportingTaskDTO) AuditService(org.apache.nifi.admin.service.AuditService) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) ReportingTaskDAO(org.apache.nifi.web.dao.ReportingTaskDAO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) ProcessorNode(org.apache.nifi.controller.ProcessorNode) Bucket(org.apache.nifi.registry.bucket.Bucket) NodeHeartbeat(org.apache.nifi.cluster.coordination.heartbeat.NodeHeartbeat) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) ProcessGroupStatusDTO(org.apache.nifi.web.api.dto.status.ProcessGroupStatusDTO) Group(org.apache.nifi.authorization.Group) Function(java.util.function.Function) FlowRegistry(org.apache.nifi.registry.flow.FlowRegistry) PermissionsDTO(org.apache.nifi.web.api.dto.PermissionsDTO) HashSet(java.util.HashSet) ListingRequestDTO(org.apache.nifi.web.api.dto.ListingRequestDTO) ControllerServiceReferencingComponentEntity(org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentEntity) VersionControlInformationDTO(org.apache.nifi.web.api.dto.VersionControlInformationDTO) ReportingTaskNode(org.apache.nifi.controller.ReportingTaskNode) ValidationResult(org.apache.nifi.components.ValidationResult) ComponentDifferenceDTO(org.apache.nifi.web.api.dto.ComponentDifferenceDTO) Logger(org.slf4j.Logger) RemoteGroupPort(org.apache.nifi.remote.RemoteGroupPort) PropertyHistoryDTO(org.apache.nifi.web.api.dto.PropertyHistoryDTO) FlowFileDTO(org.apache.nifi.web.api.dto.FlowFileDTO) VariableRegistryEntity(org.apache.nifi.web.api.entity.VariableRegistryEntity) VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) IllegalNodeDeletionException(org.apache.nifi.cluster.manager.exception.IllegalNodeDeletionException) DropRequestDTO(org.apache.nifi.web.api.dto.DropRequestDTO) LabelEntity(org.apache.nifi.web.api.entity.LabelEntity) RemoteProcessGroupEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupEntity) NiFiUserUtils(org.apache.nifi.authorization.user.NiFiUserUtils) BulletinRepository(org.apache.nifi.reporting.BulletinRepository) AccessPolicyEntity(org.apache.nifi.web.api.entity.AccessPolicyEntity) NodeDTO(org.apache.nifi.web.api.dto.NodeDTO) Operation(org.apache.nifi.action.Operation) SnippetDTO(org.apache.nifi.web.api.dto.SnippetDTO) Comparator(java.util.Comparator) CounterDTO(org.apache.nifi.web.api.dto.CounterDTO) InstantiatedVersionedComponent(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedComponent) Arrays(java.util.Arrays) StatusHistoryEntity(org.apache.nifi.web.api.entity.StatusHistoryEntity) FlowChangePurgeDetails(org.apache.nifi.action.details.FlowChangePurgeDetails) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ProcessGroupStatusSnapshotDTO(org.apache.nifi.web.api.dto.status.ProcessGroupStatusSnapshotDTO) ControllerServiceDAO(org.apache.nifi.web.dao.ControllerServiceDAO) AuthorizationRequest(org.apache.nifi.authorization.AuthorizationRequest) PropertyDescriptorDTO(org.apache.nifi.web.api.dto.PropertyDescriptorDTO) FunnelDAO(org.apache.nifi.web.dao.FunnelDAO) AuthorizationResult(org.apache.nifi.authorization.AuthorizationResult) TenantEntity(org.apache.nifi.web.api.entity.TenantEntity) ProcessGroupFlowEntity(org.apache.nifi.web.api.entity.ProcessGroupFlowEntity) RootGroupPort(org.apache.nifi.remote.RootGroupPort) BulletinQuery(org.apache.nifi.reporting.BulletinQuery) Connectable(org.apache.nifi.connectable.Connectable) Bulletin(org.apache.nifi.reporting.Bulletin) FunnelDTO(org.apache.nifi.web.api.dto.FunnelDTO) ProcessorStatus(org.apache.nifi.controller.status.ProcessorStatus) HistoryQueryDTO(org.apache.nifi.web.api.dto.action.HistoryQueryDTO) ControllerServiceReferencingComponentsEntity(org.apache.nifi.web.api.entity.ControllerServiceReferencingComponentsEntity) FunnelEntity(org.apache.nifi.web.api.entity.FunnelEntity) AccessPolicyDAO(org.apache.nifi.web.dao.AccessPolicyDAO) ProcessGroupStatus(org.apache.nifi.controller.status.ProcessGroupStatus) History(org.apache.nifi.history.History) AccessPolicySummaryEntity(org.apache.nifi.web.api.entity.AccessPolicySummaryEntity) Set(java.util.Set) BulletinBoardDTO(org.apache.nifi.web.api.dto.BulletinBoardDTO) VersionedFlowCoordinates(org.apache.nifi.registry.flow.VersionedFlowCoordinates) FlowController(org.apache.nifi.controller.FlowController) ProcessorDAO(org.apache.nifi.web.dao.ProcessorDAO) StandardCharsets(java.nio.charset.StandardCharsets) FlowComparisonEntity(org.apache.nifi.web.api.entity.FlowComparisonEntity) ScheduledState(org.apache.nifi.controller.ScheduledState) WebApplicationException(javax.ws.rs.WebApplicationException) ActionEntity(org.apache.nifi.web.api.entity.ActionEntity) DtoFactory(org.apache.nifi.web.api.dto.DtoFactory) RemoteProcessGroupStatusDTO(org.apache.nifi.web.api.dto.status.RemoteProcessGroupStatusDTO) ControllerBulletinsEntity(org.apache.nifi.web.api.entity.ControllerBulletinsEntity) Resource(org.apache.nifi.authorization.Resource) FlowComparator(org.apache.nifi.registry.flow.diff.FlowComparator) StaticDifferenceDescriptor(org.apache.nifi.registry.flow.diff.StaticDifferenceDescriptor) LeaderElectionManager(org.apache.nifi.controller.leader.election.LeaderElectionManager) Counter(org.apache.nifi.controller.Counter) AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) InstantiatedVersionedProcessGroup(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedProcessGroup) TemplateDAO(org.apache.nifi.web.dao.TemplateDAO) ArrayList(java.util.ArrayList) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) ComponentType(org.apache.nifi.reporting.ComponentType) ControllerServiceReference(org.apache.nifi.controller.service.ControllerServiceReference) StandardRevisionClaim(org.apache.nifi.web.revision.StandardRevisionClaim) NodeConnectionState(org.apache.nifi.cluster.coordination.node.NodeConnectionState) AccessPolicyDTO(org.apache.nifi.web.api.dto.AccessPolicyDTO) VersionControlComponentMappingEntity(org.apache.nifi.web.api.entity.VersionControlComponentMappingEntity) RequiredPermissionDTO(org.apache.nifi.web.api.dto.RequiredPermissionDTO) NodeConnectionStatus(org.apache.nifi.cluster.coordination.node.NodeConnectionStatus) LinkedHashSet(java.util.LinkedHashSet) DocumentedTypeDTO(org.apache.nifi.web.api.dto.DocumentedTypeDTO) FlowConfigurationDTO(org.apache.nifi.web.api.dto.FlowConfigurationDTO) ConfiguredComponent(org.apache.nifi.controller.ConfiguredComponent) ProvenanceOptionsDTO(org.apache.nifi.web.api.dto.provenance.ProvenanceOptionsDTO) LabelDAO(org.apache.nifi.web.dao.LabelDAO) InstantiatedVersionedControllerService(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedControllerService) StartVersionControlRequestEntity(org.apache.nifi.web.api.entity.StartVersionControlRequestEntity) ComponentDTO(org.apache.nifi.web.api.dto.ComponentDTO) Authorizer(org.apache.nifi.authorization.Authorizer) NiFiProperties(org.apache.nifi.util.NiFiProperties) ComponentHistoryDTO(org.apache.nifi.web.api.dto.ComponentHistoryDTO) BulletinEntity(org.apache.nifi.web.api.entity.BulletinEntity) VersionedFlowEntity(org.apache.nifi.web.api.entity.VersionedFlowEntity) NodeIdentifier(org.apache.nifi.cluster.protocol.NodeIdentifier) Permissions(org.apache.nifi.registry.authorization.Permissions) PreviousValueDTO(org.apache.nifi.web.api.dto.PreviousValueDTO) ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) LoggerFactory(org.slf4j.LoggerFactory) Port(org.apache.nifi.connectable.Port) ProcessGroupStatusEntity(org.apache.nifi.web.api.entity.ProcessGroupStatusEntity) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) ActivateControllerServicesEntity(org.apache.nifi.web.api.entity.ActivateControllerServicesEntity) UserGroupEntity(org.apache.nifi.web.api.entity.UserGroupEntity) UserGroupDTO(org.apache.nifi.web.api.dto.UserGroupDTO) ConnectionStatusEntity(org.apache.nifi.web.api.entity.ConnectionStatusEntity) JVMDiagnosticsSnapshotDTO(org.apache.nifi.web.api.dto.diagnostics.JVMDiagnosticsSnapshotDTO) ProcessGroupStatusSnapshotEntity(org.apache.nifi.web.api.entity.ProcessGroupStatusSnapshotEntity) DifferenceType(org.apache.nifi.registry.flow.diff.DifferenceType) AccessPolicySummaryDTO(org.apache.nifi.web.api.dto.AccessPolicySummaryDTO) NodeProcessGroupStatusSnapshotDTO(org.apache.nifi.web.api.dto.status.NodeProcessGroupStatusSnapshotDTO) VersionedConnection(org.apache.nifi.registry.flow.VersionedConnection) Template(org.apache.nifi.controller.Template) FlowRegistryClient(org.apache.nifi.registry.flow.FlowRegistryClient) BucketDTO(org.apache.nifi.web.api.dto.BucketDTO) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) ReportingTaskEntity(org.apache.nifi.web.api.entity.ReportingTaskEntity) Predicate(java.util.function.Predicate) Sets(com.google.common.collect.Sets) User(org.apache.nifi.authorization.User) JVMDiagnosticsDTO(org.apache.nifi.web.api.dto.diagnostics.JVMDiagnosticsDTO) SystemDiagnostics(org.apache.nifi.diagnostics.SystemDiagnostics) List(java.util.List) Result(org.apache.nifi.authorization.AuthorizationResult.Result) VersionControlInformation(org.apache.nifi.registry.flow.VersionControlInformation) StatusHistoryDTO(org.apache.nifi.web.api.dto.status.StatusHistoryDTO) HeartbeatMonitor(org.apache.nifi.cluster.coordination.heartbeat.HeartbeatMonitor) Optional(java.util.Optional) Action(org.apache.nifi.action.Action) Funnel(org.apache.nifi.connectable.Funnel) ClusterDTO(org.apache.nifi.web.api.dto.ClusterDTO) VariableEntity(org.apache.nifi.web.api.entity.VariableEntity) HashMap(java.util.HashMap) ConciseEvolvingDifferenceDescriptor(org.apache.nifi.registry.flow.diff.ConciseEvolvingDifferenceDescriptor) ResourceDTO(org.apache.nifi.web.api.dto.ResourceDTO) AffectedComponentDTO(org.apache.nifi.web.api.dto.AffectedComponentDTO) HistoryQuery(org.apache.nifi.history.HistoryQuery) ExpiredRevisionClaimException(org.apache.nifi.web.revision.ExpiredRevisionClaimException) PortStatusDTO(org.apache.nifi.web.api.dto.status.PortStatusDTO) ComparableDataFlow(org.apache.nifi.registry.flow.diff.ComparableDataFlow) ClusterCoordinator(org.apache.nifi.cluster.coordination.ClusterCoordinator) StandardRevisionUpdate(org.apache.nifi.web.revision.StandardRevisionUpdate) ComponentRestrictionPermissionDTO(org.apache.nifi.web.api.dto.ComponentRestrictionPermissionDTO) Validator(org.apache.nifi.components.Validator) PortStatusEntity(org.apache.nifi.web.api.entity.PortStatusEntity) ControllerDTO(org.apache.nifi.web.api.dto.ControllerDTO) ProcessorDiagnosticsDTO(org.apache.nifi.web.api.dto.diagnostics.ProcessorDiagnosticsDTO) ComponentVariableRegistry(org.apache.nifi.registry.ComponentVariableRegistry) FlowDifference(org.apache.nifi.registry.flow.diff.FlowDifference) ConnectionEntity(org.apache.nifi.web.api.entity.ConnectionEntity) UserContextKeys(org.apache.nifi.authorization.UserContextKeys) VersionControlInformationEntity(org.apache.nifi.web.api.entity.VersionControlInformationEntity) DeleteRevisionTask(org.apache.nifi.web.revision.DeleteRevisionTask) Component(org.apache.nifi.action.Component) AccessPolicy(org.apache.nifi.authorization.AccessPolicy) SearchResultsDTO(org.apache.nifi.web.api.dto.search.SearchResultsDTO) RegistryEntity(org.apache.nifi.web.api.entity.RegistryEntity) Collections(java.util.Collections) HashSet(java.util.HashSet) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) ProcessGroupStatusDTO(org.apache.nifi.web.api.dto.status.ProcessGroupStatusDTO) RemoteProcessGroupStatusDTO(org.apache.nifi.web.api.dto.status.RemoteProcessGroupStatusDTO) PermissionsDTO(org.apache.nifi.web.api.dto.PermissionsDTO) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) BulletinEntity(org.apache.nifi.web.api.entity.BulletinEntity) RevisionUpdate(org.apache.nifi.web.revision.RevisionUpdate) StandardRevisionUpdate(org.apache.nifi.web.revision.StandardRevisionUpdate) VersionedProcessGroup(org.apache.nifi.registry.flow.VersionedProcessGroup) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) ProcessGroup(org.apache.nifi.groups.ProcessGroup) InstantiatedVersionedProcessGroup(org.apache.nifi.registry.flow.mapping.InstantiatedVersionedProcessGroup) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) StandardRevisionClaim(org.apache.nifi.web.revision.StandardRevisionClaim) RevisionClaim(org.apache.nifi.web.revision.RevisionClaim) StandardRevisionClaim(org.apache.nifi.web.revision.StandardRevisionClaim) BulletinDTO(org.apache.nifi.web.api.dto.BulletinDTO)

Example 5 with VersionedFlowSnapshot

use of org.apache.nifi.registry.flow.VersionedFlowSnapshot in project nifi by apache.

the class ProcessGroupResource method createProcessGroup.

/**
 * Adds the specified process group.
 *
 * @param httpServletRequest request
 * @param groupId The group id
 * @param requestProcessGroupEntity A processGroupEntity
 * @return A processGroupEntity
 * @throws IOException if the request indicates that the Process Group should be imported from a Flow Registry and NiFi is unable to communicate with the Flow Registry
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/process-groups")
@ApiOperation(value = "Creates a process group", response = ProcessGroupEntity.class, authorizations = { @Authorization(value = "Write - /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 createProcessGroup(@Context final HttpServletRequest httpServletRequest, @ApiParam(value = "The process group id.", required = true) @PathParam("id") final String groupId, @ApiParam(value = "The process group configuration details.", required = true) final ProcessGroupEntity requestProcessGroupEntity) throws IOException {
    if (requestProcessGroupEntity == null || requestProcessGroupEntity.getComponent() == null) {
        throw new IllegalArgumentException("Process group details must be specified.");
    }
    if (requestProcessGroupEntity.getRevision() == null || (requestProcessGroupEntity.getRevision().getVersion() == null || requestProcessGroupEntity.getRevision().getVersion() != 0)) {
        throw new IllegalArgumentException("A revision of 0 must be specified when creating a new Process group.");
    }
    if (requestProcessGroupEntity.getComponent().getId() != null) {
        throw new IllegalArgumentException("Process group ID cannot be specified.");
    }
    final PositionDTO proposedPosition = requestProcessGroupEntity.getComponent().getPosition();
    if (proposedPosition != null) {
        if (proposedPosition.getX() == null || proposedPosition.getY() == null) {
            throw new IllegalArgumentException("The x and y coordinate of the proposed position must be specified.");
        }
    }
    // if the group name isn't specified, ensure the group is being imported from version control
    if (StringUtils.isBlank(requestProcessGroupEntity.getComponent().getName()) && requestProcessGroupEntity.getComponent().getVersionControlInformation() == null) {
        throw new IllegalArgumentException("The group name is required when the group is not imported from version control.");
    }
    if (requestProcessGroupEntity.getComponent().getParentGroupId() != null && !groupId.equals(requestProcessGroupEntity.getComponent().getParentGroupId())) {
        throw new IllegalArgumentException(String.format("If specified, the parent process group id %s must be the same as specified in the URI %s", requestProcessGroupEntity.getComponent().getParentGroupId(), groupId));
    }
    requestProcessGroupEntity.getComponent().setParentGroupId(groupId);
    // Step 1: Ensure that user has write permissions to the Process Group. If not, then immediately fail.
    // Step 2: Retrieve flow from Flow Registry
    // Step 3: Resolve Bundle info
    // Step 4: Update contents of the ProcessGroupDTO passed in to include the components that need to be added.
    // Step 5: If any of the components is a Restricted Component, then we must authorize the user
    // for write access to the RestrictedComponents resource
    // Step 6: Replicate the request or call serviceFacade.updateProcessGroup
    final VersionControlInformationDTO versionControlInfo = requestProcessGroupEntity.getComponent().getVersionControlInformation();
    if (versionControlInfo != null && requestProcessGroupEntity.getVersionedFlowSnapshot() == null) {
        // Step 1: Ensure that user has write permissions to the Process Group. If not, then immediately fail.
        // Step 2: Retrieve flow from Flow Registry
        final VersionedFlowSnapshot flowSnapshot = serviceFacade.getVersionedFlowSnapshot(versionControlInfo, true);
        final Bucket bucket = flowSnapshot.getBucket();
        final VersionedFlow flow = flowSnapshot.getFlow();
        versionControlInfo.setBucketName(bucket.getName());
        versionControlInfo.setFlowName(flow.getName());
        versionControlInfo.setFlowDescription(flow.getDescription());
        versionControlInfo.setRegistryName(serviceFacade.getFlowRegistryName(versionControlInfo.getRegistryId()));
        final VersionedFlowState flowState = flowSnapshot.isLatest() ? VersionedFlowState.UP_TO_DATE : VersionedFlowState.STALE;
        versionControlInfo.setState(flowState.name());
        // Step 3: Resolve Bundle info
        BundleUtils.discoverCompatibleBundles(flowSnapshot.getFlowContents());
        // Step 4: Update contents of the ProcessGroupDTO passed in to include the components that need to be added.
        requestProcessGroupEntity.setVersionedFlowSnapshot(flowSnapshot);
    }
    if (versionControlInfo != null) {
        final VersionedFlowSnapshot flowSnapshot = requestProcessGroupEntity.getVersionedFlowSnapshot();
        serviceFacade.verifyImportProcessGroup(versionControlInfo, flowSnapshot.getFlowContents(), groupId);
    }
    // Step 6: Replicate the request or call serviceFacade.updateProcessGroup
    if (isReplicateRequest()) {
        return replicate(HttpMethod.POST, requestProcessGroupEntity);
    }
    return withWriteLock(serviceFacade, requestProcessGroupEntity, lookup -> {
        final Authorizable processGroup = lookup.getProcessGroup(groupId).getAuthorizable();
        processGroup.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        // Step 5: If any of the components is a Restricted Component, then we must authorize the user
        // for write access to the RestrictedComponents resource
        final VersionedFlowSnapshot versionedFlowSnapshot = requestProcessGroupEntity.getVersionedFlowSnapshot();
        if (versionedFlowSnapshot != null) {
            final Set<ConfigurableComponent> restrictedComponents = FlowRegistryUtils.getRestrictedComponents(versionedFlowSnapshot.getFlowContents());
            restrictedComponents.forEach(restrictedComponent -> {
                final ComponentAuthorizable restrictedComponentAuthorizable = lookup.getConfigurableComponent(restrictedComponent);
                authorizeRestrictions(authorizer, restrictedComponentAuthorizable);
            });
        }
    }, () -> {
        final VersionedFlowSnapshot versionedFlowSnapshot = requestProcessGroupEntity.getVersionedFlowSnapshot();
        if (versionedFlowSnapshot != null) {
            serviceFacade.verifyComponentTypes(versionedFlowSnapshot.getFlowContents());
        }
    }, processGroupEntity -> {
        final ProcessGroupDTO processGroup = processGroupEntity.getComponent();
        // set the processor id as appropriate
        processGroup.setId(generateUuid());
        // ensure the group name comes from the versioned flow
        final VersionedFlowSnapshot flowSnapshot = processGroupEntity.getVersionedFlowSnapshot();
        if (flowSnapshot != null && StringUtils.isNotBlank(flowSnapshot.getFlowContents().getName()) && StringUtils.isBlank(processGroup.getName())) {
            processGroup.setName(flowSnapshot.getFlowContents().getName());
        }
        // create the process group contents
        final Revision revision = getRevision(processGroupEntity, processGroup.getId());
        ProcessGroupEntity entity = serviceFacade.createProcessGroup(revision, groupId, processGroup);
        if (flowSnapshot != null) {
            final RevisionDTO revisionDto = entity.getRevision();
            final String newGroupId = entity.getComponent().getId();
            final Revision newGroupRevision = new Revision(revisionDto.getVersion(), revisionDto.getClientId(), newGroupId);
            // We don't want the Process Group's position to be updated because we want to keep the position where the user
            // placed the Process Group. However, we do want to use the name of the Process Group that is in the Flow Contents.
            // To accomplish this, we call updateProcessGroupContents() passing 'true' for the updateSettings flag but null out the position.
            flowSnapshot.getFlowContents().setPosition(null);
            entity = serviceFacade.updateProcessGroupContents(NiFiUserUtils.getNiFiUser(), newGroupRevision, newGroupId, versionControlInfo, flowSnapshot, getIdGenerationSeed().orElse(null), false, true, true);
        }
        populateRemainingProcessGroupEntityContent(entity);
        // generate a 201 created response
        String uri = entity.getUri();
        return generateCreatedResponse(URI.create(uri), entity).build();
    });
}
Also used : ComponentAuthorizable(org.apache.nifi.authorization.ComponentAuthorizable) ProcessGroupEntity(org.apache.nifi.web.api.entity.ProcessGroupEntity) RemoteProcessGroupEntity(org.apache.nifi.web.api.entity.RemoteProcessGroupEntity) VersionedFlow(org.apache.nifi.registry.flow.VersionedFlow) ConfigurableComponent(org.apache.nifi.components.ConfigurableComponent) PositionDTO(org.apache.nifi.web.api.dto.PositionDTO) RevisionDTO(org.apache.nifi.web.api.dto.RevisionDTO) VersionControlInformationDTO(org.apache.nifi.web.api.dto.VersionControlInformationDTO) Revision(org.apache.nifi.web.Revision) Bucket(org.apache.nifi.registry.bucket.Bucket) VersionedFlowSnapshot(org.apache.nifi.registry.flow.VersionedFlowSnapshot) VersionedFlowState(org.apache.nifi.registry.flow.VersionedFlowState) 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) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

VersionedFlowSnapshot (org.apache.nifi.registry.flow.VersionedFlowSnapshot)38 VersionedFlowSnapshotMetadata (org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata)18 VersionedProcessGroup (org.apache.nifi.registry.flow.VersionedProcessGroup)16 VersionedFlow (org.apache.nifi.registry.flow.VersionedFlow)15 Bucket (org.apache.nifi.registry.bucket.Bucket)12 IOException (java.io.IOException)11 Date (java.util.Date)11 Test (org.junit.Test)11 ApiOperation (io.swagger.annotations.ApiOperation)8 ApiResponses (io.swagger.annotations.ApiResponses)8 Consumes (javax.ws.rs.Consumes)8 Path (javax.ws.rs.Path)8 Produces (javax.ws.rs.Produces)8 Authorizable (org.apache.nifi.authorization.resource.Authorizable)8 VersionedFlowState (org.apache.nifi.registry.flow.VersionedFlowState)8 RevisionDTO (org.apache.nifi.web.api.dto.RevisionDTO)8 VersionControlInformationDTO (org.apache.nifi.web.api.dto.VersionControlInformationDTO)8 HashMap (java.util.HashMap)7 NiFiRegistryException (org.apache.nifi.registry.client.NiFiRegistryException)7 Collections (java.util.Collections)6