use of org.apache.nifi.authorization.Authorizer in project nifi by apache.
the class EncryptedWriteAheadProvenanceRepository method initialize.
/**
* This method initializes the repository. It first builds the key provider and event encryptor
* from the config values, then creates the encrypted record writer and reader, then delegates
* back to the superclass for the common implementation.
*
* @param eventReporter the event reporter
* @param authorizer the authorizer
* @param resourceFactory the authorizable factory
* @param idLookup the lookup provider
* @throws IOException if there is an error initializing this repository
*/
@Override
public synchronized void initialize(final EventReporter eventReporter, final Authorizer authorizer, final ProvenanceAuthorizableFactory resourceFactory, final IdentifierLookup idLookup) throws IOException {
// Initialize the encryption-specific fields
ProvenanceEventEncryptor provenanceEventEncryptor;
if (getConfig().supportsEncryption()) {
try {
KeyProvider keyProvider;
if (KeyProviderFactory.requiresMasterKey(getConfig().getKeyProviderImplementation())) {
SecretKey masterKey = getMasterKey();
keyProvider = buildKeyProvider(masterKey);
} else {
keyProvider = buildKeyProvider();
}
provenanceEventEncryptor = new AESProvenanceEventEncryptor();
provenanceEventEncryptor.initialize(keyProvider);
} catch (KeyManagementException e) {
String msg = "Encountered an error building the key provider";
logger.error(msg, e);
throw new IOException(msg, e);
}
} else {
throw new IOException("The provided configuration does not support a encrypted repository");
}
// Build a factory using lambda which injects the encryptor
final RecordWriterFactory recordWriterFactory = (file, idGenerator, compressed, createToc) -> {
try {
final TocWriter tocWriter = createToc ? new StandardTocWriter(TocUtil.getTocFile(file), false, false) : null;
return new EncryptedSchemaRecordWriter(file, idGenerator, tocWriter, compressed, BLOCK_SIZE, idLookup, provenanceEventEncryptor, getConfig().getDebugFrequency());
} catch (EncryptionException e) {
logger.error("Encountered an error building the schema record writer factory: ", e);
throw new IOException(e);
}
};
// Build a factory using lambda which injects the encryptor
final EventFileManager fileManager = new EventFileManager();
final RecordReaderFactory recordReaderFactory = (file, logs, maxChars) -> {
fileManager.obtainReadLock(file);
try {
EncryptedSchemaRecordReader tempReader = (EncryptedSchemaRecordReader) RecordReaders.newRecordReader(file, logs, maxChars);
tempReader.setProvenanceEventEncryptor(provenanceEventEncryptor);
return tempReader;
} finally {
fileManager.releaseReadLock(file);
}
};
// Delegate the init to the parent impl
super.init(recordWriterFactory, recordReaderFactory, eventReporter, authorizer, resourceFactory);
}
use of org.apache.nifi.authorization.Authorizer in project nifi by apache.
the class SnippetResource method deleteSnippet.
/**
* Removes the specified snippet.
*
* @param httpServletRequest request
* @param snippetId The id of the snippet to remove.
* @return A entity containing the client id and an updated revision.
*/
@DELETE
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(value = "Deletes the components in a snippet and discards the snippet", response = SnippetEntity.class, authorizations = { @Authorization(value = "Write - /{component-type}/{uuid} - For each component in the Snippet and their descendant components"), @Authorization(value = "Write - Parent Process Group - /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 deleteSnippet(@Context final HttpServletRequest httpServletRequest, @ApiParam(value = "The snippet id.", required = true) @PathParam("id") final String snippetId) {
if (isReplicateRequest()) {
return replicate(HttpMethod.DELETE);
}
final ComponentEntity requestEntity = new ComponentEntity();
requestEntity.setId(snippetId);
// get the revision from this snippet
final Set<Revision> requestRevisions = serviceFacade.getRevisionsFromSnippet(snippetId);
return withWriteLock(serviceFacade, requestEntity, requestRevisions, lookup -> {
// ensure write permission to every component in the snippet excluding referenced services
final SnippetAuthorizable snippet = lookup.getSnippet(snippetId);
authorizeSnippet(snippet, authorizer, lookup, RequestAction.WRITE, true, false);
// ensure write permission to the parent process group
snippet.getParentProcessGroup().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
}, () -> serviceFacade.verifyDeleteSnippet(snippetId, requestRevisions.stream().map(rev -> rev.getComponentId()).collect(Collectors.toSet())), (revisions, entity) -> {
// delete the specified snippet
final SnippetEntity snippetEntity = serviceFacade.deleteSnippet(revisions, entity.getId());
return generateOkResponse(snippetEntity).build();
});
}
use of org.apache.nifi.authorization.Authorizer in project nifi by apache.
the class SnippetResource method updateSnippet.
/**
* Move's the components in this Snippet into a new Process Group.
*
* @param httpServletRequest request
* @param snippetId The id of the snippet.
* @param requestSnippetEntity A snippetEntity
* @return A snippetEntity
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
@ApiOperation(value = "Move's the components in this Snippet into a new Process Group and discards the snippet", response = SnippetEntity.class, authorizations = { @Authorization(value = "Write Process Group - /process-groups/{uuid}"), @Authorization(value = "Write - /{component-type}/{uuid} - For each component in the Snippet and their descendant components") })
@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 updateSnippet(@Context HttpServletRequest httpServletRequest, @ApiParam(value = "The snippet id.", required = true) @PathParam("id") String snippetId, @ApiParam(value = "The snippet configuration details.", required = true) final SnippetEntity requestSnippetEntity) {
if (requestSnippetEntity == null || requestSnippetEntity.getSnippet() == null) {
throw new IllegalArgumentException("Snippet details must be specified.");
}
// ensure the ids are the same
final SnippetDTO requestSnippetDTO = requestSnippetEntity.getSnippet();
if (!snippetId.equals(requestSnippetDTO.getId())) {
throw new IllegalArgumentException(String.format("The snippet id (%s) in the request body does not equal the " + "snippet id of the requested resource (%s).", requestSnippetDTO.getId(), snippetId));
}
if (isReplicateRequest()) {
return replicate(HttpMethod.PUT, requestSnippetEntity);
}
// get the revision from this snippet
final Set<Revision> requestRevisions = serviceFacade.getRevisionsFromSnippet(snippetId);
return withWriteLock(serviceFacade, requestSnippetEntity, requestRevisions, lookup -> {
// ensure write access to the target process group
if (requestSnippetDTO.getParentGroupId() != null) {
lookup.getProcessGroup(requestSnippetDTO.getParentGroupId()).getAuthorizable().authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
}
// ensure write permission to every component in the snippet excluding referenced services
final SnippetAuthorizable snippet = lookup.getSnippet(snippetId);
authorizeSnippet(snippet, authorizer, lookup, RequestAction.WRITE, false, false);
}, () -> serviceFacade.verifyUpdateSnippet(requestSnippetDTO, requestRevisions.stream().map(rev -> rev.getComponentId()).collect(Collectors.toSet())), (revisions, snippetEntity) -> {
// update the snippet
final SnippetEntity entity = serviceFacade.updateSnippet(revisions, snippetEntity.getSnippet());
populateRemainingSnippetEntityContent(entity);
return generateOkResponse(entity).build();
});
}
use of org.apache.nifi.authorization.Authorizer in project nifi by apache.
the class VersionsResource method initiateVersionControlUpdate.
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("update-requests/process-groups/{id}")
@ApiOperation(value = "Initiate the Update Request of a Process Group with the given ID", response = VersionedFlowUpdateRequestEntity.class, notes = "For a Process Group that is already under Version Control, this will initiate the action of changing " + "from a specific version of the flow in the Flow Registry to a different version of the flow. This can be a lengthy " + "process, as it will stop any Processors and disable any Controller Services necessary to perform the action and then restart them. As a result, " + "the endpoint will immediately return a VersionedFlowUpdateRequestEntity, and the process of updating the flow will occur " + "asynchronously in the background. The client may then periodically poll the status of the request by issuing a GET request to " + "/versions/update-requests/{requestId}. Once the request is completed, the client is expected to issue a DELETE request to " + "/versions/update-requests/{requestId}. " + NON_GUARANTEED_ENDPOINT, authorizations = { @Authorization(value = "Read - /process-groups/{uuid}"), @Authorization(value = "Write - /process-groups/{uuid}"), @Authorization(value = "Read - /{component-type}/{uuid} - For all encapsulated components"), @Authorization(value = "Write - /{component-type}/{uuid} - For all encapsulated components"), @Authorization(value = "Write - if the template contains any restricted components - /restricted-components") })
@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 initiateVersionControlUpdate(@ApiParam("The process group id.") @PathParam("id") final String groupId, @ApiParam(value = "The controller service configuration details.", required = true) final VersionControlInformationEntity requestEntity) {
// Verify the request
final RevisionDTO revisionDto = requestEntity.getProcessGroupRevision();
if (revisionDto == null) {
throw new IllegalArgumentException("Process Group Revision must be specified");
}
final VersionControlInformationDTO requestVersionControlInfoDto = requestEntity.getVersionControlInformation();
if (requestVersionControlInfoDto == null) {
throw new IllegalArgumentException("Version Control Information must be supplied.");
}
if (requestVersionControlInfoDto.getGroupId() == null) {
throw new IllegalArgumentException("The Process Group ID must be supplied.");
}
if (!requestVersionControlInfoDto.getGroupId().equals(groupId)) {
throw new IllegalArgumentException("The Process Group ID in the request body does not match the Process Group ID of the requested resource.");
}
if (requestVersionControlInfoDto.getBucketId() == null) {
throw new IllegalArgumentException("The Bucket ID must be supplied.");
}
if (requestVersionControlInfoDto.getFlowId() == null) {
throw new IllegalArgumentException("The Flow ID must be supplied.");
}
if (requestVersionControlInfoDto.getRegistryId() == null) {
throw new IllegalArgumentException("The Registry ID must be supplied.");
}
if (requestVersionControlInfoDto.getVersion() == null) {
throw new IllegalArgumentException("The Version of the flow must be supplied.");
}
// We will perform the updating of the Versioned Flow in a background thread because it can be a long-running process.
// In order to do this, we will need some parameters that are only available as Thread-Local variables to the current
// thread, so we will gather the values for these parameters up front.
final boolean replicateRequest = isReplicateRequest();
final ComponentLifecycle componentLifecycle = replicateRequest ? clusterComponentLifecycle : localComponentLifecycle;
final NiFiUser user = NiFiUserUtils.getNiFiUser();
// Workflow for this process:
// 0. Obtain the versioned flow snapshot to use for the update
// a. Contact registry to download the desired version.
// b. Get Variable Registry of this Process Group and all ancestor groups
// c. Perform diff to find any new variables
// d. Get Variable Registry of any child Process Group in the versioned flow
// e. Perform diff to find any new variables
// f. Prompt user to fill in values for all new variables
// 1. Determine which components would be affected (and are enabled/running)
// a. Component itself is modified in some way, other than position changing.
// b. Source and Destination of any Connection that is modified.
// c. Any Processor or Controller Service that references a Controller Service that is modified.
// 2. Verify READ and WRITE permissions for user, for every component.
// 3. Verify that all components in the snapshot exist on all nodes (i.e., the NAR exists)?
// 4. Verify that Process Group is already under version control. If not, must start Version Control instead of updateFlow
// 5. Verify that Process Group is not 'dirty'.
// 6. Stop all Processors, Funnels, Ports that are affected.
// 7. Wait for all of the components to finish stopping.
// 8. Disable all Controller Services that are affected.
// 9. Wait for all Controller Services to finish disabling.
// 10. Ensure that if any connection was deleted, 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. Checking ports & connections could be done before
// stopping everything, but removal of Connections cannot.
// 11. Update variable registry to include new variables
// (only new variables so don't have to worry about affected components? Or do we need to in case a processor
// is already referencing the variable? In which case we need to include the affected components above in the
// Set of affected components before stopping/disabling.).
// 12. Update components in the Process Group; update Version Control Information.
// 13. Re-Enable all affected Controller Services that were not removed.
// 14. Re-Start all Processors, Funnels, Ports that are affected and not removed.
// Step 0: Get the Versioned Flow Snapshot from the Flow Registry
final VersionedFlowSnapshot flowSnapshot = serviceFacade.getVersionedFlowSnapshot(requestEntity.getVersionControlInformation(), true);
// The flow in the registry may not contain the same versions of components that we have in our flow. As a result, we need to update
// the flow snapshot to contain compatible bundles.
BundleUtils.discoverCompatibleBundles(flowSnapshot.getFlowContents());
// Step 1: Determine which components will be affected by updating the version
final Set<AffectedComponentEntity> affectedComponents = serviceFacade.getComponentsAffectedByVersionChange(groupId, flowSnapshot, user);
// build a request wrapper
final InitiateChangeFlowVersionRequestWrapper requestWrapper = new InitiateChangeFlowVersionRequestWrapper(requestEntity, componentLifecycle, getAbsolutePath(), affectedComponents, replicateRequest, flowSnapshot);
final Revision requestRevision = getRevision(requestEntity.getProcessGroupRevision(), groupId);
return withWriteLock(serviceFacade, requestWrapper, requestRevision, lookup -> {
// Step 2: Verify READ and WRITE permissions for user, for every component.
final ProcessGroupAuthorizable groupAuthorizable = lookup.getProcessGroup(groupId);
authorizeProcessGroup(groupAuthorizable, authorizer, lookup, RequestAction.READ, true, false, true, true);
authorizeProcessGroup(groupAuthorizable, authorizer, lookup, RequestAction.WRITE, true, false, true, true);
final VersionedProcessGroup groupContents = flowSnapshot.getFlowContents();
final Set<ConfigurableComponent> restrictedComponents = FlowRegistryUtils.getRestrictedComponents(groupContents);
restrictedComponents.forEach(restrictedComponent -> {
final ComponentAuthorizable restrictedComponentAuthorizable = lookup.getConfigurableComponent(restrictedComponent);
authorizeRestrictions(authorizer, restrictedComponentAuthorizable);
});
}, () -> {
// Step 3: Verify that all components in the snapshot exist on all nodes
// Step 4: Verify that Process Group is already under version control. If not, must start Version Control instead of updating flow
// Step 5: Verify that Process Group is not 'dirty'
serviceFacade.verifyCanUpdate(groupId, flowSnapshot, false, true);
}, (revision, wrapper) -> {
final String idGenerationSeed = getIdGenerationSeed().orElse(null);
// Create an asynchronous request that will occur in the background, because this request may
// result in stopping components, which can take an indeterminate amount of time.
final String requestId = UUID.randomUUID().toString();
final AsynchronousWebRequest<VersionControlInformationEntity> request = new StandardAsynchronousWebRequest<>(requestId, groupId, user, "Stopping Affected Processors");
// Submit the request to be performed in the background
final Consumer<AsynchronousWebRequest<VersionControlInformationEntity>> updateTask = vcur -> {
try {
final VersionControlInformationEntity updatedVersionControlEntity = updateFlowVersion(groupId, wrapper.getComponentLifecycle(), wrapper.getExampleUri(), wrapper.getAffectedComponents(), user, wrapper.isReplicateRequest(), revision, wrapper.getVersionControlInformationEntity(), wrapper.getFlowSnapshot(), request, idGenerationSeed, true, true);
vcur.markComplete(updatedVersionControlEntity);
} catch (final ResumeFlowException rfe) {
// Treat ResumeFlowException differently because we don't want to include a message that we couldn't update the flow
// since in this case the flow was successfully updated - we just couldn't re-enable the components.
logger.error(rfe.getMessage(), rfe);
vcur.setFailureReason(rfe.getMessage());
} catch (final Exception e) {
logger.error("Failed to update flow to new version", e);
vcur.setFailureReason("Failed to update flow to new version due to " + e);
}
};
requestManager.submitRequest("update-requests", requestId, request, updateTask);
// Generate the response.
final VersionedFlowUpdateRequestDTO updateRequestDto = new VersionedFlowUpdateRequestDTO();
updateRequestDto.setComplete(request.isComplete());
updateRequestDto.setFailureReason(request.getFailureReason());
updateRequestDto.setLastUpdated(request.getLastUpdated());
updateRequestDto.setProcessGroupId(groupId);
updateRequestDto.setRequestId(requestId);
updateRequestDto.setUri(generateResourceUri("versions", "update-requests", requestId));
updateRequestDto.setPercentCompleted(request.getPercentComplete());
updateRequestDto.setState(request.getState());
final VersionedFlowUpdateRequestEntity updateRequestEntity = new VersionedFlowUpdateRequestEntity();
final RevisionDTO groupRevision = serviceFacade.getProcessGroup(groupId).getRevision();
updateRequestEntity.setProcessGroupRevision(groupRevision);
updateRequestEntity.setRequest(updateRequestDto);
return generateOkResponse(updateRequestEntity).build();
});
}
use of org.apache.nifi.authorization.Authorizer in project nifi by apache.
the class VersionsResource method initiateRevertFlowVersion.
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("revert-requests/process-groups/{id}")
@ApiOperation(value = "Initiate the Revert Request of a Process Group with the given ID", response = VersionedFlowUpdateRequestEntity.class, notes = "For a Process Group that is already under Version Control, this will initiate the action of reverting " + "any local changes that have been made to the Process Group since it was last synchronized with the Flow Registry. This will result in the " + "flow matching the Versioned Flow that exists in the Flow Registry. This can be a lengthy " + "process, as it will stop any Processors and disable any Controller Services necessary to perform the action and then restart them. As a result, " + "the endpoint will immediately return a VersionedFlowUpdateRequestEntity, and the process of updating the flow will occur " + "asynchronously in the background. The client may then periodically poll the status of the request by issuing a GET request to " + "/versions/revert-requests/{requestId}. Once the request is completed, the client is expected to issue a DELETE request to " + "/versions/revert-requests/{requestId}. " + NON_GUARANTEED_ENDPOINT, authorizations = { @Authorization(value = "Read - /process-groups/{uuid}"), @Authorization(value = "Write - /process-groups/{uuid}"), @Authorization(value = "Read - /{component-type}/{uuid} - For all encapsulated components"), @Authorization(value = "Write - /{component-type}/{uuid} - For all encapsulated components"), @Authorization(value = "Write - if the template contains any restricted components - /restricted-components") })
@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 initiateRevertFlowVersion(@ApiParam("The process group id.") @PathParam("id") final String groupId, @ApiParam(value = "The controller service configuration details.", required = true) final VersionControlInformationEntity requestEntity) throws IOException {
// Verify the request
final RevisionDTO revisionDto = requestEntity.getProcessGroupRevision();
if (revisionDto == null) {
throw new IllegalArgumentException("Process Group Revision must be specified");
}
final VersionControlInformationDTO requestVersionControlInfoDto = requestEntity.getVersionControlInformation();
if (requestVersionControlInfoDto == null) {
throw new IllegalArgumentException("Version Control Information must be supplied.");
}
if (requestVersionControlInfoDto.getGroupId() == null) {
throw new IllegalArgumentException("The Process Group ID must be supplied.");
}
if (!requestVersionControlInfoDto.getGroupId().equals(groupId)) {
throw new IllegalArgumentException("The Process Group ID in the request body does not match the Process Group ID of the requested resource.");
}
if (requestVersionControlInfoDto.getBucketId() == null) {
throw new IllegalArgumentException("The Bucket ID must be supplied.");
}
if (requestVersionControlInfoDto.getFlowId() == null) {
throw new IllegalArgumentException("The Flow ID must be supplied.");
}
if (requestVersionControlInfoDto.getRegistryId() == null) {
throw new IllegalArgumentException("The Registry ID must be supplied.");
}
if (requestVersionControlInfoDto.getVersion() == null) {
throw new IllegalArgumentException("The Version of the flow must be supplied.");
}
// We will perform the updating of the Versioned Flow in a background thread because it can be a long-running process.
// In order to do this, we will need some parameters that are only available as Thread-Local variables to the current
// thread, so we will gather the values for these parameters up front.
final boolean replicateRequest = isReplicateRequest();
final ComponentLifecycle componentLifecycle = replicateRequest ? clusterComponentLifecycle : localComponentLifecycle;
final NiFiUser user = NiFiUserUtils.getNiFiUser();
// Step 0: Get the Versioned Flow Snapshot from the Flow Registry
final VersionedFlowSnapshot flowSnapshot = serviceFacade.getVersionedFlowSnapshot(requestEntity.getVersionControlInformation(), true);
// The flow in the registry may not contain the same versions of components that we have in our flow. As a result, we need to update
// the flow snapshot to contain compatible bundles.
BundleUtils.discoverCompatibleBundles(flowSnapshot.getFlowContents());
// Step 1: Determine which components will be affected by updating the version
final Set<AffectedComponentEntity> affectedComponents = serviceFacade.getComponentsAffectedByVersionChange(groupId, flowSnapshot, user);
// build a request wrapper
final InitiateChangeFlowVersionRequestWrapper requestWrapper = new InitiateChangeFlowVersionRequestWrapper(requestEntity, componentLifecycle, getAbsolutePath(), affectedComponents, replicateRequest, flowSnapshot);
final Revision requestRevision = getRevision(requestEntity.getProcessGroupRevision(), groupId);
return withWriteLock(serviceFacade, requestWrapper, requestRevision, lookup -> {
// Step 2: Verify READ and WRITE permissions for user, for every component.
final ProcessGroupAuthorizable groupAuthorizable = lookup.getProcessGroup(groupId);
authorizeProcessGroup(groupAuthorizable, authorizer, lookup, RequestAction.READ, true, false, true, true);
authorizeProcessGroup(groupAuthorizable, authorizer, lookup, RequestAction.WRITE, true, false, true, true);
final VersionedProcessGroup groupContents = flowSnapshot.getFlowContents();
final Set<ConfigurableComponent> restrictedComponents = FlowRegistryUtils.getRestrictedComponents(groupContents);
restrictedComponents.forEach(restrictedComponent -> {
final ComponentAuthorizable restrictedComponentAuthorizable = lookup.getConfigurableComponent(restrictedComponent);
authorizeRestrictions(authorizer, restrictedComponentAuthorizable);
});
}, () -> {
// Step 3: Verify that all components in the snapshot exist on all nodes
// Step 4: Verify that Process Group is already under version control. If not, must start Version Control instead of updating flow
serviceFacade.verifyCanRevertLocalModifications(groupId, flowSnapshot);
}, (revision, wrapper) -> {
final VersionControlInformationEntity versionControlInformationEntity = wrapper.getVersionControlInformationEntity();
final VersionControlInformationDTO versionControlInformationDTO = versionControlInformationEntity.getVersionControlInformation();
// Ensure that the information passed in is correct
final VersionControlInformationEntity currentVersionEntity = serviceFacade.getVersionControlInformation(groupId);
if (currentVersionEntity == null) {
throw new IllegalStateException("Process Group cannot be reverted to the previous version of the flow because Process Group is not under Version Control.");
}
final VersionControlInformationDTO currentVersion = currentVersionEntity.getVersionControlInformation();
if (!currentVersion.getBucketId().equals(versionControlInformationDTO.getBucketId())) {
throw new IllegalArgumentException("The Version Control Information provided does not match the flow that the Process Group is currently synchronized with.");
}
if (!currentVersion.getFlowId().equals(versionControlInformationDTO.getFlowId())) {
throw new IllegalArgumentException("The Version Control Information provided does not match the flow that the Process Group is currently synchronized with.");
}
if (!currentVersion.getRegistryId().equals(versionControlInformationDTO.getRegistryId())) {
throw new IllegalArgumentException("The Version Control Information provided does not match the flow that the Process Group is currently synchronized with.");
}
if (!currentVersion.getVersion().equals(versionControlInformationDTO.getVersion())) {
throw new IllegalArgumentException("The Version Control Information provided does not match the flow that the Process Group is currently synchronized with.");
}
final String idGenerationSeed = getIdGenerationSeed().orElse(null);
// Create an asynchronous request that will occur in the background, because this request may
// result in stopping components, which can take an indeterminate amount of time.
final String requestId = UUID.randomUUID().toString();
final AsynchronousWebRequest<VersionControlInformationEntity> request = new StandardAsynchronousWebRequest<>(requestId, groupId, user, "Stopping Affected Processors");
// Submit the request to be performed in the background
final Consumer<AsynchronousWebRequest<VersionControlInformationEntity>> updateTask = vcur -> {
try {
final VersionControlInformationEntity updatedVersionControlEntity = updateFlowVersion(groupId, wrapper.getComponentLifecycle(), wrapper.getExampleUri(), wrapper.getAffectedComponents(), user, wrapper.isReplicateRequest(), revision, versionControlInformationEntity, wrapper.getFlowSnapshot(), request, idGenerationSeed, false, true);
vcur.markComplete(updatedVersionControlEntity);
} catch (final ResumeFlowException rfe) {
// Treat ResumeFlowException differently because we don't want to include a message that we couldn't update the flow
// since in this case the flow was successfully updated - we just couldn't re-enable the components.
logger.error(rfe.getMessage(), rfe);
vcur.setFailureReason(rfe.getMessage());
} catch (final Exception e) {
logger.error("Failed to update flow to new version", e);
vcur.setFailureReason("Failed to update flow to new version due to " + e.getMessage());
}
};
requestManager.submitRequest("revert-requests", requestId, request, updateTask);
// Generate the response.
final VersionedFlowUpdateRequestDTO updateRequestDto = new VersionedFlowUpdateRequestDTO();
updateRequestDto.setComplete(request.isComplete());
updateRequestDto.setFailureReason(request.getFailureReason());
updateRequestDto.setLastUpdated(request.getLastUpdated());
updateRequestDto.setProcessGroupId(groupId);
updateRequestDto.setRequestId(requestId);
updateRequestDto.setState(request.getState());
updateRequestDto.setPercentCompleted(request.getPercentComplete());
updateRequestDto.setUri(generateResourceUri("versions", "revert-requests", requestId));
final VersionedFlowUpdateRequestEntity updateRequestEntity = new VersionedFlowUpdateRequestEntity();
final RevisionDTO groupRevision = serviceFacade.getProcessGroup(groupId).getRevision();
updateRequestEntity.setProcessGroupRevision(groupRevision);
updateRequestEntity.setRequest(updateRequestDto);
return generateOkResponse(updateRequestEntity).build();
});
}
Aggregations