You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by bb...@apache.org on 2023/04/19 17:27:53 UTC
[nifi] branch main updated: NIFI-11327 Add Export/Import All - NiFi CLI - NiFi Registry (#7092)
This is an automated email from the ASF dual-hosted git repository.
bbende pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi.git
The following commit(s) were added to refs/heads/main by this push:
new 3df8c9d2ac NIFI-11327 Add Export/Import All - NiFi CLI - NiFi Registry (#7092)
3df8c9d2ac is described below
commit 3df8c9d2acd6af77b41f5464b1bd2f2adc0ce2b6
Author: timeabarna <38...@users.noreply.github.com>
AuthorDate: Wed Apr 19 19:27:41 2023 +0200
NIFI-11327 Add Export/Import All - NiFi CLI - NiFi Registry (#7092)
* NIFI-11327 Add Export/Import All - NiFi CLI - NiFi Registry
* NIFI-11327 Addressing review comment, updating storage location, improving serialization
* NIFI-11327 Addressing review comments, updating Rest endpoints and storage location handling
* NIFI-11327 Restoring EventType to its original version
* NIFI-11327 Addressing review comments changing skipExisting, updating documentation, adding some more error handling
---
nifi-docs/src/main/asciidoc/toolkit-guide.adoc | 80 +++++
.../apache/nifi/registry/client/BucketClient.java | 10 +
.../nifi/registry/client/FlowSnapshotClient.java | 15 +
.../registry/client/impl/JerseyBucketClient.java | 20 +-
.../client/impl/JerseyFlowSnapshotClient.java | 10 +-
.../nifi/registry/web/api/BucketFlowResource.java | 16 +-
.../nifi/registry/web/api/BucketResource.java | 8 +-
.../nifi/registry/web/service/ServiceFacade.java | 2 +
.../web/service/StandardServiceFacade.java | 37 ++-
.../web/api/SecureNiFiRegistryClientIT.java | 17 ++
.../toolkit/cli/impl/command/CommandOption.java | 5 +-
.../command/registry/NiFiRegistryCommandGroup.java | 4 +
.../impl/command/registry/flow/ExportAllFlows.java | 205 +++++++++++++
.../impl/command/registry/flow/ImportAllFlows.java | 337 +++++++++++++++++++++
.../registry/VersionedFlowSnapshotsResult.java | 79 +++++
15 files changed, 818 insertions(+), 27 deletions(-)
diff --git a/nifi-docs/src/main/asciidoc/toolkit-guide.adoc b/nifi-docs/src/main/asciidoc/toolkit-guide.adoc
index f22029e75a..303548cc67 100644
--- a/nifi-docs/src/main/asciidoc/toolkit-guide.adoc
+++ b/nifi-docs/src/main/asciidoc/toolkit-guide.adoc
@@ -171,6 +171,8 @@ The following are available commands:
registry get-access-token
registry get-access-token-spnego
registry logout-access-token
+ registry export-all-flows
+ registry import-all-flows
session keys
session show
session get
@@ -768,6 +770,84 @@ This command migrates nifi.properties back from AWS_KMS to AES_GCM protection sc
-v
----
+[export_import_all_flows]
+=== Export All Flows
+You can use the `export-all-flows` to perform the following tasks:
+
+* List all the buckets
+* For each bucket, list all flows
+* For each flow, list all versions
+* Export each version into a provided directory
+
+Running the command requires an `--outputDirectory` parameter. The directory must exist and permissions correctly set.
+
+=== Import All Flows
+You can use the `import-all-flows` to perform the following tasks:
+
+* List all files, representing a flow version, from a directory created by export-all-flows
+* Create all the corresponding buckets
+* Create all the corresponding flows
+* Import all the corresponding flow versions
+
+Running the command requires 2 parameters:
+
+* `--input` parameter represents a directory to read files from
+* `--skipExisting` optional parameter, configuring how to handle existing flow and flow version creation.
+If provided the flow and flow version creation will be skipped regardless of there are missing flow versions.
+If not provided the missing flow versions will be created.
+
+=== Usage
+The input source for an import-all-flows command must be created by an export-all-flows command.
+To avoid migration conflicts, no modification should be performed in the NiFi Registry during this activity.
+Buckets and flows with the same name are considered equal.
+
+* Export all flow versions:
+
+ ./bin/cli.sh registry export-all-flows -u http://localhost:18080 --outputDirectory "/my_dir/flow_exports"
+
+* Import all flow versions:
+
+ ./bin/cli.sh registry import-all-flows -u http://localhost:18080 --input "/my_dir/flow_exports" --skipExisting
+
+=== Expected behaviour
+=== Use case 1: reconfiguring an existing NiFi Registry
+
+NiFi is connecting to NiFi Registry, the NiFi Registry does not change, only its configuration.
+All the data will be created.
+
+1. Export versions:
+
+ ./bin/cli.sh registry export-all-flows -u http://localhost:18080 --outputDirectory "/my_dir/flow_exports"
+
+2. Stop registry
+
+3. Switch provider
+
+4. Start registry
+
+5. Import versions
+
+ ./bin/cli.sh registry import-all-flows -u http://localhost:18080 --input "/my_dir/flow_exports" --skipExisting
+
+
+=== Use case 2: data replication
+
+NiFi_1 is connecting to NiFi Registry_1 and NiFi_2 is connecting to NiFi Registry_2.
+
+For disaster recovery purposes the data from NiFi Registry_1 needs to be periodically replicated to NiFi Registry_2 via a scheduled job.
+
+The initial version of Nifi Registry_2 needs to be created by this tool.
+
+The missing buckets, flows and versions will be created. If bucket and flow exist the missing versions will be created.
+
+1. Export versions:
+
+ ./bin/cli.sh registry export-all-flows -u http://nifi-registry-1:18080 --outputDirectory "/my_dir/flow_exports"
+
+2. Import versions:
+
+ ./bin/cli.sh registry import-all-flows -u http://nifi-registry-2:18080 --input "/my_dir/flow_exports"
+
[[tls_toolkit]]
== TLS Toolkit
In order to facilitate the secure setup of NiFi, you can use the `tls-toolkit` command line utility to automatically generate the required keystores, truststore, and relevant configuration files. This is especially useful for securing multiple NiFi nodes, which can be a tedious and error-prone process.
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/BucketClient.java b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/BucketClient.java
index 7bc256a487..1f715687fd 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/BucketClient.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/BucketClient.java
@@ -36,6 +36,16 @@ public interface BucketClient {
*/
Bucket create(Bucket bucket) throws NiFiRegistryException, IOException;
+ /**
+ * Creates the given bucket. If migration parameter is true the bucket will be created with the provided identifier.
+ * False will set a generated identifier.
+ *
+ * @param bucket the bucket to create
+ * @param preserveSourceProperties whether the operation is migration related
+ * @return the created bucket with the populated identifier
+ */
+ Bucket create(Bucket bucket, boolean preserveSourceProperties) throws NiFiRegistryException, IOException;
+
/**
* Gets the bucket with the given id.
*
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/FlowSnapshotClient.java b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/FlowSnapshotClient.java
index edf7beb1e4..c927899cfb 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/FlowSnapshotClient.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/FlowSnapshotClient.java
@@ -40,6 +40,21 @@ public interface FlowSnapshotClient {
*/
VersionedFlowSnapshot create(VersionedFlowSnapshot snapshot) throws NiFiRegistryException, IOException;
+ /**
+ * Creates a new snapshot/version for the given flow. If migration parameter is true the version will be created
+ * with the author can be found in the snapshot. False will set the author to the caller's identity.
+ *
+ * The snapshot object must have the version populated, and will receive an error if the submitted version is
+ * not the next one-up version.
+ *
+ * @param snapshot the new snapshot
+ * @param preserveSourceProperties whether the operation is migration related
+ * @return the created snapshot
+ * @throws NiFiRegistryException if an error is encountered other than IOException
+ * @throws IOException if an I/O error is encountered
+ */
+ VersionedFlowSnapshot create(VersionedFlowSnapshot snapshot, boolean preserveSourceProperties) throws NiFiRegistryException, IOException;
+
/**
* Gets the snapshot for the given bucket, flow, and version.
*
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyBucketClient.java b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyBucketClient.java
index 6d35998f79..18b74d9a9a 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyBucketClient.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyBucketClient.java
@@ -51,17 +51,23 @@ public class JerseyBucketClient extends AbstractJerseyClient implements BucketCl
@Override
public Bucket create(final Bucket bucket) throws NiFiRegistryException, IOException {
+ return create(bucket, Boolean.FALSE);
+ }
+
+ @Override
+ public Bucket create(final Bucket bucket, final boolean preserveSourceProperties) throws NiFiRegistryException, IOException {
if (bucket == null) {
throw new IllegalArgumentException("Bucket cannot be null");
}
- return executeAction("Error creating bucket", () -> {
- return getRequestBuilder(bucketsTarget)
- .post(
- Entity.entity(bucket, MediaType.APPLICATION_JSON),
- Bucket.class
- );
- });
+ final WebTarget target = bucketsTarget
+ .queryParam("preserveSourceProperties", preserveSourceProperties);
+
+ return executeAction("Error creating bucket", () -> getRequestBuilder(target)
+ .post(
+ Entity.entity(bucket, MediaType.APPLICATION_JSON),
+ Bucket.class
+ ));
}
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyFlowSnapshotClient.java b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyFlowSnapshotClient.java
index 19890ca2f5..f7f873d8b1 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyFlowSnapshotClient.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/JerseyFlowSnapshotClient.java
@@ -52,6 +52,11 @@ public class JerseyFlowSnapshotClient extends AbstractJerseyClient implements Fl
@Override
public VersionedFlowSnapshot create(final VersionedFlowSnapshot snapshot)
throws NiFiRegistryException, IOException {
+ return create(snapshot, Boolean.FALSE);
+ }
+
+ @Override
+ public VersionedFlowSnapshot create(VersionedFlowSnapshot snapshot, boolean preserveSourceProperties) throws NiFiRegistryException, IOException {
if (snapshot.getSnapshotMetadata() == null) {
throw new IllegalArgumentException("Snapshot Metadata cannot be null");
}
@@ -68,8 +73,9 @@ public class JerseyFlowSnapshotClient extends AbstractJerseyClient implements Fl
return executeAction("Error creating snapshot", () -> {
final WebTarget target = bucketFlowSnapshotTarget
- .resolveTemplate("bucketId", bucketId)
- .resolveTemplate("flowId", flowId);
+ .resolveTemplate("bucketId", bucketId)
+ .resolveTemplate("flowId", flowId)
+ .queryParam("preserveSourceProperties", preserveSourceProperties);
return getRequestBuilder(target)
.post(
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketFlowResource.java b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketFlowResource.java
index fd0d9cb76a..a1b270b28b 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketFlowResource.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketFlowResource.java
@@ -279,15 +279,25 @@ public class BucketFlowResource extends ApplicationResource {
@ApiParam(value = "The flow identifier")
final String flowId,
@ApiParam(value = "The new versioned flow snapshot.", required = true)
- final VersionedFlowSnapshot snapshot) {
+ final VersionedFlowSnapshot snapshot,
+ @ApiParam(
+ value = "Whether source properties like author should be kept")
+ @QueryParam("preserveSourceProperties")
+ final boolean preserveSourceProperties) {
verifyPathParamsMatchBody(bucketId, flowId, snapshot);
// bucketId and flowId fields are optional in the body parameter, but required before calling the service layer
setSnaphotMetadataIfMissing(bucketId, flowId, snapshot);
- final String userIdentity = NiFiUserUtils.getNiFiUserIdentity();
- snapshot.getSnapshotMetadata().setAuthor(userIdentity);
+ if (preserveSourceProperties) {
+ if (StringUtils.isBlank(snapshot.getSnapshotMetadata().getAuthor())) {
+ throw new BadRequestException("Author must not be blank");
+ }
+ } else {
+ final String userIdentity = NiFiUserUtils.getNiFiUserIdentity();
+ snapshot.getSnapshotMetadata().setAuthor(userIdentity);
+ }
final VersionedFlowSnapshot createdSnapshot = serviceFacade.createFlowSnapshot(snapshot);
publish(EventFactory.flowVersionCreated(createdSnapshot));
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketResource.java b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketResource.java
index 1692a2945e..718a0ed62d 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketResource.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/api/BucketResource.java
@@ -85,9 +85,13 @@ public class BucketResource extends ApplicationResource {
@ApiResponse(code = 403, message = HttpStatusMessages.MESSAGE_403) })
public Response createBucket(
@ApiParam(value = "The bucket to create", required = true)
- final Bucket bucket) {
+ final Bucket bucket,
+ @ApiParam(
+ value = "Whether source properties like identifier should be kept")
+ @QueryParam("preserveSourceProperties")
+ final boolean preserveSourceProperties) {
- final Bucket createdBucket = serviceFacade.createBucket(bucket);
+ final Bucket createdBucket = serviceFacade.createBucket(bucket, preserveSourceProperties);
publish(EventFactory.bucketCreated(createdBucket));
return Response.status(Response.Status.OK).entity(createdBucket).build();
}
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/ServiceFacade.java b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/ServiceFacade.java
index a284715bc7..11d8fa46c6 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/ServiceFacade.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/ServiceFacade.java
@@ -70,6 +70,8 @@ public interface ServiceFacade {
Bucket deleteBucket(String bucketIdentifier, RevisionInfo revisionInfo);
+ Bucket createBucket(Bucket bucket, boolean preserveSourceProperties);
+
// ---------------------- BucketItem methods ----------------------------------------------
List<BucketItem> getBucketItems(String bucketIdentifier);
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/StandardServiceFacade.java b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/StandardServiceFacade.java
index f4a5459af1..2bcedc1fac 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/StandardServiceFacade.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/main/java/org/apache/nifi/registry/web/service/StandardServiceFacade.java
@@ -138,17 +138,7 @@ public class StandardServiceFacade implements ServiceFacade {
@Override
public Bucket createBucket(final Bucket bucket) {
- authorizeBucketsAccess(RequestAction.WRITE);
- validateCreationOfRevisableEntity(bucket, BUCKET_ENTITY_TYPE);
- validateIdentifierNotPresent(bucket, BUCKET_ENTITY_TYPE);
-
- bucket.setIdentifier(UUID.randomUUID().toString());
-
- final Bucket createdBucket = createRevisableEntity(bucket, BUCKET_ENTITY_TYPE, currentUserIdentity(),
- () -> registryService.createBucket(bucket));
- permissionsService.populateBucketPermissions(createdBucket);
- linkService.populateLinks(createdBucket);
- return createdBucket;
+ return createBucket(bucket, Boolean.FALSE);
}
@Override
@@ -202,6 +192,25 @@ public class StandardServiceFacade implements ServiceFacade {
() -> registryService.deleteBucket(bucketIdentifier));
}
+ @Override
+ public Bucket createBucket(final Bucket bucket, final boolean preserveSourceProperties) {
+ authorizeBucketsAccess(RequestAction.WRITE);
+ validateCreationOfRevisableEntity(bucket, BUCKET_ENTITY_TYPE);
+
+ if (preserveSourceProperties) {
+ validateIdentifierPresent(bucket, BUCKET_ENTITY_TYPE);
+ } else {
+ validateIdentifierNotPresent(bucket, BUCKET_ENTITY_TYPE);
+ bucket.setIdentifier(UUID.randomUUID().toString());
+ }
+
+ final Bucket createdBucket = createRevisableEntity(bucket, BUCKET_ENTITY_TYPE, currentUserIdentity(),
+ () -> registryService.createBucket(bucket));
+ permissionsService.populateBucketPermissions(createdBucket);
+ linkService.populateLinks(createdBucket);
+ return createdBucket;
+ }
+
// ---------------------- BucketItem methods ----------------------------------------------
@Override
@@ -1200,6 +1209,12 @@ public class StandardServiceFacade implements ServiceFacade {
}
}
+ private void validateIdentifierPresent(final RevisableEntity entity, final String entityTypeName) {
+ if (entity.getIdentifier() == null) {
+ throw new IllegalArgumentException(entityTypeName + " identifier must be specified.");
+ }
+ }
+
private void validateUpdateOfRevisableEntity(final RevisableEntity entity, final String entityTypeName) {
if (entity == null) {
throw new IllegalArgumentException(entityTypeName + " cannot be null");
diff --git a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/test/java/org/apache/nifi/registry/web/api/SecureNiFiRegistryClientIT.java b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/test/java/org/apache/nifi/registry/web/api/SecureNiFiRegistryClientIT.java
index 80b8b01297..40592dbb38 100644
--- a/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/test/java/org/apache/nifi/registry/web/api/SecureNiFiRegistryClientIT.java
+++ b/nifi-registry/nifi-registry-core/nifi-registry-web-api/src/test/java/org/apache/nifi/registry/web/api/SecureNiFiRegistryClientIT.java
@@ -73,6 +73,8 @@ public class SecureNiFiRegistryClientIT extends IntegrationTestBase {
static final String INITIAL_ADMIN_IDENTITY = "CN=user1, OU=nifi";
static final String NO_ACCESS_IDENTITY = "CN=no-access, OU=nifi";
+ static final String SECOND_IDENTITY = "CN=keep_author, OU=nifi";
+
private NiFiRegistryClient client;
@BeforeEach
@@ -160,6 +162,21 @@ public class SecureNiFiRegistryClientIT extends IntegrationTestBase {
final VersionedFlowSnapshot createdSnapshot = snapshotClient.create(snapshot);
assertNotNull(createdSnapshot);
assertEquals(INITIAL_ADMIN_IDENTITY, createdSnapshot.getSnapshotMetadata().getAuthor());
+
+ final VersionedFlowSnapshotMetadata snapshotMetadata2 = new VersionedFlowSnapshotMetadata();
+ snapshotMetadata2.setBucketIdentifier(createdFlow.getBucketIdentifier());
+ snapshotMetadata2.setFlowIdentifier(createdFlow.getIdentifier());
+ snapshotMetadata2.setVersion(2);
+ snapshotMetadata2.setComments("This is snapshot #2");
+ snapshotMetadata2.setAuthor(SECOND_IDENTITY);
+
+ final VersionedFlowSnapshot snapshot2 = new VersionedFlowSnapshot();
+ snapshot2.setSnapshotMetadata(snapshotMetadata2);
+ snapshot2.setFlowContents(rootProcessGroup);
+
+ final VersionedFlowSnapshot createdSnapshot2 = snapshotClient.create(snapshot2, true);
+ assertNotNull(createdSnapshot2);
+ assertEquals(SECOND_IDENTITY, createdSnapshot2.getSnapshotMetadata().getAuthor());
}
@Test
diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java
index f7a8c2a3e1..677db3955c 100644
--- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java
+++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/CommandOption.java
@@ -27,7 +27,7 @@ public enum CommandOption {
CONNECTION_TIMEOUT("cto", "connectionTimeout", "Timeout parameter for creating a connection to NiFi/Registry, specified in milliseconds", true),
READ_TIMEOUT("rto", "readTimeout", "Timeout parameter for reading from NiFi/Registry, specified in milliseconds", true),
URL("u", "baseUrl", "The URL to execute the command against", true),
- INPUT_SOURCE("i", "input", "A local file to read as input contents, or a public URL to fetch", true, true),
+ INPUT_SOURCE("i", "input", "A local file to read as input contents, a directory to read files from or a public URL to fetch", true, true),
OUTPUT_FILE("o", "outputFile", "A file to write output to, must contain full path and filename", true, true),
OUTPUT_DIR("od", "outputDirectory", "A directory to write output to", true, true),
PROPERTIES("p", "properties", "A properties file to load arguments from, " +
@@ -164,7 +164,8 @@ public enum CommandOption {
OUTPUT_TYPE("ot", "outputType", "The type of output to produce (json or simple)", true),
VERBOSE("verbose", "verbose", "Indicates that verbose output should be provided", false),
RECURSIVE("r", "recursive", "Indicates the command should perform the action recursively", false),
- HELP("h", "help", "Help", false)
+ HELP("h", "help", "Help", false),
+ SKIP_EXISTING("se", "skipExisting", "Indicates to skip an operation if target object exists", false),
;
private final String shortName;
diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/NiFiRegistryCommandGroup.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/NiFiRegistryCommandGroup.java
index 5a9a42b5bc..d913177ef9 100644
--- a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/NiFiRegistryCommandGroup.java
+++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/NiFiRegistryCommandGroup.java
@@ -37,7 +37,9 @@ import org.apache.nifi.toolkit.cli.impl.command.registry.extension.UploadBundles
import org.apache.nifi.toolkit.cli.impl.command.registry.flow.CreateFlow;
import org.apache.nifi.toolkit.cli.impl.command.registry.flow.DeleteFlow;
import org.apache.nifi.toolkit.cli.impl.command.registry.flow.DiffFlowVersions;
+import org.apache.nifi.toolkit.cli.impl.command.registry.flow.ExportAllFlows;
import org.apache.nifi.toolkit.cli.impl.command.registry.flow.ExportFlowVersion;
+import org.apache.nifi.toolkit.cli.impl.command.registry.flow.ImportAllFlows;
import org.apache.nifi.toolkit.cli.impl.command.registry.flow.ImportFlowVersion;
import org.apache.nifi.toolkit.cli.impl.command.registry.flow.ListFlowVersions;
import org.apache.nifi.toolkit.cli.impl.command.registry.flow.ListFlows;
@@ -104,6 +106,8 @@ public class NiFiRegistryCommandGroup extends AbstractCommandGroup {
commandList.add(new GetAccessToken());
commandList.add(new GetAccessTokenSpnego());
commandList.add(new LogoutAccessToken());
+ commandList.add(new ExportAllFlows());
+ commandList.add(new ImportAllFlows());
return new ArrayList<>(commandList);
}
}
diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ExportAllFlows.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ExportAllFlows.java
new file mode 100644
index 0000000000..5b224d213e
--- /dev/null
+++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ExportAllFlows.java
@@ -0,0 +1,205 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.toolkit.cli.impl.command.registry.flow;
+
+import org.apache.commons.cli.MissingOptionException;
+import org.apache.commons.cli.ParseException;
+import org.apache.nifi.registry.bucket.Bucket;
+import org.apache.nifi.registry.client.NiFiRegistryClient;
+import org.apache.nifi.registry.client.NiFiRegistryException;
+import org.apache.nifi.registry.flow.VersionedFlow;
+import org.apache.nifi.registry.flow.VersionedFlowSnapshot;
+import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata;
+import org.apache.nifi.toolkit.cli.api.CommandException;
+import org.apache.nifi.toolkit.cli.api.Context;
+import org.apache.nifi.toolkit.cli.impl.client.NiFiRegistryClientFactory;
+import org.apache.nifi.toolkit.cli.impl.command.CommandOption;
+import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand;
+import org.apache.nifi.toolkit.cli.impl.command.registry.bucket.ListBuckets;
+import org.apache.nifi.toolkit.cli.impl.result.registry.VersionedFlowSnapshotsResult;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+public class ExportAllFlows extends AbstractNiFiRegistryCommand<VersionedFlowSnapshotsResult> {
+ private static final String ALL_BUCKETS_COLLECTED = "All buckets collected...";
+ private static final String ALL_FLOWS_COLLECTED = "All flows collected...";
+ private static final String ALL_FLOW_VERSIONS_COLLECTED = "All flow versions collected...";
+ private final ListBuckets listBuckets;
+ private final ListFlows listFlows;
+ private final ListFlowVersions listFlowVersions;
+
+ public ExportAllFlows() {
+ super("export-all-flows", VersionedFlowSnapshotsResult.class);
+ this.listBuckets = new ListBuckets();
+ this.listFlows = new ListFlows();
+ this.listFlowVersions = new ListFlowVersions();
+ }
+
+ @Override
+ public void doInitialize(final Context context) {
+ addOption(CommandOption.OUTPUT_DIR.createOption());
+
+ listBuckets.initialize(context);
+ listFlows.initialize(context);
+ listFlowVersions.initialize(context);
+ }
+
+ @Override
+ public String getDescription() {
+ return "List all the buckets, for each bucket, list all the flows, for each flow, list all versions and export each version." +
+ "Versions will be saved in the provided target directory.";
+ }
+
+ @Override
+ public VersionedFlowSnapshotsResult doExecute(NiFiRegistryClient client, Properties properties) throws IOException, NiFiRegistryException, ParseException, CommandException {
+ final String outputDirectory = getRequiredArg(properties, CommandOption.OUTPUT_DIR);
+ final boolean isInteractive = getContext().isInteractive();
+
+ // Gather all buckets and create a map for quick access by bucket id
+ final Map<String, Bucket> bucketMap = getBucketMap(client, isInteractive);
+
+ // Gather all flows and create a map for quick access by flow id
+ final Map<String, VersionedFlow> flowMap = getFlowMap(client, bucketMap, isInteractive);
+
+ // Gather all versions for all the flows
+ final List<VersionedFlowSnapshotMetadata> versionedFlowSnapshotMetadataList = getVersionedFlowSnapshotMetadataList(client, flowMap, isInteractive);
+
+ // Prepare flow version exports
+ final Iterator<VersionedFlowSnapshot> versionedFlowSnapshotIterator = new ExportAllFlowSnapshotIterator(properties, outputDirectory, bucketMap,
+ flowMap, versionedFlowSnapshotMetadataList.iterator());
+
+ // Export all flow versions
+ return new VersionedFlowSnapshotsResult(versionedFlowSnapshotIterator, outputDirectory);
+ }
+
+ private Map<String, Bucket> getBucketMap(final NiFiRegistryClient client, final boolean isInteractive) throws IOException, NiFiRegistryException {
+ printMessage(isInteractive, ALL_BUCKETS_COLLECTED);
+
+ return listBuckets.doExecute(client, new Properties())
+ .getResult()
+ .stream()
+ .collect(Collectors.toMap(Bucket::getIdentifier, Function.identity()));
+ }
+
+ private Map<String, VersionedFlow> getFlowMap(final NiFiRegistryClient client, final Map<String, Bucket> bucketMap,
+ final boolean isInteractive) throws IOException, NiFiRegistryException, ParseException {
+ printMessage(isInteractive, ALL_FLOWS_COLLECTED);
+
+ return getFlows(client, bucketMap)
+ .stream()
+ .collect(Collectors.toMap(VersionedFlow::getIdentifier, Function.identity()));
+ }
+
+ private List<VersionedFlow> getFlows(final NiFiRegistryClient client, final Map<String, Bucket> bucketMap) throws ParseException, IOException, NiFiRegistryException {
+ final List<VersionedFlow> versionedFlowList = new ArrayList<>();
+
+ for (final String bucketId : bucketMap.keySet()) {
+ final Properties listFlowProperties = new Properties();
+ listFlowProperties.setProperty(CommandOption.BUCKET_ID.getLongName(), bucketId);
+
+ versionedFlowList.addAll(listFlows.doExecute(client, listFlowProperties).getResult());
+ }
+ return versionedFlowList;
+ }
+
+ private List<VersionedFlowSnapshotMetadata> getVersionedFlowSnapshotMetadataList(final NiFiRegistryClient client, final Map<String, VersionedFlow> flowMap,
+ final boolean isInteractive) throws ParseException, IOException, NiFiRegistryException {
+ final List<VersionedFlowSnapshotMetadata> versionedFlowSnapshotMetadataList = new ArrayList<>();
+
+ for (final String flowId : flowMap.keySet()) {
+ final Properties listFlowVersionsProperties = new Properties();
+ listFlowVersionsProperties.setProperty(CommandOption.FLOW_ID.getLongName(), flowId);
+
+ versionedFlowSnapshotMetadataList.addAll(listFlowVersions.doExecute(client, listFlowVersionsProperties).getResult());
+ }
+
+ printMessage(isInteractive, ALL_FLOW_VERSIONS_COLLECTED);
+
+ return versionedFlowSnapshotMetadataList;
+ }
+
+ private void printMessage(final boolean isInteractive, final String message) {
+ if (isInteractive) {
+ println();
+ println(message);
+ println();
+ }
+ }
+
+ public static class ExportAllFlowSnapshotIterator implements Iterator<VersionedFlowSnapshot> {
+ private final NiFiRegistryClient client;
+ private final String outputDirectory;
+ private final Map<String, Bucket> bucketMap;
+ private final Map<String, VersionedFlow> flowMap;
+ private final Iterator<VersionedFlowSnapshotMetadata> metadataIterator;
+ private final ExportFlowVersion exportFlowVersion = new ExportFlowVersion();
+
+ public ExportAllFlowSnapshotIterator(final Properties properties, final String outputDirectory, final Map<String, Bucket> bucketMap,
+ final Map<String, VersionedFlow> flowMap, final Iterator<VersionedFlowSnapshotMetadata> metaDataIterator) throws MissingOptionException {
+ this.client = new NiFiRegistryClientFactory().createClient(properties);
+ this.outputDirectory = outputDirectory;
+ this.bucketMap = bucketMap;
+ this.flowMap = flowMap;
+ this.metadataIterator = metaDataIterator;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return metadataIterator.hasNext();
+ }
+
+ @Override
+ public VersionedFlowSnapshot next() {
+ try {
+ return setNextElement();
+ } catch (ParseException | IOException | NiFiRegistryException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private VersionedFlowSnapshot setNextElement() throws ParseException, IOException, NiFiRegistryException {
+ final VersionedFlowSnapshotMetadata metaData = metadataIterator.next();
+ final Properties exportFlowVersionProperties = new Properties();
+ exportFlowVersionProperties.setProperty(CommandOption.FLOW_ID.getLongName(), metaData.getFlowIdentifier());
+ exportFlowVersionProperties.setProperty(CommandOption.FLOW_VERSION.getLongName(), Integer.toString(metaData.getVersion()));
+ exportFlowVersionProperties.setProperty(CommandOption.OUTPUT_FILE.getLongName(), outputDirectory);
+
+ final VersionedFlowSnapshot exportedSnapshot = exportFlowVersion.doExecute(client, exportFlowVersionProperties).getResult();
+
+ final VersionedFlow flow = new VersionedFlow();
+ flow.setIdentifier(metaData.getFlowIdentifier());
+ flow.setName(flowMap.get(metaData.getFlowIdentifier()).getName());
+ flow.setDescription(flowMap.get(metaData.getFlowIdentifier()).getDescription());
+ exportedSnapshot.setFlow(flow);
+
+ final Bucket bucket = new Bucket();
+ bucket.setIdentifier(metaData.getBucketIdentifier());
+ bucket.setName(bucketMap.get(metaData.getBucketIdentifier()).getName());
+ bucket.setDescription(bucketMap.get(metaData.getBucketIdentifier()).getDescription());
+ exportedSnapshot.setBucket(bucket);
+
+ return exportedSnapshot;
+ }
+ }
+}
diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ImportAllFlows.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ImportAllFlows.java
new file mode 100644
index 0000000000..d1d031a5ee
--- /dev/null
+++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/command/registry/flow/ImportAllFlows.java
@@ -0,0 +1,337 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.toolkit.cli.impl.command.registry.flow;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.cli.MissingOptionException;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.curator.shaded.com.google.common.collect.ComparisonChain;
+import org.apache.nifi.flow.VersionedFlowCoordinates;
+import org.apache.nifi.flow.VersionedProcessGroup;
+import org.apache.nifi.registry.bucket.Bucket;
+import org.apache.nifi.registry.client.BucketClient;
+import org.apache.nifi.registry.client.FlowClient;
+import org.apache.nifi.registry.client.FlowSnapshotClient;
+import org.apache.nifi.registry.client.NiFiRegistryClient;
+import org.apache.nifi.registry.client.NiFiRegistryException;
+import org.apache.nifi.registry.flow.VersionedFlow;
+import org.apache.nifi.registry.flow.VersionedFlowSnapshot;
+import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata;
+import org.apache.nifi.toolkit.cli.api.CommandException;
+import org.apache.nifi.toolkit.cli.api.Context;
+import org.apache.nifi.toolkit.cli.impl.command.CommandOption;
+import org.apache.nifi.toolkit.cli.impl.command.registry.AbstractNiFiRegistryCommand;
+import org.apache.nifi.toolkit.cli.impl.command.registry.bucket.ListBuckets;
+import org.apache.nifi.toolkit.cli.impl.result.StringResult;
+import org.apache.nifi.toolkit.cli.impl.util.JacksonUtils;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class ImportAllFlows extends AbstractNiFiRegistryCommand<StringResult> {
+ private static final String FILE_NAME_PREFIX = "toolkit_registry_export_all_";
+ private static final String SKIPPING_BUCKET_CREATION = " already exists, skipping bucket creation...";
+ private static final String SKIPPING_IMPORT = " already exists, skipping import...";
+ private static final String SKIPPING_FLOW_CREATION = " already exists, skipping flow creation...";
+ private static final String IMPORT_COMPLETED = "Import completed...";
+ private static final String ALL_BUCKETS_COLLECTED = "All buckets collected...";
+ private static final String ALL_FLOWS_COLLECTED = "All flows collected...";
+ private static final String ALL_FLOW_VERSIONS_COLLECTED = "All flow versions collected...";
+ private static final String FILE_NAME_SEPARATOR = "_";
+ private static final String STORAGE_LOCATION_URL = "%s/nifi-registry-api/buckets/%s/flows/%s/versions/%s";
+ private static final String VERSION_IMPORTING_STARTED = "Importing %s - %s to %s";
+ private static final String VERSION_IMPORTING_FINISHED = "Successfully imported %s - %s to %s";
+ private static final ObjectMapper MAPPER = JacksonUtils.getObjectMapper();
+ private final ListBuckets listBuckets;
+ private final ListFlows listFlows;
+ private final ListFlowVersions listFlowVersions;
+
+ public ImportAllFlows() {
+ super("import-all-flows", StringResult.class);
+ this.listBuckets = new ListBuckets();
+ this.listFlows = new ListFlows();
+ this.listFlowVersions = new ListFlowVersions();
+ }
+
+ @Override
+ protected void doInitialize(Context context) {
+ addOption(CommandOption.INPUT_SOURCE.createOption());
+ addOption(CommandOption.SKIP_EXISTING.createOption());
+
+ listBuckets.initialize(context);
+ listFlows.initialize(context);
+ listFlowVersions.initialize(context);
+ }
+
+ @Override
+ public String getDescription() {
+ return "From a provided directory as input, the directory content must be generated by the export-all-flows command, " +
+ "based on the file contents, the corresponding buckets, flows and flow versions will be created." +
+ "If not configured otherwise, already existing objects will be skipped.";
+ }
+
+ @Override
+ public StringResult doExecute(final NiFiRegistryClient client, final Properties properties) throws IOException, NiFiRegistryException, ParseException, CommandException {
+ final boolean skip = getArg(properties, CommandOption.SKIP_EXISTING) == null ? Boolean.FALSE : Boolean.TRUE;
+ final boolean isInteractive = getContext().isInteractive();
+
+ //Gather all buckets and create a map for easier search by bucket name
+ final Map<String, String> bucketMap = getBucketMap(client, isInteractive);
+
+ // Gather all flows and create a map for easier search by flow name.
+ // As flow name is only unique within the same bucket we need to use the bucket id in the key as well
+ final Map<Pair<String, String>, String> flowMap = getFlowMap(client, bucketMap, isInteractive);
+ final Map<Pair<String, String>, String> flowCreated = new HashMap<>();
+
+ // Gather all flow versions and create a map for easier search by flow id
+ final Map<String, List<Integer>> versionMap = getVersionMap(client, flowMap, isInteractive);
+
+ // Create file path list
+ final List<VersionFileMetaData> files = getFilePathList(properties);
+
+ // As we need to keep the version order the list needs to be sorted
+ files.sort((o1, o2) -> ComparisonChain.start()
+ .compare(o1.getBucketName(), o2.getBucketName())
+ .compare(o1.getFlowName(), o2.getFlowName())
+ .compare(o1.getVersion(), o2.getVersion())
+ .result());
+
+ for (VersionFileMetaData file : files) {
+ final String inputSource = file.getInputSource();
+ final String fileContent = getInputSourceContent(inputSource);
+ final VersionedFlowSnapshot snapshot = MAPPER.readValue(fileContent, VersionedFlowSnapshot.class);
+
+ final String bucketName = snapshot.getBucket().getName();
+ final String bucketDescription = snapshot.getBucket().getDescription();
+ final String flowName = snapshot.getFlow().getName();
+ final String flowDescription = snapshot.getFlow().getDescription();
+ final int flowVersion = snapshot.getSnapshotMetadata().getVersion();
+ // The original bucket and flow ids must be kept otherwise NiFi won't be able to synchronize with the NiFi Registry
+ final String flowId = snapshot.getFlow().getIdentifier();
+ final String bucketId = snapshot.getBucket().getIdentifier();
+
+ printMessage(isInteractive, String.format(VERSION_IMPORTING_STARTED, flowName, flowVersion, bucketName));
+
+ // Create bucket if missing
+ if (bucketMap.containsKey(bucketName)) {
+ printMessage(isInteractive, bucketName + SKIPPING_BUCKET_CREATION);
+ } else {
+ //The original bucket id must be kept otherwise NiFi won't be able to synchronize with the NiFi Registry
+ createBucket(client, bucketMap, bucketName, bucketDescription, bucketId);
+ }
+
+ // Create flow if missing
+ if (flowMap.containsKey(new ImmutablePair<>(bucketId, flowName))) {
+ if (skip) {
+ printMessage(isInteractive, flowName + SKIPPING_IMPORT);
+ continue;
+ } else {
+ //flowId
+ printMessage(isInteractive, flowName + SKIPPING_FLOW_CREATION);
+ }
+ } else if (!flowCreated.containsKey(new ImmutablePair<>(bucketId, flowName))) {
+ createFlow(client, flowCreated, flowId, flowName, flowDescription, bucketId);
+ }
+
+ // Create missing flow versions
+ if (!versionMap.getOrDefault(flowId, Collections.emptyList()).contains(flowVersion)) {
+ //update storage location
+ final String registryUrl = getRequiredArg(properties, CommandOption.URL);
+
+ updateStorageLocation(snapshot.getFlowContents(), registryUrl);
+
+ createFlowVersion(client, snapshot, bucketId, flowId);
+ }
+
+ printMessage(isInteractive, String.format(VERSION_IMPORTING_FINISHED, flowName, flowVersion, bucketName));
+ }
+ return new StringResult(IMPORT_COMPLETED, getContext().isInteractive());
+ }
+
+ private Map<String, String> getBucketMap(final NiFiRegistryClient client, final boolean isInteractive) throws IOException, NiFiRegistryException {
+ printMessage(isInteractive, ALL_BUCKETS_COLLECTED);
+
+ return listBuckets.doExecute(client, new Properties())
+ .getResult()
+ .stream()
+ .collect(Collectors.toMap(Bucket::getName, Bucket::getIdentifier));
+ }
+
+ private Map<Pair<String, String>, String> getFlowMap(final NiFiRegistryClient client, final Map<String, String> bucketMap,
+ final boolean isInteractive) throws ParseException, IOException, NiFiRegistryException {
+ printMessage(isInteractive, ALL_FLOWS_COLLECTED);
+ return getVersionedFlows(client, bucketMap)
+ .stream()
+ .collect(Collectors.toMap(e -> new ImmutablePair<>(e.getBucketIdentifier(), e.getName()),
+ VersionedFlow::getIdentifier));
+ }
+
+ private List<VersionedFlow> getVersionedFlows(final NiFiRegistryClient client, final Map<String, String> bucketMap) throws ParseException, IOException, NiFiRegistryException {
+ final List<VersionedFlow> flows = new ArrayList<>();
+ for (final String id : bucketMap.values()) {
+ final Properties flowProperties = new Properties();
+ flowProperties.setProperty(CommandOption.BUCKET_ID.getLongName(), id);
+
+ flows.addAll(listFlows.doExecute(client, flowProperties).getResult());
+ }
+ return flows;
+ }
+
+ private Map<String, List<Integer>> getVersionMap(final NiFiRegistryClient client, final Map<Pair<String, String>, String> flowMap,
+ final boolean isInteractive) throws ParseException, IOException, NiFiRegistryException {
+ printMessage(isInteractive, ALL_FLOW_VERSIONS_COLLECTED);
+ return getVersionedFlowSnapshotMetadataList(client, flowMap)
+ .stream()
+ .collect(Collectors.groupingBy(VersionedFlowSnapshotMetadata::getFlowIdentifier,
+ Collectors.mapping(VersionedFlowSnapshotMetadata::getVersion, Collectors.toList())));
+ }
+
+ private List<VersionedFlowSnapshotMetadata> getVersionedFlowSnapshotMetadataList(final NiFiRegistryClient client,
+ final Map<Pair<String, String>, String> flowMap) throws ParseException, IOException, NiFiRegistryException {
+ final List<VersionedFlowSnapshotMetadata> versions = new ArrayList<>();
+ for (final String flowIds : flowMap.values()) {
+ final Properties flowVersionProperties = new Properties();
+ flowVersionProperties.setProperty(CommandOption.FLOW_ID.getLongName(), flowIds);
+
+ versions.addAll(listFlowVersions.doExecute(client, flowVersionProperties).getResult());
+ }
+ return versions;
+ }
+
+ private List<VersionFileMetaData> getFilePathList(final Properties properties) throws MissingOptionException, NiFiRegistryException {
+ final String directory = getRequiredArg(properties, CommandOption.INPUT_SOURCE);
+ final List<VersionFileMetaData> files;
+
+ try (final Stream<Path> paths = Files.list(Paths.get(directory))) {
+ files = paths
+ .filter(Files::isRegularFile)
+ .filter(path -> path.getFileName().toString().startsWith(FILE_NAME_PREFIX))
+ .map(VersionFileMetaData::new)
+ .collect(Collectors.toList());
+ } catch (Exception e) {
+ throw new NiFiRegistryException("File listing failed", e);
+ }
+ return files;
+ }
+
+ private void createBucket(final NiFiRegistryClient client, final Map<String, String> bucketMap, final String bucketName,
+ final String bucketDescription, final String bucketId) throws IOException, NiFiRegistryException {
+ final BucketClient bucketClient = client.getBucketClient();
+ final Bucket bucket = new Bucket();
+ bucket.setIdentifier(bucketId);
+ bucket.setName(bucketName);
+ bucket.setDescription(bucketDescription);
+
+ bucketClient.create(bucket, Boolean.TRUE);
+ bucketMap.put(bucketName, bucketId);
+ }
+
+ private void createFlow(final NiFiRegistryClient client, final Map<Pair<String, String>, String> flowCreated,
+ final String flowId, final String flowName, final String flowDescription, final String bucketId) throws IOException, NiFiRegistryException {
+ final FlowClient flowClient = client.getFlowClient();
+ final VersionedFlow flow = new VersionedFlow();
+ flow.setIdentifier(flowId);
+ flow.setName(flowName);
+ flow.setDescription(flowDescription);
+ flow.setBucketIdentifier(bucketId);
+
+ flowClient.create(flow);
+ flowCreated.put(new ImmutablePair<>(bucketId, flowName), flowId);
+ }
+
+ private void updateStorageLocation(final VersionedProcessGroup group, final String registryUrl) {
+ final VersionedFlowCoordinates flowCoordinates = group.getVersionedFlowCoordinates();
+ if (flowCoordinates != null && !flowCoordinates.getStorageLocation().startsWith(registryUrl)) {
+ final String updatedStorageLocation = String.format(STORAGE_LOCATION_URL, registryUrl, flowCoordinates.getBucketId(),
+ flowCoordinates.getFlowId(), flowCoordinates.getVersion());
+
+ flowCoordinates.setStorageLocation(updatedStorageLocation);
+ flowCoordinates.setRegistryUrl(registryUrl);
+ }
+ for (VersionedProcessGroup processGroup : group.getProcessGroups()) {
+ updateStorageLocation(processGroup, registryUrl);
+ }
+ }
+
+ private void createFlowVersion(final NiFiRegistryClient client, final VersionedFlowSnapshot snapshot, final String bucketId, final String flowId) throws IOException, NiFiRegistryException {
+ final FlowSnapshotClient snapshotClient = client.getFlowSnapshotClient();
+
+ int version;
+ try {
+ final VersionedFlowSnapshotMetadata latestMetadata = snapshotClient.getLatestMetadata(bucketId, flowId);
+ version = latestMetadata.getVersion() + 1;
+ } catch (NiFiRegistryException e) {
+ // when there are no versions it produces a 404 not found
+ version = 1;
+ }
+ snapshot.getSnapshotMetadata().setFlowIdentifier(flowId);
+ snapshot.getSnapshotMetadata().setBucketIdentifier(bucketId);
+ snapshot.getSnapshotMetadata().setVersion(version);
+ snapshotClient.create(snapshot, true);
+ }
+
+ private void printMessage(final boolean isInteractive, final String message) {
+ if (isInteractive) {
+ println();
+ println(message);
+ println();
+ }
+ }
+
+ public static class VersionFileMetaData {
+ private final String inputSource;
+ private final String bucketName;
+ private final String flowName;
+ private final int version;
+
+ public VersionFileMetaData(final Path path) {
+ final String[] fileNameElements = path.getFileName().toString().split(FILE_NAME_SEPARATOR);
+ this.inputSource = path.toString();
+ this.bucketName = fileNameElements[4];
+ this.flowName = fileNameElements[5];
+ this.version = Integer.parseInt(fileNameElements[6]);
+ }
+
+ public String getInputSource() {
+ return inputSource;
+ }
+
+ public String getBucketName() {
+ return bucketName;
+ }
+
+ public String getFlowName() {
+ return flowName;
+ }
+
+ public int getVersion() {
+ return version;
+ }
+ }
+}
diff --git a/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/registry/VersionedFlowSnapshotsResult.java b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/registry/VersionedFlowSnapshotsResult.java
new file mode 100644
index 0000000000..493401eadb
--- /dev/null
+++ b/nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/registry/VersionedFlowSnapshotsResult.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.toolkit.cli.impl.result.registry;
+
+import org.apache.commons.lang3.Validate;
+import org.apache.nifi.registry.flow.VersionedFlowSnapshot;
+import org.apache.nifi.toolkit.cli.api.WritableResult;
+import org.apache.nifi.toolkit.cli.impl.util.JacksonUtils;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Iterator;
+
+/**
+ * Result for a list of VersionedFlowSnapshots.
+ *
+ * If this result was created with a non-null exportDirectoryName, then the write method will ignore
+ * the passed in PrintStream, and will write the serialized snapshot to the given directory.
+ * The file name will be generated from the flow name and its version.
+ *
+ * If this result was created with a null exportDirectoryName, then the write method will write the
+ * serialized snapshots to the given PrintStream.
+ */
+public class VersionedFlowSnapshotsResult implements WritableResult<Iterator<VersionedFlowSnapshot>> {
+ private static final String FILE_NAME_PREFIX = "toolkit_registry_export_all";
+ private static final String EXPORT_FILE_NAME = "%s/%s_%s_%s_%d";
+ private static final String SEPARATOR = "_";
+ private static final String REPLACEMENT = "-";
+ private final Iterator<VersionedFlowSnapshot> versionedFlowSnapshots;
+ private final String exportDirectoryName;
+
+ public VersionedFlowSnapshotsResult(final Iterator<VersionedFlowSnapshot> versionedFlowSnapshots, final String exportDirectoryName) {
+ this.versionedFlowSnapshots = versionedFlowSnapshots;
+ this.exportDirectoryName = exportDirectoryName;
+ Validate.notNull(this.versionedFlowSnapshots);
+ }
+
+ @Override
+ public Iterator<VersionedFlowSnapshot> getResult() {
+ return versionedFlowSnapshots;
+ }
+
+ @Override
+ public void write(final PrintStream output) throws IOException {
+ while (versionedFlowSnapshots.hasNext()) {
+ final VersionedFlowSnapshot versionedFlowSnapshot = versionedFlowSnapshots.next();
+ if (exportDirectoryName != null) {
+ final String bucketName = versionedFlowSnapshot.getBucket().getName().replaceAll(SEPARATOR, REPLACEMENT);
+ final String flowName = versionedFlowSnapshot.getFlow().getName().replaceAll(SEPARATOR, REPLACEMENT);
+ final int version = versionedFlowSnapshot.getSnapshotMetadata().getVersion();
+ final String exportFileName = String.format(EXPORT_FILE_NAME, exportDirectoryName, FILE_NAME_PREFIX, bucketName, flowName, version);
+ try (final OutputStream resultOut = Files.newOutputStream(Paths.get(exportFileName))) {
+ JacksonUtils.write(versionedFlowSnapshot, resultOut);
+ } catch (Exception e) {
+ throw new RuntimeException("Unable to write flow snapshot to: " + exportFileName, e);
+ }
+ } else {
+ JacksonUtils.write(versionedFlowSnapshot, output);
+ }
+ }
+ }
+}