This is an automated email from the ASF dual-hosted git repository.
pvillard31 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 d58edcab298 NIFI-16629 Synchronize assets on Cluster Coordinator when
its flow is not elected (#11965)
d58edcab298 is described below
commit d58edcab2981ab3ff83adf51c4df571f388c5355
Author: Bryan Bende <[email protected]>
AuthorDate: Tue Nov 24 13:27:18 2026 -0500
NIFI-16629 Synchronize assets on Cluster Coordinator when its flow is not
elected (#11965)
---
.../cluster/coordination/ClusterCoordinator.java | 8 +
.../cluster/coordination/flow/FlowElection.java | 10 ++
.../coordination/flow/PopularVoteFlowElection.java | 8 +
.../coordination/node/NodeClusterCoordinator.java | 5 +
.../flow/TestPopularVoteFlowElection.java | 23 ++-
.../heartbeat/TestAbstractHeartbeatMonitor.java | 5 +
.../node/TestNodeClusterCoordinator.java | 7 +
.../nifi/asset/AssetSynchronizationSources.java | 60 +++++++
.../nifi/asset/StandardAssetSynchronizer.java | 154 ++++++++++++++++--
.../asset/StandardConnectorAssetSynchronizer.java | 155 ++++++++++++++++--
.../org/apache/nifi/client/NiFiRestApiClient.java | 4 +-
.../nifi/client/NiFiRestApiResponseException.java | 35 ++++
.../connector/ConnectorAssetReferences.java | 94 +++++++++++
.../connector/StandardConnectorRepository.java | 49 +-----
.../apache/nifi/web/api/ApplicationResource.java | 15 ++
.../org/apache/nifi/web/api/ConnectorResource.java | 2 +-
.../nifi/web/api/ParameterContextResource.java | 2 +-
.../apache/nifi/web/api/TestConnectorResource.java | 5 +-
.../ClusteredAssetCoordinatorElectionIT.java | 180 +++++++++++++++++++++
19 files changed, 743 insertions(+), 78 deletions(-)
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster-protocol/src/main/java/org/apache/nifi/cluster/coordination/ClusterCoordinator.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster-protocol/src/main/java/org/apache/nifi/cluster/coordination/ClusterCoordinator.java
index 67af688fed3..48ca1fc82cc 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster-protocol/src/main/java/org/apache/nifi/cluster/coordination/ClusterCoordinator.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster-protocol/src/main/java/org/apache/nifi/cluster/coordination/ClusterCoordinator.java
@@ -296,6 +296,14 @@ public interface ClusterCoordinator {
*/
String getFlowElectionStatus();
+ /**
+ * Returns the identifiers of the nodes that voted for the flow elected by
this node's Flow Election. This is only
+ * populated on the node that ran the election as Cluster Coordinator, and
is empty if no election has completed on this node.
+ *
+ * @return the identifiers of the nodes that voted for the elected flow
+ */
+ Set<NodeIdentifier> getElectedFlowNodeIdentifiers();
+
/**
* @return the current cluster workload retrieved from the cluster
coordinator.
* @throws IOException thrown when it failed to communicate with the
cluster coordinator.
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/FlowElection.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/FlowElection.java
index 70e72c51ac5..63fcf49959f 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/FlowElection.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/FlowElection.java
@@ -20,6 +20,8 @@ package org.apache.nifi.cluster.coordination.flow;
import org.apache.nifi.cluster.protocol.DataFlow;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
+import java.util.Set;
+
/**
* <p>
* A FlowElection is responsible for examining multiple versions of a dataflow
and determining which of
@@ -66,6 +68,14 @@ public interface FlowElection {
*/
DataFlow getElectedDataFlow();
+ /**
+ * Returns the identifiers of the nodes that voted for the elected
DataFlow. The returned Set is empty
+ * if the election has not yet completed.
+ *
+ * @return the identifiers of the nodes that voted for the elected DataFlow
+ */
+ Set<NodeIdentifier> getElectedFlowNodeIdentifiers();
+
/**
* Returns a human-readable description of the status of the election
*
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/PopularVoteFlowElection.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/PopularVoteFlowElection.java
index 05c8c31adc7..281fa575d31 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/PopularVoteFlowElection.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/PopularVoteFlowElection.java
@@ -55,6 +55,7 @@ public class PopularVoteFlowElection implements FlowElection {
private volatile Long startNanos = null;
private volatile DataFlow electedDataFlow = null;
+ private volatile Set<NodeIdentifier> electedFlowNodeIdentifiers = Set.of();
private final Map<String, FlowCandidate> candidateByFingerprint = new
HashMap<>();
@@ -149,6 +150,11 @@ public class PopularVoteFlowElection implements
FlowElection {
return electedDataFlow;
}
+ @Override
+ public Set<NodeIdentifier> getElectedFlowNodeIdentifiers() {
+ return electedFlowNodeIdentifiers;
+ }
+
private FlowCandidate performElection() {
if (candidateByFingerprint.isEmpty()) {
return null;
@@ -162,6 +168,7 @@ public class PopularVoteFlowElection implements
FlowElection {
// All flow candidates are empty flows. Just use one of them.
final FlowCandidate electedCandidate =
candidateByFingerprint.values().iterator().next();
this.electedDataFlow = electedCandidate.getDataFlow();
+ this.electedFlowNodeIdentifiers =
Set.copyOf(electedCandidate.getNodes());
return electedCandidate;
}
@@ -177,6 +184,7 @@ public class PopularVoteFlowElection implements
FlowElection {
}
this.electedDataFlow = elected.getDataFlow();
+ this.electedFlowNodeIdentifiers = Set.copyOf(elected.getNodes());
return elected;
}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/node/NodeClusterCoordinator.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/node/NodeClusterCoordinator.java
index e5b7a3de4eb..d973f07a70c 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/node/NodeClusterCoordinator.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/node/NodeClusterCoordinator.java
@@ -1241,6 +1241,11 @@ public class NodeClusterCoordinator implements
ClusterCoordinator, ProtocolHandl
return !requireElection || flowElection.isElectionComplete();
}
+ @Override
+ public Set<NodeIdentifier> getElectedFlowNodeIdentifiers() {
+ return flowElection.getElectedFlowNodeIdentifiers();
+ }
+
private void registerNodeId(final NodeIdentifier nodeIdentifier) {
final NodeConnectionStatus proposedConnectionStatus = new
NodeConnectionStatus(nodeIdentifier, DisconnectionCode.NOT_YET_CONNECTED);
final NodeConnectionStatus existingStatus =
nodeStatuses.putIfAbsent(nodeIdentifier.getId(), proposedConnectionStatus);
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/flow/TestPopularVoteFlowElection.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/flow/TestPopularVoteFlowElection.java
index 871ecda0c33..9a718b8352c 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/flow/TestPopularVoteFlowElection.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/flow/TestPopularVoteFlowElection.java
@@ -25,7 +25,10 @@ import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -42,21 +45,26 @@ public class TestPopularVoteFlowElection {
final PopularVoteFlowElection election = new
PopularVoteFlowElection(1, TimeUnit.MINUTES, 3);
final byte[] flow =
Files.readAllBytes(Paths.get("src/test/resources/conf/empty-flow.json"));
+ final NodeIdentifier nodeId1 = createNodeId(1);
+ final NodeIdentifier nodeId2 = createNodeId(2);
+ final NodeIdentifier nodeId3 = createNodeId(3);
+
assertFalse(election.isElectionComplete());
assertNull(election.getElectedDataFlow());
- assertNull(election.castVote(createDataFlow(flow), createNodeId(1)));
+ assertNull(election.castVote(createDataFlow(flow), nodeId1));
assertFalse(election.isElectionComplete());
assertNull(election.getElectedDataFlow());
- assertNull(election.castVote(createDataFlow(flow), createNodeId(2)));
+ assertNull(election.castVote(createDataFlow(flow), nodeId2));
assertFalse(election.isElectionComplete());
assertNull(election.getElectedDataFlow());
- final DataFlow electedDataFlow =
election.castVote(createDataFlow(flow), createNodeId(3));
+ final DataFlow electedDataFlow =
election.castVote(createDataFlow(flow), nodeId3);
assertNotNull(electedDataFlow);
assertEquals(new String(flow), new String(electedDataFlow.getFlow()));
+ assertEquals(Set.of(nodeId1, nodeId2, nodeId3),
election.getElectedFlowNodeIdentifiers());
}
@Test
@@ -89,9 +97,11 @@ public class TestPopularVoteFlowElection {
final byte[] emptyFlow =
Files.readAllBytes(Paths.get("src/test/resources/conf/empty-flow.json"));
final byte[] nonEmptyFlow =
Files.readAllBytes(Paths.get("src/test/resources/conf/non-empty-flow.json"));
+ final List<NodeIdentifier> nodeIds = new ArrayList<>();
for (int i = 0; i < 8; i++) {
assertFalse(election.isElectionComplete());
assertNull(election.getElectedDataFlow());
+ assertTrue(election.getElectedFlowNodeIdentifiers().isEmpty());
final DataFlow dataFlow;
if (i % 4 == 0) {
@@ -100,7 +110,10 @@ public class TestPopularVoteFlowElection {
dataFlow = createDataFlow(emptyFlow);
}
- final DataFlow electedDataFlow = election.castVote(dataFlow,
createNodeId(i));
+ final NodeIdentifier nodeId = createNodeId(i);
+ nodeIds.add(nodeId);
+
+ final DataFlow electedDataFlow = election.castVote(dataFlow,
nodeId);
if (i == 7) {
assertNotNull(electedDataFlow);
assertEquals(new String(nonEmptyFlow), new
String(electedDataFlow.getFlow()));
@@ -108,6 +121,8 @@ public class TestPopularVoteFlowElection {
assertNull(electedDataFlow);
}
}
+
+ assertEquals(Set.of(nodeIds.get(0), nodeIds.get(4)),
election.getElectedFlowNodeIdentifiers());
}
@Test
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/heartbeat/TestAbstractHeartbeatMonitor.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/heartbeat/TestAbstractHeartbeatMonitor.java
index ecf00553eec..eb8521659bd 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/heartbeat/TestAbstractHeartbeatMonitor.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/heartbeat/TestAbstractHeartbeatMonitor.java
@@ -399,6 +399,11 @@ public class TestAbstractHeartbeatMonitor {
return null;
}
+ @Override
+ public Set<NodeIdentifier> getElectedFlowNodeIdentifiers() {
+ return Set.of();
+ }
+
@Override
public Map<NodeIdentifier, NodeWorkload> getClusterWorkload() {
return null;
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/node/TestNodeClusterCoordinator.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/node/TestNodeClusterCoordinator.java
index 97d112a8a89..8d50813d20c 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/node/TestNodeClusterCoordinator.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/node/TestNodeClusterCoordinator.java
@@ -145,6 +145,8 @@ public class TestNodeClusterCoordinator {
assertEquals(NodeConnectionState.CONNECTED,
statusMap.get(createNodeId(4)).getState());
assertEquals(NodeConnectionState.CONNECTED,
statusMap.get(createNodeId(5)).getState());
assertEquals(NodeConnectionState.CONNECTING,
statusMap.get(createNodeId(6)).getState());
+
+ assertEquals(Set.of(requestedNodeId),
coordinator.getElectedFlowNodeIdentifiers());
}
@Test
@@ -590,6 +592,11 @@ public class TestNodeClusterCoordinator {
return dataFlow;
}
+ @Override
+ public Set<NodeIdentifier> getElectedFlowNodeIdentifiers() {
+ return voter == null ? Set.of() : Set.of(voter);
+ }
+
@Override
public String getStatusDescription() {
return "First Vote Wins";
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/AssetSynchronizationSources.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/AssetSynchronizationSources.java
new file mode 100644
index 00000000000..291dd11ec32
--- /dev/null
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/AssetSynchronizationSources.java
@@ -0,0 +1,60 @@
+/*
+ * 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.asset;
+
+import org.apache.nifi.cluster.coordination.ClusterCoordinator;
+import org.apache.nifi.cluster.protocol.NodeIdentifier;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Determines the nodes from which the Cluster Coordinator synchronizes assets.
+ */
+final class AssetSynchronizationSources {
+
+ private static final Comparator<NodeIdentifier> NODE_IDENTIFIER_COMPARATOR
=
Comparator.comparing(NodeIdentifier::getApiAddress).thenComparingInt(NodeIdentifier::getApiPort);
+
+ private AssetSynchronizationSources() {
+ }
+
+ /**
+ * Returns the nodes from which the Cluster Coordinator should synchronize
missing assets. The list is empty when the
+ * local node voted for the elected flow, because the local node then
already holds the assets that the flow references.
+ *
+ * @param clusterCoordinator the Cluster Coordinator
+ * @param localNodeIdentifier the identifier of the local node, or null if
not yet known
+ * @return the nodes from which to synchronize missing assets, ordered by
API address and then API port
+ */
+ static List<NodeIdentifier> getCoordinatorSourceNodes(final
ClusterCoordinator clusterCoordinator, final NodeIdentifier
localNodeIdentifier) {
+ if (localNodeIdentifier == null) {
+ return List.of();
+ }
+
+ final Set<NodeIdentifier> electedFlowNodeIdentifiers =
clusterCoordinator.getElectedFlowNodeIdentifiers();
+ if (electedFlowNodeIdentifiers.contains(localNodeIdentifier)) {
+ return List.of();
+ }
+
+ final List<NodeIdentifier> sourceNodeIds = new
ArrayList<>(electedFlowNodeIdentifiers);
+ sourceNodeIds.sort(NODE_IDENTIFIER_COMPARATOR);
+ return sourceNodeIds;
+ }
+}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
index c4bd08fbd37..89a063e4e74 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardAssetSynchronizer.java
@@ -18,6 +18,7 @@
package org.apache.nifi.asset;
import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.apache.nifi.client.NiFiRestApiResponseException;
import org.apache.nifi.client.NiFiRestApiRetryableException;
import org.apache.nifi.cluster.coordination.ClusterCoordinator;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
@@ -30,6 +31,7 @@ import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.web.api.dto.AssetDTO;
import org.apache.nifi.web.api.entity.AssetEntity;
import org.apache.nifi.web.api.entity.AssetsEntity;
+import org.apache.nifi.web.client.api.HttpResponseStatus;
import org.apache.nifi.web.client.api.WebClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,6 +42,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -47,7 +50,8 @@ import java.util.function.Function;
import java.util.stream.Collectors;
/**
- * Synchronizes assets from the cluster coordinator using the NiFi REST API.
+ * Synchronizes assets from the cluster coordinator using the NiFi REST API.
When the local node is the cluster coordinator but did not provide the
+ * elected flow, missing assets are synchronized from the nodes that did.
*/
public class StandardAssetSynchronizer implements AssetSynchronizer {
@@ -57,6 +61,7 @@ public class StandardAssetSynchronizer implements
AssetSynchronizer {
private static final Duration LIST_ASSETS_RETRY_DURATION =
Duration.ofMinutes(5);
private static final Duration SYNC_ASSET_RETRY_DURATION =
Duration.ofSeconds(30);
+ private final FlowController flowController;
private final AssetManager assetManager;
private final AssetComponentManager assetComponentManager;
private final FlowManager flowManager;
@@ -69,6 +74,7 @@ public class StandardAssetSynchronizer implements
AssetSynchronizer {
final WebClientService webClientService,
final NiFiProperties properties,
final AssetComponentManager
assetComponentManager) {
+ this.flowController = flowController;
this.assetManager = flowController.getAssetManager();
this.assetComponentManager = assetComponentManager;
this.flowManager = flowController.getFlowManager();
@@ -94,7 +100,15 @@ public class StandardAssetSynchronizer implements
AssetSynchronizer {
}
if (clusterCoordinator.isActiveClusterCoordinator()) {
- logger.info("Current node is the cluster coordinator: Asset
synchronization disabled");
+ final List<NodeIdentifier> sourceNodeIds =
AssetSynchronizationSources.getCoordinatorSourceNodes(clusterCoordinator,
flowController.getNodeId());
+ if (sourceNodeIds.isEmpty()) {
+ logger.info("Current node is the cluster coordinator: Asset
synchronization disabled");
+ return;
+ }
+
+ logger.info("Current node is the cluster coordinator but did not
provide the elected flow: synchronizing missing assets from nodes {}",
sourceNodeIds);
+ final List<Asset> syncedAssets =
synchronizeFromElectedFlowNodes(sourceNodeIds);
+ restartReferencingComponents(syncedAssets);
return;
}
@@ -117,17 +131,123 @@ public class StandardAssetSynchronizer implements
AssetSynchronizer {
}
}
- // Restart components that reference the synchronized assets
- if (!allSyncedAssets.isEmpty()) {
+ restartReferencingComponents(allSyncedAssets);
+ }
+
+ private List<Asset> synchronizeFromElectedFlowNodes(final
List<NodeIdentifier> sourceNodeIds) {
+ final List<Asset> syncedAssets = new ArrayList<>();
+ final Set<ParameterContext> parameterContexts =
flowManager.getParameterContextManager().getParameterContexts();
+
+ for (final NodeIdentifier sourceNodeId : sourceNodeIds) {
+ final AssetsRestApiClient assetsRestApiClient = new
AssetsRestApiClient(webClientService, sourceNodeId.getApiAddress(),
sourceNodeId.getApiPort(), properties.isHTTPSConfigured());
+
+ for (final ParameterContext parameterContext : parameterContexts) {
+ if (getAssetsMissingContent(parameterContext).isEmpty()) {
+ continue;
+ }
+
+ final AssetsEntity sourceAssetsEntity;
+ try {
+ sourceAssetsEntity =
listAssetsWithRetry(assetsRestApiClient, parameterContext.getIdentifier(),
true);
+ } catch (final IllegalStateException e) {
+ logger.error("Failed to list assets from node [{}] for
parameter context [{}]", sourceNodeId, parameterContext.getIdentifier(), e);
+ continue;
+ }
+
+ if (sourceAssetsEntity == null) {
+ logger.error("Timeout listing assets from node [{}] for
parameter context [{}]: skipping node", sourceNodeId,
parameterContext.getIdentifier());
+ break;
+ }
+
+ try {
+
syncedAssets.addAll(synchronizeMissingAssets(assetsRestApiClient, sourceNodeId,
parameterContext, sourceAssetsEntity));
+ } catch (final Exception e) {
+ logger.error("Failed to synchronize missing assets for
parameter context [{}] from node [{}]", parameterContext.getIdentifier(),
sourceNodeId, e);
+ }
+ }
+ }
+
+ for (final ParameterContext parameterContext : parameterContexts) {
+ final List<Asset> assetsMissingContent =
getAssetsMissingContent(parameterContext);
+ if (assetsMissingContent.isEmpty()) {
+ continue;
+ }
+
+ final List<String> missingAssetNames = new ArrayList<>();
+ for (final Asset asset : assetsMissingContent) {
+ missingAssetNames.add(asset.getName());
+ }
+
+ logger.warn("Parameter context [{}] still has {} assets without
content after synchronizing from nodes {}: {}",
+ parameterContext.getIdentifier(),
assetsMissingContent.size(), sourceNodeIds, missingAssetNames);
+ }
+
+ return syncedAssets;
+ }
+
+ private void restartReferencingComponents(final List<Asset> syncedAssets) {
+ if (!syncedAssets.isEmpty()) {
try {
- logger.info("Restarting components referencing {} synchronized
assets", allSyncedAssets.size());
-
assetComponentManager.restartReferencingComponents(allSyncedAssets);
+ logger.info("Restarting components referencing {} synchronized
assets", syncedAssets.size());
+
assetComponentManager.restartReferencingComponents(syncedAssets);
} catch (final Exception e) {
logger.error("Failed to restart components referencing
synchronized assets", e);
}
}
}
+ private List<Asset> getAssetsMissingContent(final ParameterContext
parameterContext) {
+ final Map<String, Asset> assetsMissingContent = new LinkedHashMap<>();
+ for (final Parameter parameter :
parameterContext.getParameters().values()) {
+ for (final Asset asset : parameter.getReferencedAssets()) {
+ if (!asset.getFile().exists()) {
+ assetsMissingContent.putIfAbsent(asset.getIdentifier(),
asset);
+ }
+ }
+ }
+
+ return new ArrayList<>(assetsMissingContent.values());
+ }
+
+ private List<Asset> synchronizeMissingAssets(final AssetsRestApiClient
assetsRestApiClient, final NodeIdentifier sourceNodeId, final ParameterContext
parameterContext,
+ final AssetsEntity
sourceAssetsEntity) {
+ final List<Asset> syncedAssets = new ArrayList<>();
+ final Collection<AssetEntity> sourceAssets =
sourceAssetsEntity.getAssets();
+ if (sourceAssets == null) {
+ return syncedAssets;
+ }
+
+ final String paramContextId = parameterContext.getIdentifier();
+ final Map<String, Asset> assetsMissingContent = new LinkedHashMap<>();
+ for (final Asset asset : getAssetsMissingContent(parameterContext)) {
+ assetsMissingContent.put(asset.getIdentifier(), asset);
+ }
+
+ for (final AssetEntity sourceAssetEntity : sourceAssets) {
+ final AssetDTO sourceAsset = sourceAssetEntity.getAsset();
+ if (!assetsMissingContent.containsKey(sourceAsset.getId())) {
+ continue;
+ }
+
+ if (Boolean.TRUE.equals(sourceAsset.getMissingContent())) {
+ logger.info("Node [{}] is also missing content for asset
[id={},name={}] in parameter context [{}]", sourceNodeId, sourceAsset.getId(),
sourceAsset.getName(), paramContextId);
+ continue;
+ }
+
+ try {
+ final Asset syncedAsset =
synchronizeAssetWithRetry(assetsRestApiClient, paramContextId, sourceAsset);
+ if (syncedAsset != null) {
+ logger.info("Successfully synchronized asset
[id={},name={}] for parameter context [{}]", syncedAsset.getIdentifier(),
syncedAsset.getName(), paramContextId);
+ syncedAssets.add(syncedAsset);
+ }
+ } catch (final Exception e) {
+ logger.error("Failed to synchronize asset [id={},name={}] for
parameter context [{}] from node [{}]", sourceAsset.getId(),
sourceAsset.getName(), paramContextId, sourceNodeId, e);
+ }
+ }
+
+ return syncedAssets;
+ }
+
private List<Asset> synchronize(final AssetsRestApiClient
assetsRestApiClient, final ParameterContext parameterContext) {
final List<Asset> syncedAssets = new ArrayList<>();
@@ -143,7 +263,7 @@ public class StandardAssetSynchronizer implements
AssetSynchronizer {
logger.info("Parameter context [{}] has {} assets on the current
node", parameterContext.getIdentifier(), existingAssets.size());
- final AssetsEntity coordinatorAssetsEntity =
listAssetsWithRetry(assetsRestApiClient, parameterContext.getIdentifier());
+ final AssetsEntity coordinatorAssetsEntity =
listAssetsWithRetry(assetsRestApiClient, parameterContext.getIdentifier(),
false);
if (coordinatorAssetsEntity == null) {
logger.error("Timeout listing assets from cluster coordinator for
parameter context [{}]", parameterContext.getIdentifier());
return syncedAssets;
@@ -184,6 +304,11 @@ public class StandardAssetSynchronizer implements
AssetSynchronizer {
logger.info("Synchronizing missing asset [id={},name={}] for
parameter context [{}]", assetId, assetName, paramContextId);
return synchronizeAssetWithRetry(assetsRestApiClient,
paramContextId, coordinatorAsset);
} else {
+ if (Boolean.TRUE.equals(coordinatorAsset.getMissingContent())) {
+ logger.warn("Cluster coordinator is missing content for asset
[id={},name={}] in parameter context [{}]: keeping local asset file", assetId,
assetName, paramContextId);
+ return null;
+ }
+
final String coordinatorAssetDigest = coordinatorAsset.getDigest();
final String matchingAssetDigest =
matchingAsset.getDigest().orElse(null);
if (!coordinatorAssetDigest.equals(matchingAssetDigest)) {
@@ -197,26 +322,33 @@ public class StandardAssetSynchronizer implements
AssetSynchronizer {
}
}
- private AssetsEntity listAssetsWithRetry(final AssetsRestApiClient
assetsRestApiClient, final String parameterContextId) {
+ private AssetsEntity listAssetsWithRetry(final AssetsRestApiClient
assetsRestApiClient, final String parameterContextId, final boolean
retryNotFound) {
final Instant expirationTime =
Instant.ofEpochMilli(System.currentTimeMillis() +
LIST_ASSETS_RETRY_DURATION.toMillis());
while (System.currentTimeMillis() < expirationTime.toEpochMilli()) {
- final AssetsEntity assetsEntity = listAssets(assetsRestApiClient,
parameterContextId);
+ final AssetsEntity assetsEntity = listAssets(assetsRestApiClient,
parameterContextId, retryNotFound);
if (assetsEntity != null) {
return assetsEntity;
}
- logger.info("Unable to list assets from cluster coordinator for
parameter context [{}]: retrying until [{}]", parameterContextId,
expirationTime);
+ logger.info("Unable to list assets for parameter context [{}]:
retrying until [{}]", parameterContextId, expirationTime);
sleep(Duration.ofSeconds(5));
}
return null;
}
- private AssetsEntity listAssets(final AssetsRestApiClient
assetsRestApiClient, final String parameterContextId) {
+ private AssetsEntity listAssets(final AssetsRestApiClient
assetsRestApiClient, final String parameterContextId, final boolean
retryNotFound) {
try {
return
assetsRestApiClient.getParameterContextAssets(parameterContextId);
} catch (final NiFiRestApiRetryableException e) {
final Throwable rootCause = ExceptionUtils.getRootCause(e);
logger.warn("{}, root cause [{}]: retrying", e.getMessage(),
rootCause.getMessage());
return null;
+ } catch (final NiFiRestApiResponseException e) {
+ if (!retryNotFound || e.getStatusCode() !=
HttpResponseStatus.NOT_FOUND.getCode()) {
+ throw e;
+ }
+
+ logger.warn("{}: retrying", e.getMessage());
+ return null;
}
}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardConnectorAssetSynchronizer.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardConnectorAssetSynchronizer.java
index ad70446ce5f..702f861d6d7 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardConnectorAssetSynchronizer.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/asset/StandardConnectorAssetSynchronizer.java
@@ -18,22 +18,27 @@
package org.apache.nifi.asset;
import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.apache.nifi.client.NiFiRestApiResponseException;
import org.apache.nifi.client.NiFiRestApiRetryableException;
import org.apache.nifi.cluster.coordination.ClusterCoordinator;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
+import org.apache.nifi.components.connector.ConnectorAssetReferences;
import org.apache.nifi.components.connector.ConnectorNode;
import org.apache.nifi.components.connector.ConnectorRepository;
import org.apache.nifi.components.connector.ConnectorState;
+import org.apache.nifi.components.connector.FrameworkFlowContext;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.flow.FlowManager;
import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.web.api.dto.AssetDTO;
import org.apache.nifi.web.api.entity.AssetEntity;
import org.apache.nifi.web.api.entity.AssetsEntity;
+import org.apache.nifi.web.client.api.HttpResponseStatus;
import org.apache.nifi.web.client.api.WebClientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
@@ -49,7 +54,8 @@ import java.util.function.Function;
import java.util.stream.Collectors;
/**
- * Synchronizes connector assets from the cluster coordinator using the NiFi
REST API.
+ * Synchronizes connector assets from the cluster coordinator using the NiFi
REST API. When the local node is the cluster coordinator but did not provide the
+ * elected flow, missing connector assets are synchronized from the nodes that
did.
*/
public class StandardConnectorAssetSynchronizer implements AssetSynchronizer {
@@ -59,6 +65,7 @@ public class StandardConnectorAssetSynchronizer implements
AssetSynchronizer {
private static final Duration LIST_ASSETS_RETRY_DURATION =
Duration.ofMinutes(5);
private static final Duration SYNC_ASSET_RETRY_DURATION =
Duration.ofSeconds(30);
+ private final FlowController flowController;
private final AssetManager assetManager;
private final FlowManager flowManager;
private final ConnectorRepository connectorRepository;
@@ -70,6 +77,7 @@ public class StandardConnectorAssetSynchronizer implements
AssetSynchronizer {
final ClusterCoordinator
clusterCoordinator,
final WebClientService
webClientService,
final NiFiProperties properties)
{
+ this.flowController = flowController;
this.assetManager = flowController.getConnectorAssetManager();
this.flowManager = flowController.getFlowManager();
this.connectorRepository = flowController.getConnectorRepository();
@@ -92,7 +100,15 @@ public class StandardConnectorAssetSynchronizer implements
AssetSynchronizer {
}
if (clusterCoordinator.isActiveClusterCoordinator()) {
- logger.info("Current node is the cluster coordinator: Connector
asset synchronization disabled");
+ final List<NodeIdentifier> sourceNodeIds =
AssetSynchronizationSources.getCoordinatorSourceNodes(clusterCoordinator,
flowController.getNodeId());
+ if (sourceNodeIds.isEmpty()) {
+ logger.info("Current node is the cluster coordinator:
Connector asset synchronization disabled");
+ return;
+ }
+
+ logger.info("Current node is the cluster coordinator but did not
provide the elected flow: synchronizing missing connector assets from nodes
{}", sourceNodeIds);
+ final Set<ConnectorNode> connectorsWithSynchronizedAssets =
synchronizeFromElectedFlowNodes(sourceNodeIds);
+
refreshConnectorsWithSynchronizedAssets(connectorsWithSynchronizedAssets);
return;
}
@@ -116,10 +132,107 @@ public class StandardConnectorAssetSynchronizer
implements AssetSynchronizer {
}
}
-
restartConnectorsWithSynchronizedAssets(connectorsWithSynchronizedAssets);
+
refreshConnectorsWithSynchronizedAssets(connectorsWithSynchronizedAssets);
+ }
+
+ private Set<ConnectorNode> synchronizeFromElectedFlowNodes(final
List<NodeIdentifier> sourceNodeIds) {
+ final Set<ConnectorNode> connectorsWithSynchronizedAssets = new
HashSet<>();
+ final List<ConnectorNode> connectors = flowManager.getAllConnectors();
+
+ for (final NodeIdentifier sourceNodeId : sourceNodeIds) {
+ final AssetsRestApiClient assetsRestApiClient = new
AssetsRestApiClient(webClientService, sourceNodeId.getApiAddress(),
sourceNodeId.getApiPort(), properties.isHTTPSConfigured());
+
+ for (final ConnectorNode connector : connectors) {
+ final Set<String> missingAssetIds =
getMissingAssetIds(connector);
+ if (missingAssetIds.isEmpty()) {
+ continue;
+ }
+
+ final String connectorId = connector.getIdentifier();
+ final AssetsEntity sourceAssetsEntity;
+ try {
+ sourceAssetsEntity =
listConnectorAssetsWithRetry(assetsRestApiClient, connectorId, true);
+ } catch (final IllegalStateException e) {
+ logger.error("Failed to list assets from node [{}] for
connector [{}]", sourceNodeId, connectorId, e);
+ continue;
+ }
+
+ if (sourceAssetsEntity == null) {
+ logger.error("Timeout listing assets from node [{}] for
connector [{}]: skipping node", sourceNodeId, connectorId);
+ break;
+ }
+
+ try {
+ if (synchronizeMissingAssets(assetsRestApiClient,
sourceNodeId, connectorId, missingAssetIds, sourceAssetsEntity)) {
+ connectorsWithSynchronizedAssets.add(connector);
+ }
+ } catch (final Exception e) {
+ logger.error("Failed to synchronize missing assets for
connector [{}] from node [{}]", connectorId, sourceNodeId, e);
+ }
+ }
+ }
+
+ for (final ConnectorNode connector : connectors) {
+ final Set<String> missingAssetIds = getMissingAssetIds(connector);
+ if (!missingAssetIds.isEmpty()) {
+ logger.warn("Connector [{}] still has {} assets without
content after synchronizing from nodes {}: {}",
+ connector.getIdentifier(), missingAssetIds.size(),
sourceNodeIds, missingAssetIds);
+ }
+ }
+
+ return connectorsWithSynchronizedAssets;
+ }
+
+ private Set<String> getMissingAssetIds(final ConnectorNode connector) {
+ final Set<String> missingAssetIds = new HashSet<>();
+ for (final String assetId :
ConnectorAssetReferences.getReferencedAssetIds(connector)) {
+ if (!hasAssetContent(assetId)) {
+ missingAssetIds.add(assetId);
+ }
+ }
+
+ return missingAssetIds;
}
- private void restartConnectorsWithSynchronizedAssets(final
Set<ConnectorNode> connectorsWithSynchronizedAssets) {
+ private boolean hasAssetContent(final String assetId) {
+ return
assetManager.getAsset(assetId).map(Asset::getFile).filter(File::exists).isPresent();
+ }
+
+ private boolean synchronizeMissingAssets(final AssetsRestApiClient
assetsRestApiClient, final NodeIdentifier sourceNodeId, final String
connectorId,
+ final Set<String>
missingAssetIds, final AssetsEntity sourceAssetsEntity) {
+ final Collection<AssetEntity> sourceAssets =
sourceAssetsEntity.getAssets();
+ if (sourceAssets == null) {
+ return false;
+ }
+
+ boolean assetSynchronized = false;
+ for (final AssetEntity sourceAssetEntity : sourceAssets) {
+ final AssetDTO sourceAsset = sourceAssetEntity.getAsset();
+ final String assetId = sourceAsset.getId();
+ if (!missingAssetIds.contains(assetId)) {
+ continue;
+ }
+
+ if (Boolean.TRUE.equals(sourceAsset.getMissingContent())) {
+ logger.info("Node [{}] is also missing content for asset
[id={},name={}] in connector [{}]", sourceNodeId, assetId,
sourceAsset.getName(), connectorId);
+ continue;
+ }
+
+ try {
+ synchronizeConnectorAssetWithRetry(assetsRestApiClient,
connectorId, sourceAsset);
+ if (hasAssetContent(assetId)) {
+ logger.info("Successfully synchronized asset
[id={},name={}] for connector [{}]", assetId, sourceAsset.getName(),
connectorId);
+ assetSynchronized = true;
+ }
+ } catch (final Exception e) {
+ logger.error("Failed to synchronize asset [id={},name={}] for
connector [{}] from node [{}]", assetId, sourceAsset.getName(), connectorId,
sourceNodeId, e);
+ }
+ }
+
+ return assetSynchronized;
+ }
+
+ private void refreshConnectorsWithSynchronizedAssets(final
Set<ConnectorNode> connectorsWithSynchronizedAssets) {
for (final ConnectorNode connector : connectorsWithSynchronizedAssets)
{
final ConnectorState currentState = connector.getDesiredState();
if (currentState == ConnectorState.RUNNING) {
@@ -135,7 +248,17 @@ public class StandardConnectorAssetSynchronizer implements
AssetSynchronizer {
logger.error("Failed to restart connector [{}] after asset
synchronization", connector.getIdentifier(), e.getCause());
}
} else {
- logger.info("Connector [{}] is not running (state={}):
skipping restart after asset synchronization", connector.getIdentifier(),
currentState);
+ logger.info("Connector [{}] is not running (state={}):
refreshing asset references without restart", connector.getIdentifier(),
currentState);
+ try {
+ final FrameworkFlowContext activeFlowContext =
connector.getActiveFlowContext();
+ if (activeFlowContext != null) {
+
activeFlowContext.getConfigurationContext().resolvePropertyValues();
+ }
+
+ connector.resetValidationState();
+ } catch (final Exception e) {
+ logger.error("Failed to refresh asset references for
connector [{}] after asset synchronization", connector.getIdentifier(), e);
+ }
}
}
}
@@ -145,7 +268,7 @@ public class StandardConnectorAssetSynchronizer implements
AssetSynchronizer {
final Map<String, Asset> existingAssets =
assetManager.getAssets(connectorId).stream()
.collect(Collectors.toMap(Asset::getIdentifier,
Function.identity()));
- final AssetsEntity coordinatorAssetsEntity =
listConnectorAssetsWithRetry(assetsRestApiClient, connectorId);
+ final AssetsEntity coordinatorAssetsEntity =
listConnectorAssetsWithRetry(assetsRestApiClient, connectorId, false);
if (coordinatorAssetsEntity == null) {
logger.error("Timeout listing assets from cluster coordinator for
connector [{}]", connectorId);
return false;
@@ -184,6 +307,11 @@ public class StandardConnectorAssetSynchronizer implements
AssetSynchronizer {
synchronizeConnectorAssetWithRetry(assetsRestApiClient,
connectorId, coordinatorAsset);
return true;
} else {
+ if (Boolean.TRUE.equals(coordinatorAsset.getMissingContent())) {
+ logger.warn("Cluster coordinator is missing content for asset
[id={},name={}] in connector [{}]: keeping local asset file", assetId,
assetName, connectorId);
+ return false;
+ }
+
final String coordinatorAssetDigest = coordinatorAsset.getDigest();
final String matchingAssetDigest =
matchingAsset.getDigest().orElse(null);
if (!coordinatorAssetDigest.equals(matchingAssetDigest)) {
@@ -198,26 +326,33 @@ public class StandardConnectorAssetSynchronizer
implements AssetSynchronizer {
}
}
- private AssetsEntity listConnectorAssetsWithRetry(final
AssetsRestApiClient assetsRestApiClient, final String connectorId) {
+ private AssetsEntity listConnectorAssetsWithRetry(final
AssetsRestApiClient assetsRestApiClient, final String connectorId, final
boolean retryNotFound) {
final Instant expirationTime =
Instant.ofEpochMilli(System.currentTimeMillis() +
LIST_ASSETS_RETRY_DURATION.toMillis());
while (System.currentTimeMillis() < expirationTime.toEpochMilli()) {
- final AssetsEntity assetsEntity =
listConnectorAssets(assetsRestApiClient, connectorId);
+ final AssetsEntity assetsEntity =
listConnectorAssets(assetsRestApiClient, connectorId, retryNotFound);
if (assetsEntity != null) {
return assetsEntity;
}
- logger.info("Unable to list assets from cluster coordinator for
connector [{}]: retrying until [{}]", connectorId, expirationTime);
+ logger.info("Unable to list assets for connector [{}]: retrying
until [{}]", connectorId, expirationTime);
sleep(Duration.ofSeconds(5));
}
return null;
}
- private AssetsEntity listConnectorAssets(final AssetsRestApiClient
assetsRestApiClient, final String connectorId) {
+ private AssetsEntity listConnectorAssets(final AssetsRestApiClient
assetsRestApiClient, final String connectorId, final boolean retryNotFound) {
try {
return assetsRestApiClient.getConnectorAssets(connectorId);
} catch (final NiFiRestApiRetryableException e) {
final Throwable rootCause = ExceptionUtils.getRootCause(e);
logger.warn("{}, root cause [{}]: retrying", e.getMessage(),
rootCause.getMessage());
return null;
+ } catch (final NiFiRestApiResponseException e) {
+ if (!retryNotFound || e.getStatusCode() !=
HttpResponseStatus.NOT_FOUND.getCode()) {
+ throw e;
+ }
+
+ logger.warn("{}: retrying", e.getMessage());
+ return null;
}
}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/client/NiFiRestApiClient.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/client/NiFiRestApiClient.java
index 7c6fe765b94..5862ba1f917 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/client/NiFiRestApiClient.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/client/NiFiRestApiClient.java
@@ -92,7 +92,7 @@ public abstract class NiFiRestApiClient {
* @param response the response
* @return the input stream of the response body
* @throws NiFiRestApiRetryableException if a retryable response or
exception happens
- * @throws IllegalStateException if a non-retryable response happens
+ * @throws NiFiRestApiResponseException if a non-retryable response happens
*/
protected InputStream getResponseBody(final URI requestUri, final
HttpResponseEntity response) {
final int statusCode = response.statusCode();
@@ -108,7 +108,7 @@ public abstract class NiFiRestApiClient {
if (statusCode == HttpResponseStatus.CONFLICT.getCode()) {
throw new NiFiRestApiRetryableException("Error calling %s - %s
- %s".formatted(requestUri, statusCode, responseMessage));
} else {
- throw new IllegalStateException("Error calling %s - %s -
%s".formatted(requestUri, statusCode, responseMessage));
+ throw new NiFiRestApiResponseException("Error calling %s - %s
- %s".formatted(requestUri, statusCode, responseMessage), statusCode);
}
}
}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/client/NiFiRestApiResponseException.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/client/NiFiRestApiResponseException.java
new file mode 100644
index 00000000000..5d80725dba9
--- /dev/null
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/client/NiFiRestApiResponseException.java
@@ -0,0 +1,35 @@
+/*
+ * 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.client;
+
+/**
+ * Indicates a non-retryable response status from calling NiFi's REST API.
+ */
+public class NiFiRestApiResponseException extends IllegalStateException {
+
+ private final int statusCode;
+
+ public NiFiRestApiResponseException(final String message, final int
statusCode) {
+ super(message);
+ this.statusCode = statusCode;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorAssetReferences.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorAssetReferences.java
new file mode 100644
index 00000000000..ec67b52dbef
--- /dev/null
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorAssetReferences.java
@@ -0,0 +1,94 @@
+/*
+ * 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.components.connector;
+
+import org.apache.nifi.asset.Asset;
+import org.apache.nifi.groups.ProcessGroup;
+import org.apache.nifi.parameter.Parameter;
+import org.apache.nifi.parameter.ParameterContext;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Determines the identifiers of the assets referenced by a Connector.
+ */
+public final class ConnectorAssetReferences {
+
+ private ConnectorAssetReferences() {
+ }
+
+ /**
+ * Returns the identifiers of the assets referenced by the Connector's
active and working flow contexts, including asset references in the
+ * Connector configuration and assets referenced by parameters of the
managed Process Group's Parameter Context.
+ *
+ * @param connector the Connector
+ * @return the identifiers of the referenced assets
+ */
+ public static Set<String> getReferencedAssetIds(final ConnectorNode
connector) {
+ final Set<String> referencedAssetIds = new HashSet<>();
+ collectReferencedAssetIds(connector.getActiveFlowContext(),
referencedAssetIds);
+ collectReferencedAssetIds(connector.getWorkingFlowContext(),
referencedAssetIds);
+ return referencedAssetIds;
+ }
+
+ private static void collectReferencedAssetIds(final FrameworkFlowContext
flowContext, final Set<String> referencedAssetIds) {
+ if (flowContext == null) {
+ return;
+ }
+
+ final ProcessGroup managedProcessGroup =
flowContext.getManagedProcessGroup();
+ if (managedProcessGroup != null) {
+
collectReferencedParameterContextAssetIds(managedProcessGroup.getParameterContext(),
referencedAssetIds);
+ }
+
+ final ConnectorConfiguration configuration =
flowContext.getConfigurationContext().toConnectorConfiguration();
+ for (final NamedStepConfiguration namedStepConfiguration :
configuration.getNamedStepConfigurations()) {
+ final StepConfiguration stepConfiguration =
namedStepConfiguration.configuration();
+ final Map<String, ConnectorValueReference> stepPropertyValues =
stepConfiguration.getPropertyValues();
+ if (stepPropertyValues == null) {
+ continue;
+ }
+
+ for (final ConnectorValueReference valueReference :
stepPropertyValues.values()) {
+ if (valueReference instanceof final AssetReference
assetReference) {
+
referencedAssetIds.addAll(assetReference.getAssetIdentifiers());
+ }
+ }
+ }
+ }
+
+ private static void collectReferencedParameterContextAssetIds(final
ParameterContext parameterContext, final Set<String> referencedAssetIds) {
+ if (parameterContext == null) {
+ return;
+ }
+
+ for (final Parameter parameter :
parameterContext.getEffectiveParameters().values()) {
+ final List<Asset> referencedAssets =
parameter.getReferencedAssets();
+ if (referencedAssets == null) {
+ continue;
+ }
+
+ for (final Asset referencedAsset : referencedAssets) {
+ referencedAssetIds.add(referencedAsset.getIdentifier());
+ }
+ }
+ }
+}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java
index 42f35deb9c7..2338d453d45 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepository.java
@@ -30,11 +30,8 @@ import org.apache.nifi.flow.VersionedConfigurationStep;
import org.apache.nifi.flow.VersionedConnector;
import org.apache.nifi.flow.VersionedConnectorState;
import org.apache.nifi.flow.VersionedConnectorValueReference;
-import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.nar.ExtensionManager;
import org.apache.nifi.nar.NarCloseable;
-import org.apache.nifi.parameter.Parameter;
-import org.apache.nifi.parameter.ParameterContext;
import org.apache.nifi.util.BundleUtils;
import org.apache.nifi.util.ReflectionUtils;
import org.apache.nifi.web.api.dto.BundleDTO;
@@ -1025,9 +1022,7 @@ public class StandardConnectorRepository implements
ConnectorRepository {
}
final String connectorId = connector.getIdentifier();
- final Set<String> referencedAssetIds = new HashSet<>();
- collectReferencedAssetIds(connector.getActiveFlowContext(),
referencedAssetIds);
- collectReferencedAssetIds(connector.getWorkingFlowContext(),
referencedAssetIds);
+ final Set<String> referencedAssetIds =
ConnectorAssetReferences.getReferencedAssetIds(connector);
logger.debug("Found {} assets referenced for Connector [{}]",
referencedAssetIds.size(), connectorId);
@@ -1051,48 +1046,6 @@ public class StandardConnectorRepository implements
ConnectorRepository {
}
}
- private void collectReferencedAssetIds(final FrameworkFlowContext
flowContext, final Set<String> referencedAssetIds) {
- if (flowContext == null) {
- return;
- }
-
- final ProcessGroup managedProcessGroup =
flowContext.getManagedProcessGroup();
- if (managedProcessGroup != null) {
-
collectReferencedParameterContextAssetIds(managedProcessGroup.getParameterContext(),
referencedAssetIds);
- }
-
- final ConnectorConfiguration configuration =
flowContext.getConfigurationContext().toConnectorConfiguration();
- for (final NamedStepConfiguration namedStepConfiguration :
configuration.getNamedStepConfigurations()) {
- final StepConfiguration stepConfiguration =
namedStepConfiguration.configuration();
- final Map<String, ConnectorValueReference> stepPropertyValues =
stepConfiguration.getPropertyValues();
- if (stepPropertyValues == null) {
- continue;
- }
- for (final ConnectorValueReference valueReference :
stepPropertyValues.values()) {
- if (valueReference instanceof final AssetReference
assetReference) {
-
referencedAssetIds.addAll(assetReference.getAssetIdentifiers());
- }
- }
- }
- }
-
- private void collectReferencedParameterContextAssetIds(final
ParameterContext parameterContext, final Set<String> referencedAssetIds) {
- if (parameterContext == null) {
- return;
- }
-
- for (final Parameter parameter :
parameterContext.getEffectiveParameters().values()) {
- final List<Asset> referencedAssets =
parameter.getReferencedAssets();
- if (referencedAssets == null) {
- continue;
- }
-
- for (final Asset referencedAsset : referencedAssets) {
- referencedAssetIds.add(referencedAsset.getIdentifier());
- }
- }
- }
-
@Override
public void updateConnector(final ConnectorNode connector, final String
name) {
if (connector.getCurrentState() == ConnectorState.TROUBLESHOOTING) {
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ApplicationResource.java
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ApplicationResource.java
index f0fc58b052d..dcce36a92c3 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ApplicationResource.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ApplicationResource.java
@@ -405,6 +405,21 @@ public abstract class ApplicationResource {
return header == null;
}
+ /**
+ * Indicates whether the request was sent directly by another node in the
cluster and is marked as already replicated. Such a request is
+ * serviced locally and is never replicated, so it can be answered before
the local flow has been initialized, for example while this node
+ * and the requesting node are both still connecting to the cluster.
+ *
+ * @return <code>true</code> if the request carries the replicated header
and comes directly from a cluster node, <code>false</code> otherwise
+ */
+ protected boolean isReplicatedRequestFromClusterNode() {
+ if
(httpServletRequest.getHeader(ReplicationHeader.REQUEST_REPLICATED.getHeader())
== null) {
+ return false;
+ }
+
+ return isRequestFromClusterNode();
+ }
+
/**
* Converts a Revision DTO and an associated Component ID into a Revision
object
*
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java
index 3063a761fe0..670aaa09358 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ConnectorResource.java
@@ -3026,7 +3026,7 @@ public class ConnectorResource extends
ApplicationResource {
) {
authorizeReadConnector(connectorId);
- if (isReplicateRequest()) {
+ if (!isReplicatedRequestFromClusterNode() && isReplicateRequest()) {
return replicate(HttpMethod.GET);
}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java
index 1f196283c96..da7ebb715df 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/ParameterContextResource.java
@@ -531,7 +531,7 @@ public class ParameterContextResource extends
AbstractParameterResource {
// authorize access
authorizeReadParameterContext(parameterContextId);
- if (isReplicateRequest()) {
+ if (!isReplicatedRequestFromClusterNode() && isReplicateRequest()) {
return replicate(HttpMethod.GET);
}
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/api/TestConnectorResource.java
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/api/TestConnectorResource.java
index 4936af9376c..970bf0ed0e5 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/api/TestConnectorResource.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/api/TestConnectorResource.java
@@ -33,6 +33,8 @@ import org.apache.nifi.authorization.resource.Authorizable;
import org.apache.nifi.authorization.user.NiFiUser;
import org.apache.nifi.authorization.user.NiFiUserDetails;
import org.apache.nifi.authorization.user.StandardNiFiUser;
+import org.apache.nifi.cluster.coordination.http.ReplicationHeader;
+import org.apache.nifi.cluster.manager.exception.IllegalClusterStateException;
import org.apache.nifi.components.BacklogReportingException;
import org.apache.nifi.controller.ScheduledState;
import org.apache.nifi.flow.VersionedProcessGroup;
@@ -381,8 +383,9 @@ public class TestConnectorResource {
@Test
public void testGetAssetsClusterNodeRequestBypassesAuth() {
final ConnectorResource spyResource = spy(connectorResource);
- doReturn(false).when(spyResource).isReplicateRequest();
+ lenient().doThrow(new IllegalClusterStateException("The Flow
Controller is initializing the Data
Flow.")).when(spyResource).isReplicateRequest();
doReturn(true).when(spyResource).isRequestFromClusterNode();
+
when(httpServletRequest.getHeader(ReplicationHeader.REQUEST_REPLICATED.getHeader())).thenReturn(Boolean.TRUE.toString());
when(serviceFacade.getConnectorAssets(CONNECTOR_ID)).thenReturn(List.of());
diff --git
a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/clustering/ClusteredAssetCoordinatorElectionIT.java
b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/clustering/ClusteredAssetCoordinatorElectionIT.java
new file mode 100644
index 00000000000..c06dc6e1597
--- /dev/null
+++
b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/clustering/ClusteredAssetCoordinatorElectionIT.java
@@ -0,0 +1,180 @@
+/*
+ * 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.tests.system.clustering;
+
+import org.apache.nifi.cluster.coordination.node.ClusterRoles;
+import org.apache.nifi.tests.system.InstanceConfiguration;
+import org.apache.nifi.tests.system.NiFiInstance;
+import org.apache.nifi.tests.system.NiFiInstanceFactory;
+import org.apache.nifi.tests.system.NiFiSystemIT;
+import org.apache.nifi.tests.system.SpawnedClusterNiFiInstanceFactory;
+import org.apache.nifi.toolkit.client.NiFiClientException;
+import org.apache.nifi.util.file.FileUtils;
+import org.apache.nifi.web.api.dto.AssetReferenceDTO;
+import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO;
+import org.apache.nifi.web.api.entity.AssetEntity;
+import org.apache.nifi.web.api.entity.ConnectorEntity;
+import org.apache.nifi.web.api.entity.ParameterContextEntity;
+import org.apache.nifi.web.api.entity.ParameterContextUpdateRequestEntity;
+import org.apache.nifi.web.api.entity.ProcessorEntity;
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Verifies that a Cluster Coordinator whose own flow loses the flow election
synchronizes the assets it is missing
+ * from the nodes whose flow was elected.
+ */
+public class ClusteredAssetCoordinatorElectionIT extends NiFiSystemIT {
+
+ private static final File SOURCE_ASSET_FILE = new
File("src/test/resources/sample-assets/helloworld.txt");
+ private static final String COORDINATOR_ELECTED_LOG_MESSAGE = "This node
has been elected Active " + ClusterRoles.CLUSTER_COORDINATOR;
+
+ @Override
+ public NiFiInstanceFactory getInstanceFactory() {
+ final Map<String, String> propertyOverrides = Map.of(
+ "nifi.cluster.flow.election.max.candidates", "2",
+ "nifi.cluster.flow.election.max.wait.time", "2 mins");
+
+ return new SpawnedClusterNiFiInstanceFactory(
+ new InstanceConfiguration.Builder()
+
.bootstrapConfig("src/test/resources/conf/clustered/node1/bootstrap.conf")
+ .instanceDirectory("target/node1")
+ .overrideNifiProperties(propertyOverrides)
+ .build(),
+ new InstanceConfiguration.Builder()
+
.bootstrapConfig("src/test/resources/conf/clustered/node2/bootstrap.conf")
+ .instanceDirectory("target/node2")
+ .overrideNifiProperties(propertyOverrides)
+ .build());
+ }
+
+ @Override
+ protected boolean isDestroyEnvironmentAfterEachTest() {
+ return true;
+ }
+
+ @Override
+ protected boolean isAllowFactoryReuse() {
+ return false;
+ }
+
+ @Test
+ public void
testCoordinatorWithoutParameterContextAssetsSynchronizesFromElectedFlowNode()
throws NiFiClientException, IOException, InterruptedException {
+ waitForAllNodesConnected();
+
+ final ParameterContextEntity paramContext =
getClientUtil().createParameterContext("testCoordinatorAssetSync",
Map.of("fileToIngest", ""));
+ getClientUtil().setParameterContext("root", paramContext);
+
+ final ProcessorEntity ingest =
getClientUtil().createProcessor("IngestFile");
+ getClientUtil().updateProcessorProperties(ingest, Map.of("Filename",
"#{fileToIngest}", "Delete File", "false"));
+ getClientUtil().updateProcessorSchedulingPeriod(ingest, "10 mins");
+
+ final AssetEntity asset =
getNifiClient().getParamContextClient().createAsset(paramContext.getId(),
SOURCE_ASSET_FILE.getName(), SOURCE_ASSET_FILE);
+ final ParameterContextUpdateRequestEntity referenceAssetUpdateRequest
= getClientUtil().updateParameterAssetReferences(
+ paramContext, Map.of("fileToIngest",
List.of(asset.getAsset().getId())));
+
getClientUtil().waitForParameterContextRequestToComplete(paramContext.getId(),
referenceAssetUpdateRequest.getRequest().getRequestId());
+
+ final ProcessorEntity terminate =
getClientUtil().createProcessor(TERMINATE_FLOWFILE);
+ getClientUtil().createConnection(ingest, terminate, SUCCESS);
+ getClientUtil().waitForValidProcessor(ingest.getId());
+
+ restartWithNode1AsEmptyCoordinator(List.of("assets"));
+
+ final File node1Dir =
getNiFiInstance().getNodeInstance(1).getInstanceDirectory();
+ final File restoredAssetFile = new File(node1Dir, "assets/" +
paramContext.getId() + "/" + SOURCE_ASSET_FILE.getName());
+ assertTrue(restoredAssetFile.exists());
+ assertArrayEquals(Files.readAllBytes(SOURCE_ASSET_FILE.toPath()),
Files.readAllBytes(restoredAssetFile.toPath()));
+
+ getClientUtil().waitForValidProcessor(ingest.getId());
+ }
+
+ @Test
+ public void
testCoordinatorWithoutConnectorAssetsSynchronizesFromElectedFlowNode() throws
NiFiClientException, IOException, InterruptedException {
+ waitForAllNodesConnected();
+
+ final ConnectorEntity connector =
getClientUtil().createConnector("AssetConnector");
+ final String connectorId = connector.getId();
+
+ final AssetEntity assetEntity =
getNifiClient().getConnectorClient().createAsset(connectorId,
SOURCE_ASSET_FILE.getName(), SOURCE_ASSET_FILE);
+ final String uploadedAssetId = assetEntity.getAsset().getId();
+
+ final ConnectorValueReferenceDTO assetValueReference = new
ConnectorValueReferenceDTO();
+ assetValueReference.setValueType("ASSET_REFERENCE");
+ assetValueReference.setAssetReferences(List.of(new
AssetReferenceDTO(uploadedAssetId)));
+ getClientUtil().configureConnectorWithReferences(connectorId, "Asset
Configuration", Map.of("Test Asset", assetValueReference));
+ getClientUtil().applyConnectorUpdate(connector);
+ getClientUtil().waitForValidConnector(connectorId);
+
+ restartWithNode1AsEmptyCoordinator(List.of("connector_assets"));
+
+ final File node1Dir =
getNiFiInstance().getNodeInstance(1).getInstanceDirectory();
+ final File restoredAssetFile = new File(node1Dir, "connector_assets/"
+ connectorId + "/" + uploadedAssetId + "/" + SOURCE_ASSET_FILE.getName());
+ assertTrue(restoredAssetFile.exists());
+ assertArrayEquals(Files.readAllBytes(SOURCE_ASSET_FILE.toPath()),
Files.readAllBytes(restoredAssetFile.toPath()));
+
+ getClientUtil().waitForValidConnector(connectorId);
+ }
+
+ /**
+ * Stops the cluster, removes the flow and the given asset directories
from node 1, and restarts the cluster so that node 1 becomes
+ * Cluster Coordinator with an empty flow while node 2 provides the
elected flow. Node 1 hosts the embedded ZooKeeper and is started
+ * alone first so that it gains the coordinator role, while the flow
election waits for the vote from node 2.
+ */
+ private void restartWithNode1AsEmptyCoordinator(final List<String>
assetDirectoryNames) throws IOException, InterruptedException,
NiFiClientException {
+ getNiFiInstance().stop();
+
+ final NiFiInstance node1 = getNiFiInstance().getNodeInstance(1);
+ final File node1Dir = node1.getInstanceDirectory();
+ final File node1ConfDir = new File(node1Dir, "conf");
+ Files.deleteIfExists(new File(node1ConfDir, "flow.json.gz").toPath());
+
+ final File node1ArchiveDir = new File(node1ConfDir, "archive");
+ if (node1ArchiveDir.exists()) {
+ FileUtils.deleteFilesInDir(node1ArchiveDir, (dir, name) -> true,
null, true, true);
+ }
+
+ for (final String assetDirectoryName : assetDirectoryNames) {
+ final File assetDir = new File(node1Dir, assetDirectoryName);
+ if (assetDir.exists()) {
+ FileUtils.deleteFilesInDir(assetDir, (dir, name) -> true,
null, true, true);
+ Files.delete(assetDir.toPath());
+ }
+ }
+
+ final File node1AppLog = new File(node1Dir, "logs/nifi-app.log");
+ Files.deleteIfExists(node1AppLog.toPath());
+
+ node1.start(false);
+ waitFor(() -> node1AppLog.exists() &&
Files.readString(node1AppLog.toPath(),
StandardCharsets.UTF_8).contains(COORDINATOR_ELECTED_LOG_MESSAGE), 500L,
+ "node 1 to be elected Cluster Coordinator");
+
+ getNiFiInstance().getNodeInstance(2).start(true);
+ setupClient();
+ waitForAllNodesConnected();
+
+
assertTrue(getNodeEntity(1).getNode().getRoles().contains(ClusterRoles.CLUSTER_COORDINATOR));
+ }
+}