From 53ffb1d9b528561f46ae7b3dfd7975e01b57c8db Mon Sep 17 00:00:00 2001 From: Bob Paulin Date: Wed, 7 Oct 2026 15:04:47 -0500 Subject: [PATCH 1/5] NIFI-16477: Implement Flow Evolution Drain Hooks and Flow persistence * Implement hooks to allow the Connector to drain the flow when its loaded version changes * When the Connector version differs from the version that built the authoritative flow load the persisted flow from the managedProcessGroup. --- .../org/apache/nifi/util/NiFiProperties.java | 2 + .../main/asciidoc/administration-guide.adoc | 10 + .../src/main/asciidoc/developer-guide.adoc | 54 + .../apache/nifi/web/api/dto/ConnectorDTO.java | 23 + .../api/entity/ConnectorRunStatusEntity.java | 13 + .../ClusteredConnectorRequestReplicator.java | 93 +- .../manager/ConnectorEntityMerger.java | 48 + ...nnectorRequestReplicatorConfiguration.java | 9 +- ...stClusteredConnectorRequestReplicator.java | 133 +++ .../manager/ConnectorEntityMergerTest.java | 77 +- ...tandardVersionedComponentSynchronizer.java | 23 +- .../nifi/groups/StandardProcessGroup.java | 25 +- .../mapping/VersionedComponentFlowMapper.java | 87 +- .../TestVersionedComponentFlowMapper.java | 19 + .../ConnectorClusterUnavailableException.java | 31 + .../connector/ConnectorFlowSnapshot.java | 49 + .../components/connector/ConnectorNode.java | 76 ++ .../connector/ConnectorRepository.java | 13 +- ...nectorRepositoryInitializationContext.java | 9 + .../connector/ConnectorRequestReplicator.java | 10 + .../connector/FlowEvolutionStatus.java | 74 ++ ...ameworkConnectorInitializationContext.java | 12 + .../connector/FrameworkFlowContext.java | 23 +- .../org/apache/nifi/groups/ProcessGroup.java | 10 + .../flow/mapping/FlowMappingOptions.java | 18 + .../ConnectorFlowSnapshotMapper.java | 87 ++ .../connector/MigrationFlowContext.java | 13 +- .../connector/ParameterSecretReferences.java | 225 ++++ .../connector/PreUpgradeFlowContext.java | 70 ++ .../StandaloneConnectorRequestReplicator.java | 19 +- ...tandardConnectorInitializationContext.java | 3 +- .../connector/StandardConnectorNode.java | 957 +++++++++++++++++- ...ardConnectorRepoInitializationContext.java | 10 +- .../StandardConnectorRepository.java | 353 ++++++- .../connector/StandardFlowContext.java | 56 +- .../StandardFlowEvolutionContext.java | 62 ++ .../nifi/controller/ExtensionBuilder.java | 15 +- .../nifi/controller/FlowController.java | 26 +- .../nifi/controller/StandardFlowService.java | 2 + .../FlowControllerFlowContextFactory.java | 8 +- .../VersionedDataflowMapper.java | 17 +- .../connector/FlowEvolutionHookConnector.java | 110 ++ .../connector/StandardConnectorNodeIT.java | 2 + .../TestParameterSecretReferences.java | 171 ++++ .../connector/TestStandardConnectorNode.java | 495 ++++++++- .../TestStandardConnectorRepository.java | 321 +++++- .../connector/TestStandardFlowContext.java | 58 +- .../flow/TestStandardFlowManager.java | 2 + .../service/mock/MockProcessGroup.java | 5 + .../nifi-framework/nifi-resources/pom.xml | 1 + .../src/main/resources/conf/nifi.properties | 3 + .../apache/nifi/audit/ConnectorAuditor.java | 4 +- .../nifi/web/StandardNiFiServiceFacade.java | 52 +- .../nifi/web/api/ConnectorResource.java | 21 +- .../apache/nifi/web/api/dto/DtoFactory.java | 3 + .../org/apache/nifi/web/dao/ConnectorDAO.java | 2 +- .../web/dao/impl/StandardConnectorDAO.java | 4 +- .../web/StandardNiFiServiceFacadeTest.java | 101 +- .../nifi/web/api/TestConnectorResource.java | 48 + .../pom.xml | 6 + .../nifi-alternate-config-extensions/pom.xml | 5 + .../nifi-system-test-extensions-nar/pom.xml | 6 + .../nifi-system-test-extensions2/pom.xml | 10 + .../FileConnectorConfigurationProvider.java | 157 +++ .../tests/system/UpgradeDrainGenerate.java | 104 ++ .../tests/system/UpgradeDrainRelay.java | 53 + .../tests/system/UpgradeDrainTerminate.java | 65 ++ ...s.connector.ConnectorConfigurationProvider | 16 + .../org.apache.nifi.processor.Processor | 5 +- .../pom.xml | 55 + .../nifi-connector-upgrade-drain-v1/pom.xml | 45 + .../tests/system/UpgradeDrainConnector.java | 240 +++++ ...apache.nifi.components.connector.Connector | 15 + .../pom.xml | 55 + .../nifi-connector-upgrade-drain-v2/pom.xml | 45 + .../tests/system/UpgradeDrainConnector.java | 339 +++++++ ...apache.nifi.components.connector.Connector | 15 + .../pom.xml | 4 + .../nifi-system-test-suite/pom.xml | 37 + .../system/AbstractNarSwapMigrationIT.java | 66 +- .../tests/system/FlowDefinitionFiles.java | 66 ++ .../nifi/tests/system/NiFiClientUtil.java | 19 + .../AbstractChangeVersionDrainIT.java | 98 ++ .../AbstractConnectorUpgradeDrainIT.java | 406 ++++++++ .../AbstractNarSwapUpgradeDrainIT.java | 56 + ...lusteredConnectorChangeVersionDrainIT.java | 250 +++++ .../connectors/ClusteredConnectorIT.java | 27 +- .../ClusteredConnectorUpgradeDrainIT.java | 71 ++ .../ConnectorChangeVersionDrainIT.java | 481 +++++++++ .../connectors/ConnectorChangeVersionIT.java | 23 + .../ConnectorParameterContextIT.java | 15 + .../ConnectorUpgradeDrainProviderIT.java | 132 +++ nifi-system-tests/pom.xml | 3 +- 93 files changed, 7028 insertions(+), 229 deletions(-) create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshot.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshotMapper.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/PreUpgradeFlowContext.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowEvolutionContext.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java create mode 100644 nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/connectors/tests/system/FileConnectorConfigurationProvider.java create mode 100644 nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainGenerate.java create mode 100644 nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainRelay.java create mode 100644 nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainTerminate.java create mode 100644 nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.ConnectorConfigurationProvider create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1-nar/pom.xml create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/pom.xml create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2-nar/pom.xml create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/pom.xml create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java create mode 100644 nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java create mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java diff --git a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java index 12a3f01ed691..a6465052f475 100644 --- a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java +++ b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java @@ -148,6 +148,8 @@ public class NiFiProperties extends ApplicationProperties { public static final String CONNECTOR_REPOSITORY_IMPLEMENTATION = "nifi.connector.repository.implementation"; public static final String CONNECTOR_SYNC_TIMEOUT = "nifi.connector.sync.timeout"; public static final String DEFAULT_CONNECTOR_SYNC_TIMEOUT = "5 mins"; + public static final String CONNECTOR_FLOW_EVOLUTION_TIMEOUT = "nifi.connector.flow.evolution.timeout"; + public static final String DEFAULT_CONNECTOR_FLOW_EVOLUTION_TIMEOUT = "30 mins"; // Connector Configuration Provider properties public static final String CONNECTOR_CONFIGURATION_PROVIDER_IMPLEMENTATION = "nifi.connector.configuration.provider.implementation"; diff --git a/nifi-docs/src/main/asciidoc/administration-guide.adoc b/nifi-docs/src/main/asciidoc/administration-guide.adoc index 936a6d8fe36d..7d16a699a07c 100644 --- a/nifi-docs/src/main/asciidoc/administration-guide.adoc +++ b/nifi-docs/src/main/asciidoc/administration-guide.adoc @@ -3921,6 +3921,16 @@ The NiFi Registry NAR provider retrieves NARs from a NiFi Registry instance. In |`nifi.nar.library.provider.nifi-registry.url`| The URL of the NiFi Registry instance, such as `http://localhost:18080`. If the URL begins with `https`, then the NiFi keystore and truststore will be used to make the TLS connection. |==== +[[connector_properties]] +=== Connector Properties + +These properties configure how NiFi manages Connectors. For what flow evolution is and how it runs, see <> in the Developer's Guide. + +|==== +|*Property*|*Description* +|`nifi.connector.flow.evolution.timeout`|How long a Connector may spend draining its outgoing flow in `prepareForFlowEvolution`. Waiting for other cluster nodes to finish their drain is not limited by this timeout. Accepts any NiFi time duration value such as `30 mins`. The default value is `30 mins`. A timeout leaves the Connector stopped and still pending. +|==== + [[secrets_manager_properties]] === Secrets Manager Properties diff --git a/nifi-docs/src/main/asciidoc/developer-guide.adoc b/nifi-docs/src/main/asciidoc/developer-guide.adoc index 608df79a20bf..cda826c753d3 100644 --- a/nifi-docs/src/main/asciidoc/developer-guide.adoc +++ b/nifi-docs/src/main/asciidoc/developer-guide.adoc @@ -2700,6 +2700,60 @@ The following command is used to generate a standard binary distribution of Apac `mvn clean install -Pcontrib-check` +[[connector_flow_evolution]] +== Connector Flow Evolution + +A Connector's managed flow is the set of processors, controller services, and connections that the Connector builds from its bundle. Whenever NiFi saves the flow, it records the bundle version that built the managed flow. That recorded version is kept separately from the bundle version the Connector is currently loaded from. + +If the loaded bundle version differs from the recorded one, the managed flow must be evolved to match the new version before the Connector runs. This is called flow evolution. It is pending while the two versions differ, and it runs on the next START of the Connector. + +=== When the flow is saved + +There is no explicit save action. NiFi writes the flow to its flow file, `flow.json.gz` by default, as each change completes. Changes made close together are written as one update, after the delay set by `nifi.flowservice.writedelay.interval`, which defaults to `500 ms`. + +Any user action that modifies the flow saves it. Changing a Connector's version records the new Connector bundle, but the managed flow keeps the bundle it was built from until flow evolution saves. + +NiFi also saves the flow without a user action in these cases: + +* During flow evolution, once, after the upgraded flow is applied. The Connector is recorded as running, because only a START runs an evolution. A failed evolution is not saved. +* When a node reconnects to a cluster and writes the flow it inherited from the cluster. + +=== How evolution runs + +On the next START, the framework calls `prepareForFlowEvolution(FlowEvolutionContext)` on the Connector. The context describes the outgoing flow and the upgraded bundle. The Connector returns a `CompletableFuture` that completes when the outgoing flow is ready. The framework waits for that future, stops the processors in the outgoing flow, and then applies the upgraded flow as described in <>. + +When NiFi restarts with an evolution pending, it restores the outgoing flow with its components stopped, whatever state they were saved in. The Connector's recorded state decides whether the evolution starts, and the hook starts what it needs to drain. A Connector recorded in Troubleshooting mode keeps the saved component states. + +The framework does not call `prepareForFlowEvolution` when a Connector leaves the Troubleshooting state. In that case the managed flow must already be empty. + +=== Draining in prepareForFlowEvolution + +The default implementation of `prepareForFlowEvolution` does nothing and returns a completed future. The framework does not drain FlowFiles for the Connector, so a Connector that removes connections must empty them in its own hook. + +* If any connection that the upgraded flow removes still holds FlowFiles, the Connector must drain. The hook must finish with every such connection empty, or the upgrade fails. +* The Connector does not need to drain when every connection that the upgraded flow removes is already empty. A connection that the upgraded flow keeps, with the same identifier, is updated in place and keeps its queue, so it never requires a drain. +* The framework stops the outgoing processors only after the hook's future completes. The hook can start them so that queues empty, and the processors are stopped afterward. +* The framework can cancel the future, for example when the Connector is stopped or the evolution timeout is reached. Stop any work promptly when the future is cancelled. The framework does not wait for code that ignores cancellation. + +[[connector_applying_upgraded_flow]] +=== Applying the upgraded flow + +Once every node that still has the outgoing flow has drained it, the framework checks again that no connection the upgraded flow removes holds FlowFiles. If one does, the evolution fails and the outgoing flow is kept. Otherwise the framework runs the same `prepareForUpdate` and `applyUpdate` process as a configuration update, saves the resulting flow, and starts the Connector. + +Each node prepares on its own. Every node has already finished the hook, so the framework does not wait for the other nodes to reach `UPDATING`. + +`prepareForUpdate` and `applyUpdate` must be safe to run again. If either fails, the Connector is left `UPDATE_FAILED`, and the next START calls both again without running the hook. `applyUpdate` therefore has to work on a flow that it has already partly updated. + +=== What operators see + +In a cluster, each node drains its own Connector. No node applies the upgraded flow until every node that still has the outgoing flow has drained it, so the Connector reports `DRAINING` while the nodes wait for one another. A node that has already applied the upgraded flow has nothing to drain and does not hold back the others. A node that disconnects after applying the upgraded flow does not block the others either: the connected nodes start. `nifi.connector.flow.evolution.timeout` limits only the local drain in `prepareForFlowEvolution`. See <> in the Administration Guide. + +If evolution fails before the upgraded flow is applied, including while a node waits for the others to drain, the Connector remains stopped and still pending, and the next START runs the hook again. Stopping the Connector while it drains cancels the attempt. The failure is not saved, so after a restart the Connector comes back in the state that was last saved. + +A failure while applying the upgraded flow leaves the Connector `UPDATE_FAILED`. The failure is not saved, so the Connector must be corrected and started again. On a node where `prepareForUpdate` or `applyUpdate` failed, the Connector is still pending and the next START retries both without the hook. On a node where the upgraded flow was applied, the Connector is no longer pending and the next START runs the new flow. + +If the upgraded Connector fails to start, the upgraded flow has already been saved, and the Connector is handled like any other Connector that fails to start. + == Supporting migration from a Versioned Process Group Connectors can implement a one-time migration flow that uses a source Versioned Process Group as a reference for populating a freshly created Connector. diff --git a/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorDTO.java b/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorDTO.java index 80f0f024c8b7..3256081f6116 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorDTO.java +++ b/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/dto/ConnectorDTO.java @@ -31,6 +31,7 @@ public class ConnectorDTO extends ComponentDTO { private String type; private BundleDTO bundle; private String state; // RUNNING, STOPPED + private String flowEvolutionStatus; private String managedProcessGroupId; private ConnectorConfigurationDTO activeConfiguration; private ConnectorConfigurationDTO workingConfiguration; @@ -40,6 +41,7 @@ public class ConnectorDTO extends ComponentDTO { private Boolean multipleVersionsAvailable; private Boolean extensionMissing; private Boolean supportsBacklogReporting; + private BundleDTO expectedBundle; private String configurationUrl; private String detailsUrl; @@ -81,6 +83,17 @@ public void setState(final String state) { this.state = state; } + @Schema(description = "The local or merged progress of a pending Connector flow evolution.", + allowableValues = {"INACTIVE", "EVOLVE_DRAIN_PENDING", "EVOLVE_DRAIN_COMPLETE", "FAILED"}, + accessMode = Schema.AccessMode.READ_ONLY) + public String getFlowEvolutionStatus() { + return flowEvolutionStatus; + } + + public void setFlowEvolutionStatus(final String flowEvolutionStatus) { + this.flowEvolutionStatus = flowEvolutionStatus; + } + @Schema(description = "The identifier of the root Process Group managed by this Connector.") public String getManagedProcessGroupId() { return managedProcessGroupId; @@ -174,6 +187,16 @@ public void setSupportsBacklogReporting(final Boolean supportsBacklogReporting) this.supportsBacklogReporting = supportsBacklogReporting; } + @Schema(description = "The Connector bundle expected by the cluster coordinator when verifying a START. " + + "Not persisted; used only for cluster run-status verification.") + public BundleDTO getExpectedBundle() { + return expectedBundle; + } + + public void setExpectedBundle(final BundleDTO expectedBundle) { + this.expectedBundle = expectedBundle; + } + @Schema(description = "The available actions that can be performed on this Connector.") public List getAvailableActions() { return availableActions; diff --git a/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/ConnectorRunStatusEntity.java b/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/ConnectorRunStatusEntity.java index cd08a7fa7603..0da3db8a7ef1 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/ConnectorRunStatusEntity.java +++ b/nifi-framework-bundle/nifi-framework/nifi-client-dto/src/main/java/org/apache/nifi/web/api/entity/ConnectorRunStatusEntity.java @@ -18,11 +18,14 @@ import io.swagger.v3.oas.annotations.media.Schema; import jakarta.xml.bind.annotation.XmlType; +import org.apache.nifi.web.api.dto.BundleDTO; @XmlType(name = "connectorRunStatus") public class ConnectorRunStatusEntity extends ComponentRunStatusEntity { private static final String[] SUPPORTED_STATE = {"RUNNING", "STOPPED", "DISABLED"}; + private BundleDTO expectedBundle; + @Override protected String[] getSupportedState() { return SUPPORTED_STATE; @@ -33,6 +36,16 @@ protected String[] getSupportedState() { public String getState() { return super.getState(); } + + @Schema(description = "The Connector bundle the cluster coordinator has loaded. When set on a START, each node " + + "rejects the request in the validation phase if its loaded bundle differs.") + public BundleDTO getExpectedBundle() { + return expectedBundle; + } + + public void setExpectedBundle(final BundleDTO expectedBundle) { + this.expectedBundle = expectedBundle; + } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java index a09138903eb4..d5473e717aab 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java @@ -21,9 +21,17 @@ import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.Response.Status.Family; import jakarta.ws.rs.core.Response.StatusType; +import org.apache.nifi.cluster.coordination.ClusterCoordinator; +import org.apache.nifi.cluster.coordination.node.DisconnectionCode; +import org.apache.nifi.cluster.coordination.node.NodeConnectionState; +import org.apache.nifi.cluster.coordination.node.NodeConnectionStatus; import org.apache.nifi.cluster.manager.NodeResponse; +import org.apache.nifi.cluster.manager.exception.NoConnectedNodesException; +import org.apache.nifi.cluster.protocol.NodeIdentifier; +import org.apache.nifi.components.connector.ConnectorClusterUnavailableException; import org.apache.nifi.components.connector.ConnectorRequestReplicator; import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.components.connector.FlowEvolutionStatus; import org.apache.nifi.controller.flow.FlowManager; import org.apache.nifi.web.api.entity.ConnectorEntity; import org.apache.nifi.web.api.entity.Entity; @@ -41,30 +49,69 @@ public class ClusteredConnectorRequestReplicator implements ConnectorRequestRepl private static final String GET = "GET"; private final Supplier requestReplicatorSupplier; + private final Supplier clusterCoordinatorSupplier; private final String replicationScheme; - public ClusteredConnectorRequestReplicator(final Supplier requestReplicatorSupplier, final boolean httpsEnabled) { + public ClusteredConnectorRequestReplicator(final Supplier requestReplicatorSupplier, final Supplier clusterCoordinatorSupplier, + final boolean httpsEnabled) { this.requestReplicatorSupplier = Objects.requireNonNull(requestReplicatorSupplier, "Request Replicator Supplier required"); + this.clusterCoordinatorSupplier = Objects.requireNonNull(clusterCoordinatorSupplier, "Cluster Coordinator Supplier required"); this.replicationScheme = httpsEnabled ? "https" : "http"; } @Override public ConnectorState getState(final String connectorId) throws IOException { + final ConnectorEntity connectorEntity = getConnectorEntity(connectorId, false); + final String stateName = connectorEntity.getComponent().getState(); + logger.debug("getState: Connector [{}] — state from response: [{}]", connectorId, stateName); + try { + return ConnectorState.valueOf(stateName); + } catch (final IllegalArgumentException e) { + throw new IOException("Received unknown Connector state '" + stateName + "' for Connector with ID " + connectorId); + } + } + + @Override + public FlowEvolutionStatus getFlowEvolutionStatus(final String connectorId) throws IOException { + final ConnectorEntity connectorEntity = getConnectorEntity(connectorId, true); + final String statusName = connectorEntity.getComponent().getFlowEvolutionStatus(); + if (statusName == null) { + return FlowEvolutionStatus.INACTIVE; + } + + try { + return FlowEvolutionStatus.valueOf(statusName); + } catch (final IllegalArgumentException e) { + throw new IOException("Received unknown flow evolution status '" + statusName + "' for Connector with ID " + connectorId); + } + } + + private ConnectorEntity getConnectorEntity(final String connectorId, final boolean requireAllConnected) throws IOException { final RequestReplicator requestReplicator = getRequestReplicator(); + verifyClusterMembership(connectorId, requireAllConnected); + final URI uri = URI.create(replicationScheme + "://localhost/nifi-api/connectors/" + connectorId); - logger.debug("getState: Connector [{}] — replicating GET to URI [{}]", connectorId, uri); + logger.debug("Connector [{}] — replicating GET to URI [{}]", connectorId, uri); // User is null. GET /connectors/{id} API endpoint has special logic for authorizing requests made by nifi cluster nodes based on mTLS cert SANs - final AsyncClusterResponse asyncResponse = requestReplicator.replicate(null, GET, uri, Map.of(), Map.of()); + final AsyncClusterResponse asyncResponse; + try { + asyncResponse = requestReplicator.replicate(null, GET, uri, Map.of(), Map.of()); + } catch (final NoConnectedNodesException e) { + throw new ConnectorClusterUnavailableException("No connected nodes while retrieving Connector %s".formatted(connectorId), e); + } try { final NodeResponse mergedNodeResponse = asyncResponse.awaitMergedResponse(); + if (mergedNodeResponse == null) { + throw new IOException("No merged response received while retrieving Connector " + connectorId); + } final Entity updatedEntity = mergedNodeResponse.getUpdatedEntity(); final Response response = mergedNodeResponse.getClientResponse(); if (response != null) { final int statusCode = response.getStatusInfo().getStatusCode(); - logger.debug("getState: Connector [{}] — merged response status [{}] ({})", connectorId, statusCode, response.getStatusInfo().getReasonPhrase()); + logger.debug("Connector [{}] — merged response status [{}] ({})", connectorId, statusCode, response.getStatusInfo().getReasonPhrase()); verifyResponse(response.getStatusInfo(), connectorId); } else if (mergedNodeResponse.hasThrowable()) { throw new IOException("Failed to retrieve Connector state for " + connectorId, mergedNodeResponse.getThrowable()); @@ -77,10 +124,10 @@ public ConnectorState getState(final String connectorId) throws IOException { // only return the state from whichever single node was selected as the "client response". final ConnectorEntity connectorEntity; if (updatedEntity instanceof final ConnectorEntity mergedConnectorEntity) { - logger.debug("getState: Connector [{}] - using merged updatedEntity", connectorId); + logger.debug("Connector [{}] - using merged updatedEntity", connectorId); connectorEntity = mergedConnectorEntity; } else { - logger.debug("getState: Connector [{}] — updatedEntity is [{}], falling back to readEntity()", connectorId, + logger.debug("Connector [{}] — updatedEntity is [{}], falling back to readEntity()", connectorId, updatedEntity == null ? "null" : updatedEntity.getClass().getSimpleName()); connectorEntity = response.readEntity(ConnectorEntity.class); } @@ -93,19 +140,41 @@ public ConnectorState getState(final String connectorId) throws IOException { + ". Permissions canRead=" + (connectorEntity.getPermissions() != null ? connectorEntity.getPermissions().getCanRead() : "null")); } - final String stateName = connectorEntity.getComponent().getState(); - logger.debug("getState: Connector [{}] — state from response: [{}]", connectorId, stateName); - try { - return ConnectorState.valueOf(stateName); - } catch (final IllegalArgumentException e) { - throw new IOException("Received unknown Connector state '" + stateName + "' for Connector with ID " + connectorId); + if (requireAllConnected) { + for (final NodeIdentifier node : asyncResponse.getNodesInvolved()) { + final NodeResponse nodeResponse = asyncResponse.getNodeResponse(node); + if (nodeResponse == null || !nodeResponse.is2xx()) { + throw new IOException("Failed to retrieve flow evolution status for Connector " + connectorId + " from node " + node); + } + } } + return connectorEntity; } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for response for status of Connector with ID " + connectorId, e); } } + private void verifyClusterMembership(final String connectorId, final boolean requireAllConnected) throws IOException { + final ClusterCoordinator clusterCoordinator = clusterCoordinatorSupplier.get(); + if (clusterCoordinator == null || !clusterCoordinator.isConnected()) { + throw new ConnectorClusterUnavailableException("No connected nodes while retrieving Connector %s".formatted(connectorId)); + } + + for (final NodeConnectionStatus connectionStatus : clusterCoordinator.getConnectionStatuses()) { + final NodeConnectionState state = connectionStatus.getState(); + if (state == NodeConnectionState.CONNECTING + || (state == NodeConnectionState.DISCONNECTED && connectionStatus.getDisconnectCode() == DisconnectionCode.NOT_YET_CONNECTED)) { + throw new ConnectorClusterUnavailableException("Cannot retrieve Connector %s because node %s is still joining the cluster" + .formatted(connectorId, connectionStatus.getNodeIdentifier())); + } + if (requireAllConnected && state != NodeConnectionState.CONNECTED && state != NodeConnectionState.REMOVED) { + throw new IOException("Cannot retrieve flow evolution status for Connector %s because node %s is %s" + .formatted(connectorId, connectionStatus.getNodeIdentifier(), state)); + } + } + } + @Override public void setFlowManager(final FlowManager flowManager) { } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/manager/ConnectorEntityMerger.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/manager/ConnectorEntityMerger.java index 726c1d9b240a..71df47ec612b 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/manager/ConnectorEntityMerger.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/manager/ConnectorEntityMerger.java @@ -18,6 +18,8 @@ import org.apache.nifi.cluster.protocol.NodeIdentifier; import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.components.connector.FlowEvolutionStatus; +import org.apache.nifi.web.api.dto.BundleDTO; import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; import org.apache.nifi.web.api.dto.ConnectorActionDTO; import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO; @@ -28,11 +30,16 @@ import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.TreeMap; public class ConnectorEntityMerger { + static final String LOADED_BUNDLE_MISMATCH_REASON = "Cluster nodes load different Connector versions: "; + private static final String CHANGE_VERSION_ACTION = "CHANGE_VERSION"; + private static final String START_ACTION = "START"; /** * Merges the ConnectorEntity responses. * @@ -113,6 +120,8 @@ private static void mergeDtos(final ConnectorDTO clientDto, final Map dtoMap) { + final Map loadedBundles = new TreeMap<>(); + for (final Map.Entry entry : dtoMap.entrySet()) { + final ConnectorDTO nodeConnector = entry.getValue(); + if (nodeConnector == null || nodeConnector.getBundle() == null) { + continue; + } + + final BundleDTO bundle = nodeConnector.getBundle(); + loadedBundles.put(entry.getKey().getApiAddress() + ":" + entry.getKey().getApiPort(), + bundle.getGroup() + ":" + bundle.getArtifact() + ":" + bundle.getVersion()); + } + + if (new HashSet<>(loadedBundles.values()).size() <= 1) { + return; + } + + final ConnectorActionDTO startAction = findAction(clientDto, START_ACTION); + if (startAction != null) { + startAction.setAllowed(Boolean.FALSE); + startAction.setReasonNotAllowed(LOADED_BUNDLE_MISMATCH_REASON + loadedBundles); + } + } + private static ConnectorActionDTO findOrCreateChangeVersionAction(final ConnectorDTO clientDto) { final ConnectorActionDTO existingAction = findAction(clientDto, CHANGE_VERSION_ACTION); if (existingAction != null) { @@ -202,6 +239,17 @@ private static void mergeState(final ConnectorDTO clientDto, final Map dtoMap) { + final List statuses = new ArrayList<>(dtoMap.size()); + for (final ConnectorDTO nodeConnector : dtoMap.values()) { + if (nodeConnector != null && nodeConnector.getFlowEvolutionStatus() != null) { + statuses.add(FlowEvolutionStatus.valueOf(nodeConnector.getFlowEvolutionStatus())); + } + } + + clientDto.setFlowEvolutionStatus(FlowEvolutionStatus.merge(statuses).name()); + } + private static int getStatePriority(final String state) { if (state == null) { return 0; diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/framework/configuration/ConnectorRequestReplicatorConfiguration.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/framework/configuration/ConnectorRequestReplicatorConfiguration.java index 19453bfd992f..d52e5f94f752 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/framework/configuration/ConnectorRequestReplicatorConfiguration.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/framework/configuration/ConnectorRequestReplicatorConfiguration.java @@ -17,6 +17,7 @@ package org.apache.nifi.framework.configuration; +import org.apache.nifi.cluster.coordination.ClusterCoordinator; import org.apache.nifi.cluster.coordination.http.replication.ClusteredConnectorRequestReplicator; import org.apache.nifi.cluster.coordination.http.replication.RequestReplicator; import org.apache.nifi.components.connector.ConnectorRequestReplicator; @@ -30,9 +31,8 @@ public class ConnectorRequestReplicatorConfiguration { @Bean - public ConnectorRequestReplicator connectorRequestReplicator( - final NiFiProperties nifiProperties, - final ObjectProvider requestReplicatorProvider) { + public ConnectorRequestReplicator connectorRequestReplicator(final NiFiProperties nifiProperties, final ObjectProvider requestReplicatorProvider, + final ObjectProvider clusterCoordinatorProvider) { if (nifiProperties.isClustered()) { // We have to use an ObjectProvider here and obtain a Supplier because of a circular dependency. @@ -40,7 +40,8 @@ public ConnectorRequestReplicator connectorRequestReplicator( // available before attempting to use the ConnectorRequestReplicator. final String httpsHostname = nifiProperties.getProperty(NiFiProperties.WEB_HTTPS_HOST); final boolean httpsEnabled = httpsHostname != null; - return new ClusteredConnectorRequestReplicator(requestReplicatorProvider::getIfAvailable, httpsEnabled); + return new ClusteredConnectorRequestReplicator(requestReplicatorProvider::getIfAvailable, + clusterCoordinatorProvider::getIfAvailable, httpsEnabled); } return new StandaloneConnectorRequestReplicator(); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java new file mode 100644 index 000000000000..f15aaaaff3d7 --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java @@ -0,0 +1,133 @@ +/* + * 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.cluster.coordination.http.replication; + +import org.apache.nifi.cluster.coordination.ClusterCoordinator; +import org.apache.nifi.cluster.coordination.node.DisconnectionCode; +import org.apache.nifi.cluster.coordination.node.NodeConnectionState; +import org.apache.nifi.cluster.coordination.node.NodeConnectionStatus; +import org.apache.nifi.cluster.manager.NodeResponse; +import org.apache.nifi.cluster.manager.exception.NoConnectedNodesException; +import org.apache.nifi.components.connector.ConnectorClusterUnavailableException; +import org.apache.nifi.components.connector.FlowEvolutionStatus; +import org.apache.nifi.web.api.dto.ConnectorDTO; +import org.apache.nifi.web.api.entity.ConnectorEntity; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class TestClusteredConnectorRequestReplicator { + private static final String CONNECTOR_ID = "connector-1"; + + @Test + void testFlowEvolutionStatusWaitsForMembershipToSettle() { + final RequestReplicator requestReplicator = mock(RequestReplicator.class); + final ClusterCoordinator clusterCoordinator = mock(ClusterCoordinator.class); + final NodeConnectionStatus connectionStatus = mock(NodeConnectionStatus.class); + when(clusterCoordinator.getConnectionStatuses()).thenReturn(List.of(connectionStatus)); + final ClusteredConnectorRequestReplicator replicator = new ClusteredConnectorRequestReplicator( + () -> requestReplicator, () -> clusterCoordinator, false); + + when(clusterCoordinator.isConnected()).thenReturn(false); + assertThrows(ConnectorClusterUnavailableException.class, () -> replicator.getFlowEvolutionStatus(CONNECTOR_ID)); + + when(clusterCoordinator.isConnected()).thenReturn(true); + when(connectionStatus.getState()).thenReturn(NodeConnectionState.CONNECTING); + assertThrows(ConnectorClusterUnavailableException.class, () -> replicator.getFlowEvolutionStatus(CONNECTOR_ID)); + + when(connectionStatus.getState()).thenReturn(NodeConnectionState.DISCONNECTED); + when(connectionStatus.getDisconnectCode()).thenReturn(DisconnectionCode.NOT_YET_CONNECTED); + assertThrows(ConnectorClusterUnavailableException.class, () -> replicator.getFlowEvolutionStatus(CONNECTOR_ID)); + + verify(requestReplicator, never()).replicate(isNull(), eq("GET"), any(), anyMap(), anyMap()); + } + + @Test + void testFlowEvolutionStatusFailsWhenNodeDisconnected() { + final RequestReplicator requestReplicator = mock(RequestReplicator.class); + final ClusterCoordinator clusterCoordinator = mock(ClusterCoordinator.class); + final NodeConnectionStatus connectionStatus = mock(NodeConnectionStatus.class); + when(clusterCoordinator.isConnected()).thenReturn(true); + when(clusterCoordinator.getConnectionStatuses()).thenReturn(List.of(connectionStatus)); + when(connectionStatus.getState()).thenReturn(NodeConnectionState.DISCONNECTED); + + final ClusteredConnectorRequestReplicator replicator = new ClusteredConnectorRequestReplicator( + () -> requestReplicator, () -> clusterCoordinator, false); + + assertThrows(IOException.class, () -> replicator.getFlowEvolutionStatus(CONNECTOR_ID)); + verify(requestReplicator, never()).replicate(isNull(), eq("GET"), any(), anyMap(), anyMap()); + } + + @Test + void testFlowEvolutionStatusReturnsMergedFailure() throws Exception { + final RequestReplicator requestReplicator = mock(RequestReplicator.class); + final ClusterCoordinator clusterCoordinator = mock(ClusterCoordinator.class); + final AsyncClusterResponse asyncResponse = mock(AsyncClusterResponse.class); + final NodeResponse nodeResponse = mock(NodeResponse.class); + + when(clusterCoordinator.isConnected()).thenReturn(true); + when(clusterCoordinator.getConnectionStatuses()).thenReturn(List.of()); + when(requestReplicator.replicate(isNull(), eq("GET"), any(), anyMap(), anyMap())).thenReturn(asyncResponse); + when(asyncResponse.awaitMergedResponse()).thenReturn(nodeResponse); + when(nodeResponse.getUpdatedEntity()).thenReturn(connectorEntity(FlowEvolutionStatus.FAILED)); + + final ClusteredConnectorRequestReplicator replicator = new ClusteredConnectorRequestReplicator( + () -> requestReplicator, () -> clusterCoordinator, false); + + assertEquals(FlowEvolutionStatus.FAILED, replicator.getFlowEvolutionStatus(CONNECTOR_ID)); + } + + @Test + void testReplicateNoConnectedNodesIsTranslated() { + final RequestReplicator requestReplicator = mock(RequestReplicator.class); + final ClusterCoordinator clusterCoordinator = mock(ClusterCoordinator.class); + final NoConnectedNodesException cause = new NoConnectedNodesException(); + + when(clusterCoordinator.isConnected()).thenReturn(true); + when(clusterCoordinator.getConnectionStatuses()).thenReturn(List.of()); + when(requestReplicator.replicate(isNull(), eq("GET"), any(), anyMap(), anyMap())).thenThrow(cause); + + final ClusteredConnectorRequestReplicator replicator = new ClusteredConnectorRequestReplicator( + () -> requestReplicator, () -> clusterCoordinator, false); + + final ConnectorClusterUnavailableException failure = assertThrows(ConnectorClusterUnavailableException.class, + () -> replicator.getFlowEvolutionStatus(CONNECTOR_ID)); + assertSame(cause, failure.getCause()); + } + + private static ConnectorEntity connectorEntity(final FlowEvolutionStatus status) { + final ConnectorDTO connector = new ConnectorDTO(); + connector.setFlowEvolutionStatus(status.name()); + final ConnectorEntity entity = new ConnectorEntity(); + entity.setComponent(connector); + return entity; + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/manager/ConnectorEntityMergerTest.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/manager/ConnectorEntityMergerTest.java index 5b3e985bab54..167d4d809d6e 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/manager/ConnectorEntityMergerTest.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/manager/ConnectorEntityMergerTest.java @@ -17,7 +17,9 @@ package org.apache.nifi.cluster.manager; import org.apache.nifi.cluster.protocol.NodeIdentifier; +import org.apache.nifi.components.connector.FlowEvolutionStatus; import org.apache.nifi.web.api.dto.AllowableValueDTO; +import org.apache.nifi.web.api.dto.BundleDTO; import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; import org.apache.nifi.web.api.dto.ConnectorActionDTO; import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO; @@ -139,6 +141,67 @@ void testMergeChangeVersionAction() { assertNull(mergedAction.getReasonNotAllowed()); } + @Test + void testMergeRejectsStartWhenNodesLoadDifferentBundles() { + final ConnectorEntity clientEntity = createConnectorEntity("connector1", "STOPPED"); + final ConnectorEntity nodeEntity = createConnectorEntity("connector1", "STOPPED"); + final Map entityMap = new HashMap<>(); + entityMap.put(getNodeIdentifier("client", 8000), clientEntity); + entityMap.put(getNodeIdentifier("node", 8001), nodeEntity); + clientEntity.getComponent().setBundle(new BundleDTO("org.apache.nifi", "test-nar", "2.0.0")); + nodeEntity.getComponent().setBundle(new BundleDTO("org.apache.nifi", "test-nar", "1.0.0")); + clientEntity.getComponent().setAvailableActions(List.of(action("START", true, null), changeVersionAction(true, null))); + nodeEntity.getComponent().setAvailableActions(List.of(action("START", true, null), changeVersionAction(true, null))); + + ConnectorEntityMerger.merge(clientEntity, entityMap); + + final ConnectorActionDTO startAction = findAction(clientEntity, "START"); + assertFalse(startAction.getAllowed()); + assertTrue(startAction.getReasonNotAllowed().startsWith(ConnectorEntityMerger.LOADED_BUNDLE_MISMATCH_REASON)); + assertTrue(startAction.getReasonNotAllowed().contains("localhost:8000=org.apache.nifi:test-nar:2.0.0")); + assertTrue(startAction.getReasonNotAllowed().contains("localhost:8001=org.apache.nifi:test-nar:1.0.0")); + assertTrue(findChangeVersionAction(clientEntity).getAllowed()); + } + + @Test + void testMergeAllowsStartWhenNodesLoadSameBundle() { + final ConnectorEntity clientEntity = createConnectorEntity("connector1", "STOPPED"); + final ConnectorEntity nodeEntity = createConnectorEntity("connector1", "STOPPED"); + final Map entityMap = new HashMap<>(); + entityMap.put(getNodeIdentifier("client", 8000), clientEntity); + entityMap.put(getNodeIdentifier("node", 8001), nodeEntity); + clientEntity.getComponent().setBundle(new BundleDTO("org.apache.nifi", "test-nar", "2.0.0")); + nodeEntity.getComponent().setBundle(new BundleDTO("org.apache.nifi", "test-nar", "2.0.0")); + clientEntity.getComponent().setAvailableActions(List.of(action("START", true, null))); + nodeEntity.getComponent().setAvailableActions(List.of(action("START", true, null))); + + ConnectorEntityMerger.merge(clientEntity, entityMap); + + assertTrue(findAction(clientEntity, "START").getAllowed()); + assertNull(findAction(clientEntity, "START").getReasonNotAllowed()); + } + + @Test + void testMergeFlowEvolutionStatusCombinesNodeStatuses() { + final ConnectorEntity clientEntity = createConnectorEntity("connector1", "STOPPED"); + final ConnectorEntity node1Entity = createConnectorEntity("connector1", "STOPPED"); + final ConnectorEntity node2Entity = createConnectorEntity("connector1", "STOPPED"); + final Map entityMap = new HashMap<>(); + entityMap.put(getNodeIdentifier("client", 8000), clientEntity); + entityMap.put(getNodeIdentifier("node1", 8001), node1Entity); + entityMap.put(getNodeIdentifier("node2", 8002), node2Entity); + + clientEntity.getComponent().setFlowEvolutionStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE.name()); + node1Entity.getComponent().setFlowEvolutionStatus(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING.name()); + ConnectorEntityMerger.merge(clientEntity, entityMap); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING.name(), clientEntity.getComponent().getFlowEvolutionStatus()); + + clientEntity.getComponent().setFlowEvolutionStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE.name()); + node1Entity.getComponent().setFlowEvolutionStatus(null); + ConnectorEntityMerger.merge(clientEntity, entityMap); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE.name(), clientEntity.getComponent().getFlowEvolutionStatus()); + } + @Test void testMergeConfigurationStepsWithDifferentAllowableValues() { final ConnectorEntity clientEntity = createConnectorEntityWithConfig( @@ -339,9 +402,21 @@ private ConnectorActionDTO changeVersionAction(final Boolean allowed, final Stri return action; } + private ConnectorActionDTO action(final String name, final Boolean allowed, final String reasonNotAllowed) { + final ConnectorActionDTO action = new ConnectorActionDTO(); + action.setName(name); + action.setAllowed(allowed); + action.setReasonNotAllowed(reasonNotAllowed); + return action; + } + private ConnectorActionDTO findChangeVersionAction(final ConnectorEntity entity) { + return findAction(entity, "CHANGE_VERSION"); + } + + private ConnectorActionDTO findAction(final ConnectorEntity entity, final String actionName) { for (final ConnectorActionDTO action : entity.getComponent().getAvailableActions()) { - if ("CHANGE_VERSION".equals(action.getName())) { + if (actionName.equals(action.getName())) { return action; } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java index 910a07be88f0..d9535ce97fe0 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java @@ -4112,18 +4112,27 @@ private void verifyCanRemoveMissingComponents(final ProcessGroup processGroup, f final Map proposedConnectionsByVersionedId = proposedGroup.getConnections().stream() .collect(Collectors.toMap(VersionedComponent::getIdentifier, Function.identity())); - // match group's current connections to proposed connections to determine if they've been removed + // A missing connection, or one whose source changed, is removed and recreated. Either change drops + // queued data, so reject it before synchronization begins. A destination change updates the connection in place. for (final Connection connection : processGroup.getConnections()) { final String versionedId = connection.getVersionedComponentId().orElse( VersionedComponentFlowMapper.generateVersionedComponentId(connection.getIdentifier())); final VersionedConnection proposedConnection = proposedConnectionsByVersionedId.get(versionedId); + final FlowFileQueue flowFileQueue = connection.getFlowFileQueue(); + if (flowFileQueue.isEmpty()) { + continue; + } + if (proposedConnection == null) { - // connection doesn't exist in proposed connections, make sure it doesn't have any data in it - final FlowFileQueue flowFileQueue = connection.getFlowFileQueue(); - if (!flowFileQueue.isEmpty()) { - throw new IllegalStateException(processGroup + " cannot be updated to the proposed flow because the proposed flow " - + "does not contain a match for " + connection + " and the connection currently has data in the queue."); - } + throw new IllegalStateException(processGroup + " cannot be updated to the proposed flow because the proposed flow " + + "does not contain a match for " + connection + " and the connection currently has data in the queue."); + } + + final String existingSourceId = connection.getSource().getVersionedComponentId().orElse(null); + final String proposedSourceId = proposedConnection.getSource().getId(); + if (existingSourceId != null && !Objects.equals(proposedSourceId, existingSourceId)) { + throw new IllegalStateException(processGroup + " cannot be updated to the proposed flow because the proposed flow " + + "changes the source of " + connection + " and the connection currently has data in the queue."); } } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java index b35164561cc6..4ad55f6a5c6d 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java @@ -4028,6 +4028,11 @@ public void updateFlow(final VersionedExternalFlow proposedSnapshot, final Strin @Override public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedSnapshot) { + restoreFlowPreservingIdentifiers(proposedSnapshot, autoResumeState); + } + + @Override + public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedSnapshot, final boolean resumeComponentState) { // Use the Instance Identifier captured in the persisted flow as the runtime identifier for every component. This is // required so that Connection identifiers (and therefore FlowFile queue identifiers) match what was in use before // the flow was persisted. Without this, queued FlowFiles in the FlowFile Repository cannot be re-associated with @@ -4035,10 +4040,10 @@ public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow propose final ComponentIdGenerator idGenerator = (proposedId, instanceId, destinationGroupId) -> instanceId; final VersionedComponentStateLookup stateLookup = VersionedComponentStateLookup.IDENTITY_LOOKUP; - // When nifi.flowcontroller.autoResumeState is false, restore the flow structure (so queued FlowFiles can be - // re-associated with their Connections) without resuming any component to its previously running or enabled - // state. Otherwise, restore each component to the running/enabled state captured in the persisted flow. - final ComponentScheduler componentScheduler = autoResumeState + // resumeComponentState=false restores the flow structure (so queued FlowFiles can be re-associated with their + // Connections) without resuming any component to its previously running or enabled state. When true, restore each + // component to the running/enabled state captured in the persisted flow. + final ComponentScheduler componentScheduler = resumeComponentState ? new DefaultComponentScheduler(controllerServiceProvider, stateLookup) : new NonStartingComponentScheduler(controllerServiceProvider, stateLookup); @@ -4058,17 +4063,7 @@ public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow propose // with encryption enabled so the comparison between "current" and "proposed" sensitive values operates on values that are // decrypted the same way on both sides; otherwise every sensitive property appears to differ and the value written back to // the live component is the encrypted payload rather than the plaintext (or parameter reference) originally captured. - final FlowMappingOptions flowMappingOptions = new FlowMappingOptions.Builder() - .mapSensitiveConfiguration(true) - .mapPropertyDescriptors(true) - .stateLookup(stateLookup) - .componentIdLookup(ComponentIdLookup.VERSIONED_OR_GENERATE) - .mapInstanceIdentifiers(true) - .mapControllerServiceReferencesToVersionedId(true) - .mapFlowRegistryClientId(false) - .mapAssetReferences(false) - .propertyEncryptionProvider(propertyEncryptionProvider) - .build(); + final FlowMappingOptions flowMappingOptions = FlowMappingOptions.forPersistedFlow(propertyEncryptionProvider, stateLookup); synchronizeFlow(proposedSnapshot, synchronizationOptions, flowMappingOptions); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java index 361e3eabb1b1..482b1f0ba105 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java @@ -25,6 +25,7 @@ import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.connector.AssetReference; import org.apache.nifi.components.connector.ConnectorConfiguration; +import org.apache.nifi.components.connector.ConnectorFlowSnapshot; import org.apache.nifi.components.connector.ConnectorNode; import org.apache.nifi.components.connector.ConnectorState; import org.apache.nifi.components.connector.ConnectorValueReference; @@ -163,6 +164,11 @@ public VersionedComponentFlowMapper(final ExtensionManager extensionManager, fin } } + public static VersionedComponentFlowMapper forPersistedFlow(final ExtensionManager extensionManager, + final PropertyEncryptionProvider propertyEncryptionProvider, final VersionedComponentStateLookup stateLookup) { + return new VersionedComponentFlowMapper(extensionManager, FlowMappingOptions.forPersistedFlow(propertyEncryptionProvider, stateLookup)); + } + /** * Map the given process group to a versioned process group without any use of an actual flow registry even if the * group is currently versioned in a registry. @@ -1102,13 +1108,14 @@ private org.apache.nifi.flow.ScheduledState mapScheduledState(final ScheduledSta } /** - * Map the given ConnectorNode to a VersionedConnector. When the Connector is in Troubleshooting state, the Connector's - * Managed Process Group is also serialized into the VersionedConnector so that any user modifications made while in - * Troubleshooting mode survive a restart. The provided ControllerServiceProvider is required for mapping the Managed - * Process Group; if {@code null}, the Managed Process Group is not serialized even if the Connector is in Troubleshooting. + * Map the given ConnectorNode to a VersionedConnector. The parameter context, managed-flow bundle, and active + * configuration are written from the node's atomic snapshot. While the connector is in Troubleshooting, the live + * managed group is written so the user's edits survive a restart; otherwise the managed group comes from that + * snapshot. The provided ControllerServiceProvider is required for the live mapping; if {@code null} while + * Troubleshooting, the managed group is omitted. * * @param connectorNode the connector node to map - * @param controllerServiceProvider the controller service provider used when mapping the Managed Process Group; may be null + * @param controllerServiceProvider the controller service provider used when mapping the live Managed Process Group; may be null * @return the mapped VersionedConnector */ public VersionedConnector mapConnector(final ConnectorNode connectorNode, final ControllerServiceProvider controllerServiceProvider) { @@ -1117,18 +1124,32 @@ public VersionedConnector mapConnector(final ConnectorNode connectorNode, final versionedConnector.setName(connectorNode.getName()); versionedConnector.setScheduledState(mapConnectorState(connectorNode.getDesiredState())); versionedConnector.setType(connectorNode.getCanonicalClassName()); + + final ConnectorFlowSnapshot authoritativeSnapshot = connectorNode.getAuthoritativeFlowSnapshot(); + final FrameworkFlowContext activeFlowContext = connectorNode.getActiveFlowContext(); versionedConnector.setBundle(mapBundle(connectorNode.getBundleCoordinate())); - final List activeFlowConfiguration = createVersionedConfigurationSteps(connectorNode.getActiveFlowContext()); + final ConnectorConfiguration activeConfiguration = authoritativeSnapshot == null + ? activeFlowContext.getConfigurationContext().toConnectorConfiguration() + : authoritativeSnapshot.activeConfiguration(); + final List activeFlowConfiguration = createVersionedConfigurationSteps(activeConfiguration); versionedConnector.setActiveFlowConfiguration(activeFlowConfiguration); final List workingFlowConfiguration = createVersionedConfigurationSteps(connectorNode.getWorkingFlowContext()); versionedConnector.setWorkingFlowConfiguration(workingFlowConfiguration); + if (authoritativeSnapshot != null) { + versionedConnector.setManagedParameterContext(authoritativeSnapshot.parameterContext()); + versionedConnector.setManagedParameterSecretReferences( + mapParameterSecretReferences(authoritativeSnapshot.parameterSecretReferences())); + versionedConnector.setManagedFlowBundle(authoritativeSnapshot.bundle()); + } + if (connectorNode.getCurrentState() == ConnectorState.TROUBLESHOOTING && controllerServiceProvider != null) { final ProcessGroup managedGroup = connectorNode.getActiveFlowContext().getManagedProcessGroup(); - final VersionedProcessGroup versionedManagedGroup = mapNonVersionedProcessGroup(managedGroup, controllerServiceProvider); - versionedConnector.setManagedProcessGroup(versionedManagedGroup); + versionedConnector.setManagedProcessGroup(mapNonVersionedProcessGroup(managedGroup, controllerServiceProvider)); + } else if (authoritativeSnapshot != null) { + versionedConnector.setManagedProcessGroup(authoritativeSnapshot.flow()); } return versionedConnector; @@ -1140,6 +1161,10 @@ private List createVersionedConfigurationSteps(final } final ConnectorConfiguration configuration = flowContext.getConfigurationContext().toConnectorConfiguration(); + return createVersionedConfigurationSteps(configuration); + } + + private List createVersionedConfigurationSteps(final ConnectorConfiguration configuration) { final List configurationSteps = new ArrayList<>(); for (final NamedStepConfiguration stepConfiguration : configuration.getNamedStepConfigurations()) { @@ -1161,24 +1186,42 @@ private Map mapPropertyValues(final St continue; } - final VersionedConnectorValueReference versionedReference = new VersionedConnectorValueReference(); - versionedReference.setValueType(valueReference.getValueType().name()); - - switch (valueReference) { - case StringLiteralValue stringLiteral -> versionedReference.setValue(stringLiteral.getValue()); - case AssetReference assetRef -> versionedReference.setAssetIds(assetRef.getAssetIdentifiers()); - case SecretReference secretRef -> { - versionedReference.setProviderId(secretRef.getProviderId()); - versionedReference.setProviderName(secretRef.getProviderName()); - versionedReference.setSecretName(secretRef.getSecretName()); - versionedReference.setFullyQualifiedSecretName(secretRef.getFullyQualifiedName()); - } + versionedProperties.put(entry.getKey(), mapValueReference(valueReference)); + } + + return versionedProperties; + } + + private Map mapParameterSecretReferences(final Map parameterSecretReferences) { + if (parameterSecretReferences == null || parameterSecretReferences.isEmpty()) { + return null; + } + + final Map versionedReferences = new HashMap<>(); + for (final Map.Entry entry : parameterSecretReferences.entrySet()) { + if (entry.getValue() != null) { + versionedReferences.put(entry.getKey(), mapValueReference(entry.getValue())); } + } + return versionedReferences.isEmpty() ? null : versionedReferences; + } - versionedProperties.put(entry.getKey(), versionedReference); + private VersionedConnectorValueReference mapValueReference(final ConnectorValueReference valueReference) { + final VersionedConnectorValueReference versionedReference = new VersionedConnectorValueReference(); + versionedReference.setValueType(valueReference.getValueType().name()); + + switch (valueReference) { + case StringLiteralValue stringLiteral -> versionedReference.setValue(stringLiteral.getValue()); + case AssetReference assetRef -> versionedReference.setAssetIds(assetRef.getAssetIdentifiers()); + case SecretReference secretRef -> { + versionedReference.setProviderId(secretRef.getProviderId()); + versionedReference.setProviderName(secretRef.getProviderName()); + versionedReference.setSecretName(secretRef.getSecretName()); + versionedReference.setFullyQualifiedSecretName(secretRef.getFullyQualifiedName()); + } } - return versionedProperties; + return versionedReference; } private VersionedConnectorState mapConnectorState(final ConnectorState connectorState) { diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java index 5916ef43cd33..0e84c6a388c3 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java @@ -214,6 +214,25 @@ public void testControllerServicesMapsToInstanceId() { testControllerServicesMapsToProperId(false); } + @Test + public void testPersistedFlowMappingUsesInstanceIdForControllerServiceReferences() { + final VersionedComponentFlowMapper mapper = VersionedComponentFlowMapper.forPersistedFlow( + mock(ExtensionManager.class), new RecordingPropertyEncryptionProvider(), VersionedComponentStateLookup.IDENTITY_LOOKUP); + + final ControllerServiceNode mockServiceNode = mock(ControllerServiceNode.class); + when(mockServiceNode.getIdentifier()).thenReturn("1234"); + when(mockServiceNode.getVersionedComponentId()).thenReturn(Optional.of("versioned")); + + final ControllerServiceProvider serviceProvider = mock(ControllerServiceProvider.class); + when(serviceProvider.getControllerServiceNode("1234")).thenReturn(mockServiceNode); + final Map properties = new HashMap<>(); + properties.put("Service A", "1234"); + + final ProcessorNode procNode = createProcessorNode(properties); + final VersionedProcessor versionedProcessor = mapper.mapProcessor(procNode, serviceProvider, Collections.emptySet(), Collections.emptyMap()); + assertEquals("1234", versionedProcessor.getProperties().get("Service A")); + } + private void testControllerServicesMapsToProperId(final boolean useVersionedId) { final ExtensionManager extensionManager = mock(ExtensionManager.class); final FlowMappingOptions mappingOptions = new FlowMappingOptions.Builder() diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java new file mode 100644 index 000000000000..bedca7e6c383 --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java @@ -0,0 +1,31 @@ +/* + * 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; + +/** + * Thrown when a clustered Connector request cannot be completed because no node is connected yet. + */ +public class ConnectorClusterUnavailableException extends RuntimeException { + public ConnectorClusterUnavailableException(final String message) { + super(message); + } + + public ConnectorClusterUnavailableException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshot.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshot.java new file mode 100644 index 000000000000..9ff116f8b369 --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshot.java @@ -0,0 +1,49 @@ +/* + * 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.flow.Bundle; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.flow.VersionedProcessGroup; + +import java.util.Map; + +/** + * Authoritative Connector flow state serialized as one consistent unit. + * + * @param flow the managed flow as applied, never the live group while in troubleshooting; persisted as + * {@code VersionedConnector.managedProcessGroup} + * @param parameterContext the managed parameter context of that flow, or null; persisted as + * {@code VersionedConnector.managedParameterContext}. Sensitive values are encrypted. + * @param parameterSecretReferences bindings from managed parameter names to configuration secret references; persisted + * as {@code VersionedConnector.managedParameterSecretReferences} + * @param bundle the Connector bundle that built the flow; persisted as {@code VersionedConnector.managedFlowBundle} + * @param activeConfiguration the migrated ACTIVE configuration persisted with this snapshot as + * {@code VersionedConnector.activeFlowConfiguration} + */ +public record ConnectorFlowSnapshot( + VersionedProcessGroup flow, + VersionedParameterContext parameterContext, + Map parameterSecretReferences, + Bundle bundle, + ConnectorConfiguration activeConfiguration) { + + public ConnectorFlowSnapshot { + parameterSecretReferences = parameterSecretReferences == null ? Map.of() : Map.copyOf(parameterSecretReferences); + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java index 28c78a46305d..e4314d28769b 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java @@ -31,6 +31,7 @@ import org.apache.nifi.engine.FlowEngine; import org.apache.nifi.flow.Bundle; import org.apache.nifi.flow.VersionedConfigurationStep; +import org.apache.nifi.flow.VersionedConnector; import org.apache.nifi.logging.ComponentLog; import java.time.Duration; @@ -38,6 +39,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public interface ConnectorNode extends ComponentAuthorizable, VersionedComponent { @@ -192,6 +194,27 @@ default void setCustomLoggingAttributes(final Map attributes) { FrameworkFlowContext getWorkingFlowContext(); + /** + * @return true when an upgrade is still open. That is when the Connector is not ghosted, an authoritative snapshot + * is held, and its bundle differs from {@link #getBundleCoordinate()}, or when the evolution hook has finished + * in an attempt that is still open. While true, Apply is rejected and START runs the upgrade. + */ + boolean isPendingFlowEvolution(); + + /** + * @return the status this node reports to the cluster for the pending flow evolution; {@link FlowEvolutionStatus#FAILED} once + * the evolution has failed, and {@link FlowEvolutionStatus#EVOLVE_DRAIN_PENDING} while this node still has an outgoing + * flow to drain, even before an evolution attempt begins + */ + default FlowEvolutionStatus getReportedFlowEvolutionStatus() { + return FlowEvolutionStatus.INACTIVE; + } + + /** + * @return authoritative persistence snapshot, or null when none is held + */ + ConnectorFlowSnapshot getAuthoritativeFlowSnapshot(); + void discardWorkingConfiguration(); // ------------------- @@ -324,6 +347,59 @@ default void setCustomLoggingAttributes(final Map attributes) { void prepareForUpdate() throws FlowUpdateException; + /** + * Moves a pending upgrade from STOPPED or UPDATE_FAILED to DRAINING and creates the evolution context. When an earlier + * attempt failed after every node had drained, this attempt resumes after the hook without running it again. + * + * @throws IllegalStateException if no evolution is pending or the Connector is not STOPPED or UPDATE_FAILED + */ + void prepareFlowEvolution(); + + /** + * Runs preflight, the Connector evolution hook, and the local evolve-drain phase on the provided executor. The executor + * must tolerate a task blocked for the duration of the hook. A resumed evolution runs preflight without invoking the + * hook. abortUpdate cancels the returned Future and the hook. + * + * @param executor executor used to run the local evolve-drain phase + * @return the future for the local evolve-drain phase of the prepared evolution + * @throws FlowUpdateException if the prepared evolution is no longer active + */ + Future evolveFlow(ExecutorService executor) throws FlowUpdateException; + + /** + * Moves an evolution whose evolve-drain phase is complete from DRAINING to PREPARING_FOR_UPDATE so the upgraded flow + * can be applied like a configuration update. The caller then calls {@link #prepareForUpdate()} and {@link #applyUpdate()}. + * + * @throws FlowUpdateException if the evolution is no longer active, the evolve-drain phase is not complete, or the upgraded flow + * removes a connection that still holds FlowFiles + */ + void beginEvolvedFlowUpdate() throws FlowUpdateException; + + /** + * @return true when the persisted flow belongs to a different bundle and configuration must not be inherited + */ + boolean restorePendingFlowEvolution(VersionedConnector persisted, List activeConfiguration, + List workingConfiguration) throws FlowUpdateException; + + /** + * Installs the persisted managed flow, with components stopped, for a Connector whose extension is missing, so that + * queues exist before the FlowFile Repository recovers. Must only be called when {@link #isExtensionMissing()} is true. + */ + void restorePersistedManagedFlow(VersionedConnector persisted); + + /** + * Records the live managed flow as this Connector's authoritative snapshot when none is held. Does nothing when a snapshot + * is already held or the Connector's extension is missing. + */ + void ensureAuthoritativeFlowSnapshot(); + + /** + * Installs the persisted managed flow while restoring Troubleshooting. + * + * @throws FlowUpdateException if the persisted flow cannot be restored + */ + void restoreTroubleshootingManagedFlow(VersionedConnector persisted) throws FlowUpdateException; + /** * Aborts the update preparation process. This method should only be invoked via the ConnectorRepository. * @param cause the reason for aborting the update preparation diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java index 7e1bc3b99465..e801c5e6a112 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepository.java @@ -125,10 +125,15 @@ public interface ConnectorRepository { /** * Starts the given Connector, managing any appropriate lifecycle events. + * When a flow evolution is pending, the context persists the flow once, after the upgraded flow is applied. A failed evolution is not persisted. + * The context is required even when no evolution is pending. + * * @param connector the Connector to start + * @param persistenceContext persists the flow during evolution * @return a CompletableFuture that will be completed when the Connector has started + * @throws NullPointerException if the persistence context is null */ - Future startConnector(ConnectorNode connector); + Future startConnector(ConnectorNode connector, ConnectorUpdateContext persistenceContext); /** * Stops the given Connector, managing any appropriate lifecycle events. @@ -326,4 +331,10 @@ default void verifyMigration(final String connectorId) { */ default void notifyMigrationComplete(final String connectorId, final String sourceProcessGroupId) { } + + /** + * Shuts down repository-managed lifecycle resources. + */ + default void shutdown() { + } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java index 7e6e1db372b9..0309f748b0d2 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java @@ -59,4 +59,13 @@ default Duration getConnectorSyncTimeout() { return Duration.ofMinutes(5); } + /** + * Returns the time allowed for each node to drain a connector during the local evolve-drain phase of flow evolution. + * + * @return the flow evolution drain timeout, defaults to 30 minutes + */ + default Duration getConnectorFlowEvolutionTimeout() { + return Duration.ofMinutes(30); + } + } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRequestReplicator.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRequestReplicator.java index dd6d7f90c2e0..a371b70ebcfe 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRequestReplicator.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRequestReplicator.java @@ -23,8 +23,18 @@ public interface ConnectorRequestReplicator { + /** + * @throws ConnectorClusterUnavailableException if no cluster node is connected yet + * @throws IOException if the Connector state cannot be retrieved + */ ConnectorState getState(String connectorId) throws IOException; + /** + * @throws ConnectorClusterUnavailableException if no cluster node is connected yet + * @throws IOException if the flow evolution status cannot be retrieved + */ + FlowEvolutionStatus getFlowEvolutionStatus(String connectorId) throws IOException; + void setFlowManager(FlowManager flowManager); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java new file mode 100644 index 000000000000..5bd919041544 --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java @@ -0,0 +1,74 @@ +/* + * 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 java.util.Collection; + +/** + * Reports local progress through the evolve-drain phase of a pending Connector flow evolution. Applying the upgraded flow + * after the evolve-drain phase is tracked through {@link ConnectorState}, as for a configuration update. + */ +public enum FlowEvolutionStatus { + /** + * No evolution is pending, so the node no longer needs the outgoing flow. + */ + INACTIVE, + + /** + * The node still has the outgoing flow and has not finished draining it. + */ + EVOLVE_DRAIN_PENDING, + + /** + * The node has drained the outgoing flow and has not yet applied the upgraded flow. + */ + EVOLVE_DRAIN_COMPLETE, + + FAILED; + + /** + * Merges statuses from every cluster participant. {@link #INACTIVE} nodes have nothing to drain and are ignored. + * Of the rest, the lowest ordinal wins so the cluster passes the drain barrier only when every node that still has + * the outgoing flow has drained it. {@link #FAILED} wins over every other status. + * + * @param statuses the statuses to merge; a null or empty collection merges to {@link #INACTIVE} + * @return the merged status, or {@link #INACTIVE} when every participant is inactive + */ + public static FlowEvolutionStatus merge(final Collection statuses) { + if (statuses == null || statuses.isEmpty()) { + return INACTIVE; + } + + FlowEvolutionStatus mergedStatus = INACTIVE; + for (final FlowEvolutionStatus status : statuses) { + if (status == FAILED) { + return FAILED; + } + + if (status == null || status == INACTIVE) { + continue; + } + + if (mergedStatus == INACTIVE || status.ordinal() < mergedStatus.ordinal()) { + mergedStatus = status; + } + } + + return mergedStatus; + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkConnectorInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkConnectorInitializationContext.java index b6ac28b882bc..c07cef60ad73 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkConnectorInitializationContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkConnectorInitializationContext.java @@ -21,6 +21,7 @@ import org.apache.nifi.components.connector.components.FlowContext; import org.apache.nifi.components.connector.secrets.SecretsManager; import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedProcessGroup; public interface FrameworkConnectorInitializationContext extends ConnectorInitializationContext { @@ -43,4 +44,15 @@ public interface FrameworkConnectorInitializationContext extends ConnectorInitia * @throws FlowUpdateException if the flow update would not be allowed */ void verifyUpdateFlow(FlowContext flowContext, VersionedExternalFlow versionedExternalFlow, BundleCompatibility bundleCompatability) throws FlowUpdateException; + + /** + * Rewrites processor and controller service bundles in the supplied group, including nested groups, according to + * the given compatibility. An exact installed coordinate is kept. {@link BundleCompatibility#RESOLVE_BUNDLE} + * selects the only other installed bundle for that type, and leaves the coordinate unchanged when none or several + * are installed. + * + * @param group the persisted or proposed group whose component bundles may be rewritten + * @param bundleCompatibility the strategy to use when an exact bundle is not installed + */ + void resolveBundles(VersionedProcessGroup group, BundleCompatibility bundleCompatibility); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java index 7c2525e3fe26..e0b8be362d98 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java @@ -21,6 +21,7 @@ import org.apache.nifi.components.connector.components.FlowContext; import org.apache.nifi.flow.Bundle; import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.logging.ComponentLog; @@ -45,16 +46,20 @@ public interface FrameworkFlowContext extends FlowContext { void verifyUpdateFlow(VersionedExternalFlow versionedExternalFlow) throws FlowUpdateException; /** - * Restores the contents of the Managed Process Group from a snapshot persisted while the Connector was in - * Troubleshooting mode. Unlike {@link #updateFlow(VersionedExternalFlow, AssetManager)}, this method does - * not call {@code ProcessGroup#verifyCanUpdate} and is intended for use only when restoring a Connector - * that was persisted while in Troubleshooting mode. The persisted user modifications are re-applied on top of the - * Connector's current Managed Process Group contents. - * - * @param troubleshootingProcessGroup the VersionedProcessGroup representing the Managed Process Group contents - * persisted while the Connector was in Troubleshooting mode + * Restores a persisted authoritative flow into the managed process group, keeping component identifiers. + * Components resume according to the Process Group's auto-resume setting. + * @param persistedFlow the flow to restore + * @param parameterContext the parameter context that belonged to that flow, or null + */ + void restorePersistedFlow(VersionedProcessGroup persistedFlow, VersionedParameterContext parameterContext); + + /** + * Restores a persisted authoritative flow into the managed process group, keeping component identifiers. + * @param persistedFlow the flow to restore + * @param parameterContext the parameter context that belonged to that flow, or null + * @param resumeComponentState whether components should resume the running or enabled state captured in the snapshot */ - void restoreTroubleshootingFlow(VersionedProcessGroup troubleshootingProcessGroup); + void restorePersistedFlow(VersionedProcessGroup persistedFlow, VersionedParameterContext parameterContext, boolean resumeComponentState); default void reload(final Bundle bundle, final ComponentLog connectorLog) { reload(bundle, connectorLog, getConfigurationContext()); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java index d271e773a31b..9c3c5f3e0c62 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java @@ -976,6 +976,16 @@ default CompletableFuture stopComponents() { */ void restoreFlowPreservingIdentifiers(VersionedExternalFlow proposedSnapshot); + /** + * Restores a previously persisted flow while controlling whether components resume their captured scheduled state. + * When {@code resumeComponentState} is false, the flow structure is restored so queued FlowFiles can reattach, but + * no component is started or enabled. + * + * @param proposedSnapshot the proposed flow whose Instance Identifiers should be used as runtime identifiers + * @param resumeComponentState whether components should resume the running or enabled state captured in the snapshot + */ + void restoreFlowPreservingIdentifiers(VersionedExternalFlow proposedSnapshot, boolean resumeComponentState); + /** * Updates the Process Group to match the proposed flow * diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/registry/flow/mapping/FlowMappingOptions.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/registry/flow/mapping/FlowMappingOptions.java index 020bb884bc92..3fb299e63db2 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/registry/flow/mapping/FlowMappingOptions.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/registry/flow/mapping/FlowMappingOptions.java @@ -277,6 +277,24 @@ public FlowMappingOptions build() { } } + /** + * Options used when mapping a live Process Group to the snapshot that is persisted in the flow definition. + */ + public static FlowMappingOptions forPersistedFlow(final PropertyEncryptionProvider propertyEncryptionProvider, + final VersionedComponentStateLookup stateLookup) { + return new Builder() + .mapSensitiveConfiguration(true) + .mapPropertyDescriptors(false) + .stateLookup(stateLookup) + .propertyEncryptionProvider(propertyEncryptionProvider) + .componentIdLookup(ComponentIdLookup.VERSIONED_OR_GENERATE) + .mapInstanceIdentifiers(true) + .mapControllerServiceReferencesToVersionedId(false) + .mapFlowRegistryClientId(true) + .mapAssetReferences(true) + .build(); + } + /** * The Default Options are acceptable for sharing a dataflow externally (outside of a given nifi instance or cluster), such as sharing * a dataflow to a NiFi Registry. diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshotMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshotMapper.java new file mode 100644 index 000000000000..79ddd6fd97fd --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowSnapshotMapper.java @@ -0,0 +1,87 @@ +/* + * 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.components.connector.secrets.SecretsManager; +import org.apache.nifi.controller.service.ControllerServiceProvider; +import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.nar.ExtensionManager; +import org.apache.nifi.parameter.ParameterContext; +import org.apache.nifi.registry.flow.mapping.VersionedComponentFlowMapper; +import org.apache.nifi.registry.flow.mapping.VersionedComponentStateLookup; +import org.apache.nifi.security.encryption.PropertyEncryptionProvider; + +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Maps the current Connector-managed flow to its authoritative persisted representation. + */ +public final class ConnectorFlowSnapshotMapper { + private final ExtensionManager extensionManager; + private final ControllerServiceProvider controllerServiceProvider; + private final PropertyEncryptionProvider propertyEncryptionProvider; + + public ConnectorFlowSnapshotMapper(final ExtensionManager extensionManager, final ControllerServiceProvider controllerServiceProvider, + final PropertyEncryptionProvider propertyEncryptionProvider) { + this.extensionManager = Objects.requireNonNull(extensionManager, "Extension Manager required"); + this.controllerServiceProvider = Objects.requireNonNull(controllerServiceProvider, "Controller Service Provider required"); + this.propertyEncryptionProvider = Objects.requireNonNull(propertyEncryptionProvider, "Property Encryption Provider required"); + } + + ConnectorFlowSnapshot capture(final FrameworkFlowContext flowContext, final Bundle bundle, final SecretsManager secretsManager) { + final VersionedComponentFlowMapper mapper = VersionedComponentFlowMapper.forPersistedFlow(extensionManager, propertyEncryptionProvider, VersionedComponentStateLookup.IDENTITY_LOOKUP); + + final VersionedProcessGroup managedProcessGroup = mapper.mapNonVersionedProcessGroup(flowContext.getManagedProcessGroup(), controllerServiceProvider); + + final ParameterContext parameterContext = flowContext.getManagedProcessGroup().getParameterContext(); + final VersionedParameterContext mappedParameterContext = parameterContext == null ? null : mapper.mapParameterContext(parameterContext); + + final ConnectorConfiguration activeConfiguration = flowContext.getConfigurationContext().toConnectorConfiguration(); + + final Set configurationSecretReferences = new HashSet<>(); + for (final NamedStepConfiguration stepConfiguration : activeConfiguration.getNamedStepConfigurations()) { + for (final ConnectorValueReference valueReference : stepConfiguration.configuration().getPropertyValues().values()) { + if (valueReference instanceof final SecretReference secretReference) { + configurationSecretReferences.add(secretReference); + } + } + } + + final Map secrets = configurationSecretReferences.isEmpty() + ? Map.of() + : secretsManager.getSecrets(configurationSecretReferences); + + final Map parameterSecretReferences = ParameterSecretReferences.matchSensitiveParametersToSecretReferences(parameterContext, secrets); + + return new ConnectorFlowSnapshot(managedProcessGroup, mappedParameterContext, parameterSecretReferences, bundle, activeConfiguration); + } + + /** + * Resolves the values of a persisted managed Parameter Context captured by this mapper. See + * {@link ParameterSecretReferences#resolve(VersionedParameterContext, Map, SecretsManager, PropertyEncryptionProvider)}. + */ + ParameterSecretReferences.Resolution resolve(final VersionedParameterContext parameterContext, final Map parameterSecretReferences, + final SecretsManager secretsManager) { + return ParameterSecretReferences.resolve(parameterContext, parameterSecretReferences, secretsManager, propertyEncryptionProvider); + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java index 87e6b9570b94..400d6417316f 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java @@ -22,6 +22,7 @@ import org.apache.nifi.components.connector.components.ProcessGroupFacade; import org.apache.nifi.flow.Bundle; import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; @@ -104,9 +105,13 @@ public void updateFlow(final VersionedExternalFlow versionedExternalFlow, final } @Override - public void restoreTroubleshootingFlow(final VersionedProcessGroup troubleshootingProcessGroup) { - throw new IllegalStateException("restoreTroubleshootingFlow() cannot be called from MigratableConnector.migrateConfiguration() or migrateState();" - + " the migration context exposes a read-only view of the managed flow so that the framework remains the sole owner of" - + " installing the managed Process Group."); + public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext) { + throw new IllegalStateException("restorePersistedFlow() cannot be called from MigratableConnector.migrateConfiguration() or migrateState();" + + " the migration context exposes a read-only view of the managed flow so that the framework remains the sole owner of installing the managed Process Group."); + } + + @Override + public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext, final boolean resumeComponentState) { + restorePersistedFlow(persistedFlow, parameterContext); } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java new file mode 100644 index 000000000000..97b06175a165 --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java @@ -0,0 +1,225 @@ +/* + * 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.components.connector.components.ParameterValue; +import org.apache.nifi.components.connector.secrets.SecretsManager; +import org.apache.nifi.flow.VersionedConnector; +import org.apache.nifi.flow.VersionedConnectorValueReference; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.parameter.Parameter; +import org.apache.nifi.parameter.ParameterContext; +import org.apache.nifi.security.encryption.PropertyEncryptionEncoder; +import org.apache.nifi.security.encryption.PropertyEncryptionException; +import org.apache.nifi.security.encryption.PropertyEncryptionProvider; +import org.apache.nifi.security.encryption.SensitivePropertyCodec; +import org.apache.nifi.security.encryption.SensitivePropertyContext; +import org.apache.nifi.security.encryption.SensitivePropertyContextFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Matches and resolves relationships between Connector-managed Parameters and Secret References. Sensitive parameter + * values are persisted encrypted with the sensitive properties key, as in any other Parameter Context. A sensitive + * parameter whose value is exactly one configured secret is also bound to that Secret Reference, and on restore takes the + * current value of the secret from the {@link SecretsManager} instead of its persisted value. + */ +final class ParameterSecretReferences { + + private ParameterSecretReferences() { + } + + /** + * Converts a persisted Connector's managed parameter secret references into runtime Secret References. + * Entries that are null or not a secret reference are omitted. + */ + static Map convertManagedParameterSecretReferences(final VersionedConnector versionedConnector) { + final Map versionedReferences = versionedConnector.getManagedParameterSecretReferences(); + if (versionedReferences == null || versionedReferences.isEmpty()) { + return Map.of(); + } + + final Map references = new HashMap<>(); + for (final Map.Entry entry : versionedReferences.entrySet()) { + final VersionedConnectorValueReference versionedReference = entry.getValue(); + if (versionedReference == null || !ConnectorValueType.SECRET_REFERENCE.name().equals(versionedReference.getValueType())) { + continue; + } + + references.put(entry.getKey(), new SecretReference(versionedReference.getProviderId(), versionedReference.getProviderName(), + versionedReference.getSecretName(), versionedReference.getFullyQualifiedSecretName())); + } + return references; + } + + /** + * Returns the Secret Reference for each sensitive parameter whose value equals exactly one of the supplied secrets. + * A parameter whose value matches more than one reference is omitted. + */ + static Map matchSensitiveParametersToSecretReferences(final ParameterContext parameterContext, final Map secrets) { + final Map references = new HashMap<>(); + if (parameterContext == null || secrets == null || secrets.isEmpty()) { + return references; + } + + for (final Parameter parameter : parameterContext.getParameters().values()) { + final String value = parameter.getValue(); + final List assets = parameter.getReferencedAssets(); + if (!parameter.getDescriptor().isSensitive() || value == null || value.isEmpty() || assets != null && !assets.isEmpty()) { + continue; + } + + SecretReference matchingReference = null; + boolean ambiguous = false; + for (final Map.Entry entry : secrets.entrySet()) { + final Secret secret = entry.getValue(); + if (secret == null || !value.equals(secret.getValue())) { + continue; + } + + if (matchingReference == null) { + matchingReference = entry.getKey(); + } else if (!matchingReference.equals(entry.getKey())) { + ambiguous = true; + break; + } + } + + if (matchingReference != null && !ambiguous) { + references.put(parameter.getDescriptor().getName(), matchingReference); + } + } + + return references; + } + + /** + * Resolves the values of a persisted managed Parameter Context without modifying it. A sensitive parameter bound to a + * Secret Reference takes the current value of that secret, or is left null and reported when the secret cannot be + * resolved. Any other sensitive parameter takes its persisted value decrypted with the supplied provider, or is left null + * and reported when the value cannot be decrypted. + */ + static Resolution resolve(final VersionedParameterContext parameterContext, final Map parameterSecretReferences, + final SecretsManager secretsManager, final PropertyEncryptionProvider propertyEncryptionProvider) { + if (parameterContext == null) { + return new Resolution(null, List.of(), Map.of(), Set.of()); + } + + final VersionedParameterContext resolved = copyContext(parameterContext); + final Map references = parameterSecretReferences == null ? Map.of() : parameterSecretReferences; + final Set distinctReferences = new HashSet<>(references.values()); + final Map secrets = distinctReferences.isEmpty() + ? Map.of() + : secretsManager.getSecrets(distinctReferences, false); + final Map unresolved = new HashMap<>(); + final Set undecryptable = new HashSet<>(); + final List resolvedValues = new ArrayList<>(); + + if (resolved.getParameters() != null) { + for (final VersionedParameter parameter : resolved.getParameters()) { + if (!parameter.isSensitive()) { + continue; + } + + final SecretReference reference = references.get(parameter.getName()); + if (reference == null) { + final String value = parameter.getValue(); + if (PropertyEncryptionEncoder.isEncrypted(value)) { + final SensitivePropertyContext context = SensitivePropertyContextFactory.forParameter(resolved.getName(), parameter.getName()); + try { + parameter.setValue(SensitivePropertyCodec.decrypt(propertyEncryptionProvider, PropertyEncryptionEncoder.getDecoded(value), context)); + } catch (final PropertyEncryptionException e) { + parameter.setValue(null); + undecryptable.add(parameter.getName()); + } + } + + continue; + } + + final Secret secret = secrets.get(reference); + if (secret == null) { + parameter.setValue(null); + unresolved.put(parameter.getName(), reference); + continue; + } + + parameter.setValue(secret.getValue()); + resolvedValues.add(new ParameterValue.Builder() + .name(parameter.getName()) + .value(secret.getValue()) + .sensitive(true) + .build()); + } + } + + return new Resolution(resolved, resolvedValues, unresolved, undecryptable); + } + + private static VersionedParameterContext copyContext(final VersionedParameterContext source) { + final VersionedParameterContext copy = new VersionedParameterContext(); + copy.setIdentifier(source.getIdentifier()); + copy.setInstanceIdentifier(source.getInstanceIdentifier()); + copy.setGroupIdentifier(source.getGroupIdentifier()); + copy.setName(source.getName()); + copy.setComments(source.getComments()); + copy.setPosition(source.getPosition()); + copy.setDescription(source.getDescription()); + copy.setInheritedParameterContexts(source.getInheritedParameterContexts() == null ? null : new ArrayList<>(source.getInheritedParameterContexts())); + copy.setParameterProvider(source.getParameterProvider()); + copy.setParameterGroupName(source.getParameterGroupName()); + copy.setSynchronized(source.isSynchronized()); + + if (source.getParameters() != null) { + final Set parameters = new HashSet<>(); + for (final VersionedParameter sourceParameter : source.getParameters()) { + final VersionedParameter parameter = new VersionedParameter(); + parameter.setName(sourceParameter.getName()); + parameter.setDescription(sourceParameter.getDescription()); + parameter.setSensitive(sourceParameter.isSensitive()); + parameter.setProvided(sourceParameter.isProvided()); + parameter.setValue(sourceParameter.getValue()); + parameter.setReferencedAssets(sourceParameter.getReferencedAssets() == null ? null : new ArrayList<>(sourceParameter.getReferencedAssets())); + parameters.add(parameter); + } + copy.setParameters(parameters); + } + + return copy; + } + + /** + * @param parameterContext the resolved Parameter Context holding plaintext sensitive values + * @param parameterValues the values taken from Secret References + * @param unresolvedReferences Secret References that could not be resolved, keyed by parameter name + * @param undecryptableParameters names of parameters whose persisted value could not be decrypted + */ + record Resolution( + VersionedParameterContext parameterContext, + List parameterValues, + Map unresolvedReferences, + Set undecryptableParameters) { + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/PreUpgradeFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/PreUpgradeFlowContext.java new file mode 100644 index 000000000000..82cd6d24c6c2 --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/PreUpgradeFlowContext.java @@ -0,0 +1,70 @@ +/* + * 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.components.connector.components.FlowContext; +import org.apache.nifi.components.connector.components.FlowContextType; +import org.apache.nifi.components.connector.components.ParameterContextFacade; +import org.apache.nifi.components.connector.components.ProcessGroupFacade; +import org.apache.nifi.flow.Bundle; + +/** + * The view of the Active flow handed to prepareForFlowEvolution. It delegates to the Active context, except that + * getBundle() returns the version that built the flow rather than the loaded code. It deliberately does not + * implement FrameworkFlowContext, so ConnectorInitializationContext.updateFlow rejects it and the hook cannot + * restructure the pre-upgrade flow. + */ +final class PreUpgradeFlowContext implements FlowContext { + private final FlowContext activeFlowContext; + private final Bundle preUpgradeBundle; + + /** + * @param activeFlowContext the live Active context; supplies getRootGroup, getParameterContext, + * getConfigurationContext, and getType + * @param preUpgradeBundle the bundle from the authoritative snapshot, returned by getBundle + */ + PreUpgradeFlowContext(final FlowContext activeFlowContext, final Bundle preUpgradeBundle) { + this.activeFlowContext = activeFlowContext; + this.preUpgradeBundle = preUpgradeBundle; + } + + @Override + public ProcessGroupFacade getRootGroup() { + return activeFlowContext.getRootGroup(); + } + + @Override + public ParameterContextFacade getParameterContext() { + return activeFlowContext.getParameterContext(); + } + + @Override + public ConnectorConfigurationContext getConfigurationContext() { + return activeFlowContext.getConfigurationContext(); + } + + @Override + public FlowContextType getType() { + return activeFlowContext.getType(); + } + + @Override + public Bundle getBundle() { + return preUpgradeBundle; + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandaloneConnectorRequestReplicator.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandaloneConnectorRequestReplicator.java index 5880530745c6..9421fdd4c5d5 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandaloneConnectorRequestReplicator.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandaloneConnectorRequestReplicator.java @@ -25,16 +25,25 @@ public class StandaloneConnectorRequestReplicator implements ConnectorRequestRep @Override public ConnectorState getState(final String connectorId) { - final ConnectorNode connectorNode = flowManager.getConnector(connectorId); - if (connectorNode == null) { - throw new IllegalArgumentException("No connector found with id: " + connectorId); - } + return getConnector(connectorId).getCurrentState(); + } - return connectorNode.getCurrentState(); + @Override + public FlowEvolutionStatus getFlowEvolutionStatus(final String connectorId) { + return getConnector(connectorId).getReportedFlowEvolutionStatus(); } @Override public void setFlowManager(final FlowManager flowManager) { this.flowManager = flowManager; } + + private ConnectorNode getConnector(final String connectorId) { + final ConnectorNode connectorNode = flowManager.getConnector(connectorId); + if (connectorNode == null) { + throw new IllegalArgumentException("No connector found with id: " + connectorId); + } + + return connectorNode; + } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorInitializationContext.java index c8b4a267fbf6..26dfa096ad78 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorInitializationContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorInitializationContext.java @@ -102,7 +102,8 @@ private FrameworkFlowContext requireFrameworkFlowContext(final FlowContext flowC return frameworkFlowContext; } - protected void resolveBundles(final VersionedProcessGroup group, final BundleCompatibility bundleCompatability) { + @Override + public void resolveBundles(final VersionedProcessGroup group, final BundleCompatibility bundleCompatability) { if (bundleCompatability == BundleCompatibility.REQUIRE_EXACT_BUNDLE) { return; } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java index 66d01931b433..1b739e1864ba 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java @@ -51,9 +51,11 @@ import org.apache.nifi.flow.Bundle; import org.apache.nifi.flow.ScheduledState; import org.apache.nifi.flow.VersionedConfigurationStep; +import org.apache.nifi.flow.VersionedConnector; import org.apache.nifi.flow.VersionedConnectorValueReference; import org.apache.nifi.flow.VersionedControllerService; import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.flow.VersionedProcessor; import org.apache.nifi.groups.ProcessGroup; @@ -86,7 +88,10 @@ import java.util.OptionalLong; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -97,6 +102,8 @@ public class StandardConnectorNode implements ConnectorNode, GroupedComponent { private static final Logger logger = LoggerFactory.getLogger(StandardConnectorNode.class); + static final String FLOW_EVOLUTION_VALIDATION_SUBJECT = "Flow Evolution"; + private static final Set STOPPED_STATES = EnumSet.of(org.apache.nifi.controller.ScheduledState.STOPPED, org.apache.nifi.controller.ScheduledState.DISABLED); @@ -112,14 +119,22 @@ public class StandardConnectorNode implements ConnectorNode, GroupedComponent { private final ConnectorStateTransition stateTransition; private final AtomicReference versionedComponentId = new AtomicReference<>(); private final FlowContextFactory flowContextFactory; - private final FrameworkFlowContext activeFlowContext; + private final ConnectorFlowSnapshotMapper snapshotMapper; + private volatile FrameworkFlowContext activeFlowContext; + private final AtomicReference flowEvolutionProgress = new AtomicReference<>(FlowEvolutionProgress.NONE); + private volatile ConnectorFlowSnapshot authoritativeFlowSnapshot; + private final Object flowEvolutionLock = new Object(); + // Written only while holding flowEvolutionLock + private volatile FlowEvolutionAttempt latestFlowEvolutionAttempt; private final AtomicReference validationState = new AtomicReference<>(new ValidationState(ValidationStatus.VALIDATING, Collections.emptyList())); private final ConnectorValidationTrigger validationTrigger; private volatile boolean extensionMissing; + private volatile boolean managedFlowRestoreFailed; private volatile boolean triggerValidation = true; private final AtomicReference> drainFutureRef = new AtomicReference<>(); private volatile ValidationResult unresolvedBundleValidationResult = null; + private volatile Map unresolvedParameterSecretReferences = Map.of(); private final Object workingFlowContextLock = new Object(); private volatile WorkingFlowContextState workingFlowContextState = new WorkingFlowContextState(null); @@ -137,9 +152,8 @@ public class StandardConnectorNode implements ConnectorNode, GroupedComponent { public StandardConnectorNode(final String identifier, final FlowManager flowManager, final ExtensionManager extensionManager, final StateManagerProvider stateManagerProvider, final Authorizable parentAuthorizable, final ConnectorDetails connectorDetails, final String componentType, final String componentCanonicalClass, final MutableConnectorConfigurationContext configurationContext, - final ConnectorStateTransition stateTransition, final FlowContextFactory flowContextFactory, + final ConnectorStateTransition stateTransition, final FlowContextFactory flowContextFactory, final ConnectorFlowSnapshotMapper snapshotMapper, final ConnectorValidationTrigger validationTrigger, final boolean extensionMissing) { - this.identifier = identifier; this.flowManager = flowManager; this.extensionManager = extensionManager; @@ -151,6 +165,7 @@ public StandardConnectorNode(final String identifier, final FlowManager flowMana this.bundleCoordinate = connectorDetails.getBundleCoordinate(); this.stateTransition = stateTransition; this.flowContextFactory = flowContextFactory; + this.snapshotMapper = snapshotMapper; this.validationTrigger = validationTrigger; this.extensionMissing = extensionMissing; @@ -296,8 +311,11 @@ public void prepareForUpdate() throws FlowUpdateException { throw new IllegalStateException("Cannot prepare update for " + this + " because its state is currently " + getCurrentState() + "; it must be PREPARING_FOR_UPDATE."); } - if (getDesiredState() != ConnectorState.UPDATING) { - throw new IllegalStateException("Cannot prepare update for " + this + " because its desired state is currently " + getDesiredState() + // An evolution is applied with the connector desired RUNNING, because only a start request begins an evolution. + final ConnectorState desiredState = getDesiredState(); + final boolean evolving = desiredState == ConnectorState.RUNNING && isApplyingEvolvedFlow(); + if (desiredState != ConnectorState.UPDATING && !evolving) { + throw new IllegalStateException("Cannot prepare update for " + this + " because its desired state is currently " + desiredState + "; it must be UPDATING."); } @@ -427,6 +445,29 @@ public void inheritConfiguration(final List activeCo logger.debug("Successfully inherited configuration for {}", this); } + /** + * Loads migrated active and working configuration without calling {@code applyUpdate}, so a restored pre-upgrade + * flow is not replaced by the upgraded connector's flow. + */ + private void loadConfigurationsWithoutRebuildingFlow(final List activeConfig, final List workingConfig) + throws FlowUpdateException { + final Map migratedActiveProperties = migrateProperties(activeConfig); + final Map migratedWorkingProperties = migrateProperties(workingConfig); + for (final Map.Entry step : migratedActiveProperties.entrySet()) { + activeFlowContext.getConfigurationContext().replaceProperties(step.getKey(), step.getValue()); + } + final MutableConnectorConfigurationContext workingConfigContext = createConfigurationContext(migratedWorkingProperties); + final WorkingFlowContextState independentWorkingContextState = installReplacementWorkingFlowContext(workingConfigContext, loadedBundle(), true); + try { + for (final String stepName : migratedWorkingProperties.keySet()) { + notifyStepConfigured(stepName, independentWorkingContextState.getContext()); + } + } finally { + releaseWorkingFlowContext(independentWorkingContextState); + } + resetValidationState(); + } + /** * Removes the current working process group before creating its replacement. Working-context copies reuse the same * connection identifiers as the active flow, and the cluster load-balance client registry allows only one @@ -702,6 +743,9 @@ private void applyUpdate(final FrameworkFlowContext contextToInherit) throws Flo + "; it must be UPDATING."); } + // Read before the snapshot is captured, because capturing it ends the evolution. + final boolean evolving = isApplyingEvolvedFlow(); + try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(extensionManager, getConnector().getClass(), getIdentifier())) { getConnector().applyUpdate(contextToInherit, activeFlowContext); @@ -715,6 +759,7 @@ private void applyUpdate(final FrameworkFlowContext contextToInherit) throws Flo activeFlowContext.getConfigurationContext().replaceConfiguration(inheritedConfiguration); getComponentLog().info("Working Context has been applied to Active Context"); + captureAuthoritativeSnapshot(); // The update has been completed. Tear down and recreate the working flow context to ensure it is in a clean state. resetValidationState(); @@ -728,7 +773,11 @@ private void applyUpdate(final FrameworkFlowContext contextToInherit) throws Flo } stateTransition.setCurrentState(ConnectorState.UPDATED); - stateTransition.setDesiredState(ConnectorState.UPDATED); + // An evolved connector stays desired RUNNING so that the flow saved after the apply records it as running. + if (!evolving) { + stateTransition.setDesiredState(ConnectorState.UPDATED); + } + logger.info("Successfully applied update for {}", this); } @@ -766,6 +815,11 @@ private void releaseWorkingFlowContext(final WorkingFlowContextState workingCont @Override public void abortUpdate(final Throwable cause) { + if (isFlowEvolutionInProgress() || hasFlowEvolutionFailed()) { + failFlowEvolution(cause == null ? null : cause.getMessage(), cause); + return; + } + stateTransition.setCurrentState(ConnectorState.UPDATE_FAILED); stateTransition.setDesiredState(ConnectorState.UPDATE_FAILED); @@ -923,7 +977,6 @@ public ConnectorState getDesiredState() { return stateTransition.getDesiredState(); } - @Override public Optional getIdleDuration() { final ProcessGroup processGroup = getActiveFlowContext().getManagedProcessGroup(); @@ -979,7 +1032,7 @@ private void start(final FlowEngine scheduler, final CompletableFuture sta stateTransition.addPendingStartFuture(startCompleteFuture); return; } - case STOPPED, PREPARING_FOR_UPDATE, UPDATED -> { + case STOPPED, PREPARING_FOR_UPDATE, UPDATED, UPDATE_FAILED -> { startScheduled = stateTransition.trySetCurrentState(currentState, ConnectorState.STARTING); if (startScheduled) { logger.info("Starting {}", this); @@ -1008,9 +1061,12 @@ public Future stop(final FlowEngine scheduler) { logger.info("Stopping {}", this); final CompletableFuture stopCompleteFuture = new CompletableFuture<>(); - stateTransition.setDesiredState(ConnectorState.STOPPED); + if (prepareFlowEvolutionStop(stopCompleteFuture)) { + return stopCompleteFuture; + } + boolean stateUpdated = false; while (!stateUpdated) { final ConnectorState currentState = getCurrentState(); @@ -1041,6 +1097,19 @@ public Future stop(final FlowEngine scheduler) { return stopCompleteFuture; } + private boolean prepareFlowEvolutionStop(final CompletableFuture stopCompleteFuture) { + synchronized (flowEvolutionLock) { + if (!isFlowEvolutionInProgress()) { + return false; + } + + stateTransition.addPendingStopFuture(stopCompleteFuture); + } + + abortFlowEvolution(); + return true; + } + private void stopManagedProcessGroup(final FlowEngine scheduler) { if (getCurrentState() != ConnectorState.STOPPING) { return; @@ -1107,6 +1176,19 @@ public Future drainFlowFiles() { @Override public void cancelDrainFlowFiles() { + final boolean flowEvolutionActive; + synchronized (flowEvolutionLock) { + flowEvolutionActive = isFlowEvolutionInProgress(); + if (flowEvolutionActive) { + stateTransition.setDesiredState(ConnectorState.STOPPED); + } + } + + if (flowEvolutionActive) { + abortFlowEvolution(); + return; + } + final Future future = this.drainFutureRef.getAndSet(null); if (future == null) { logger.debug("No active drain to cancel for {}; drain may have already completed", this); @@ -1117,6 +1199,12 @@ public void cancelDrainFlowFiles() { logger.info("Cancelled draining of FlowFiles for {}", this); } + private void abortFlowEvolution() { + // Recorded before cancelling, because the coordinator wakes on the cancellation and must see the failure to stop the Connector + publishFlowEvolutionFailure("Flow evolution was cancelled", null); + closeCurrentFlowEvolution(); + } + @Override public void verifyCancelDrainFlowFiles() throws IllegalStateException { final ConnectorState state = getCurrentState(); @@ -1219,9 +1307,19 @@ private void startComponent(final FlowEngine scheduler, final CompletableFuture< componentLifecycleLock.lock(); try { logger.debug("Starting component for {}", this); + // A retry scheduled by an earlier failed start can outlive that start: a stop, or a stop followed by a newer start, moves + // the current state away from STARTING, and that newer start owns the Connector from then on. The superseded start + // succeeds if the Connector is already running, and fails otherwise. final ConnectorState desiredState = getDesiredState(); - if (desiredState != ConnectorState.RUNNING) { - logger.info("Will not start {} because the desired state is no longer RUNNING but is now {}", this, desiredState); + final ConnectorState currentState = getCurrentState(); + if (desiredState == ConnectorState.RUNNING && currentState == ConnectorState.RUNNING) { + logger.debug("{} is already running, so this start has nothing left to do", this); + startCompleteFuture.complete(null); + return; + } + if (desiredState != ConnectorState.RUNNING || currentState != ConnectorState.STARTING) { + logger.info("Will not start {} because its desired state is now {} and its current state is now {}", this, desiredState, currentState); + startCompleteFuture.completeExceptionally(new IllegalStateException("Start of " + this + " was superseded by a later stop or start request")); completeDeferredStop(scheduler); return; } @@ -1234,6 +1332,9 @@ private void startComponent(final FlowEngine scheduler, final CompletableFuture< } catch (final Exception e) { if (getCurrentState() == ConnectorState.STOPPING) { logger.error("Failed to start {} and a stop has since been requested, so the Connector will be stopped instead of started", this, e); + final IllegalStateException superseded = new IllegalStateException("Start of " + this + " was superseded by a stop request"); + superseded.addSuppressed(e); + startCompleteFuture.completeExceptionally(superseded); completeDeferredStop(scheduler); } else { logger.error("Failed to start {} retrying in 10 seconds", this, e); @@ -1302,12 +1403,28 @@ public void verifyCanStart() { if (getCurrentState() == ConnectorState.TROUBLESHOOTING) { throw new IllegalStateException("Cannot start " + this + " because it is in Troubleshooting mode."); } + if (isExtensionMissing()) { + throw new IllegalStateException("Cannot start " + this + " because its extension is missing."); + } + if (managedFlowRestoreFailed) { + throw new IllegalStateException("Cannot start " + this + " because its managed flow was not installed while it was ghosted; " + + "restart NiFi so queued FlowFiles rejoin the restored connections before starting"); + } final ValidationState state = performValidation(); - if (state.getStatus() != ValidationStatus.VALID) { + final boolean blockingFailure = state.getValidationErrors().stream().anyMatch(StandardConnectorNode::isBlockingValidationFailure); + if (blockingFailure) { throw new IllegalStateException("Cannot start " + this + " because it is not valid: " + state.getValidationErrors()); } } + void markManagedFlowRestoreFailed() { + managedFlowRestoreFailed = true; + } + + boolean isManagedFlowRestoreFailed() { + return managedFlowRestoreFailed; + } + @Override public void verifyCanEnterTroubleshooting() { if (isExtensionMissing()) { @@ -1340,8 +1457,19 @@ private Optional getReasonCannotEndTroubleshooting() { return quickReason; } - // After confirming all components are stopped or disabled, check if the managed flow can be safely reverted to the - // Connector's authoritative flow. This mirrors exactly what endTroubleshooting() will do so that any problem + // A pending upgrade does not run prepareForFlowEvolution. The user owns the flow while Troubleshooting, so every + // queue must already be empty before the upgraded flow is installed. This check comes before the flow comparison + // so a queue that the upgraded flow would keep is still rejected. + if (isPendingFlowEvolution()) { + final int queuedFlowFiles = getActiveFlowContext().getManagedProcessGroup().getQueueSize().getObjectCount(); + if (queuedFlowFiles > 0) { + return Optional.of("The managed flow holds " + queuedFlowFiles + + " FlowFiles; empty every queue before leaving Troubleshooting while an upgrade is pending"); + } + } + + // After confirming all components are stopped or disabled, check if the managed flow can be safely replaced by + // the Connector's authoritative flow. This mirrors exactly what endTroubleshooting() will do so that any problem // (e.g. a Connection whose contents cannot be preserved or a component that cannot be replaced) is reported // synchronously rather than surfacing halfway through the state change. This check is intentionally not run by // createEndTroubleshootingAction (which is called on every GET of the Connector entity) because it requires @@ -1443,6 +1571,7 @@ public void enterTroubleshooting() { // Troubleshooting remain running; the user may stop individual components as needed in order to edit them, and // they must all be stopped/disabled before the Connector can leave Troubleshooting mode (enforced in // verifyCanEndTroubleshooting). + ensureAuthoritativeFlowSnapshot(); stateTransition.setDesiredState(ConnectorState.TROUBLESHOOTING); stateTransition.setCurrentState(ConnectorState.TROUBLESHOOTING); } @@ -1465,7 +1594,10 @@ public void endTroubleshooting() throws FlowUpdateException { // authoritative flow are resolved against the currently-available bundles. This mirrors how the initial flow // is applied in initializeConnector and avoids failing validation when the Connector hard-codes a bundle // version that differs from the currently-installed NAR (which is common in test Connectors). + // A pending upgrade installs this flow directly. prepareForFlowEvolution is not called: the queues were + // required to be empty, and the loaded bundle is captured so the evolution is no longer pending. initializationContext.updateFlow(activeFlowContext, flowToApply, BundleCompatibility.RESOLVE_BUNDLE); + installAuthoritativeSnapshot(createAuthoritativeSnapshot()); stateTransition.setDesiredState(ConnectorState.STOPPED); stateTransition.setCurrentState(ConnectorState.STOPPED); @@ -1510,10 +1642,19 @@ public void replaceConnector(final Connector replacement, final BundleCoordinate replacement.initialize(replacementInitializationContext); } + // The snapshot keeps the outgoing flow, Parameter Context and managed-flow bundle across version changes, so a + // change to a different version leaves the flow evolution pending and a change back to the snapshot bundle clears it. + final ConnectorFlowSnapshot outgoingSnapshot = authoritativeFlowSnapshot; + final boolean replacementMissing = replacement instanceof GhostConnector; + final boolean restoreSnapshotFlow = extensionMissing && !replacementMissing && outgoingSnapshot != null && outgoingSnapshot.flow() != null; + final WorkingFlowContextState workingContextState = acquireWorkingFlowContext(); final FrameworkFlowContext workingContext = workingContextState.getContext(); final MutableConnectorConfigurationContext originalWorkingConfigurationContext = workingContext == null ? null : workingContext.getConfigurationContext(); - final Map originalActiveConfiguration = toConfigurationMap(activeFlowContext.getConfigurationContext().toConnectorConfiguration()); + final ConnectorConfiguration outgoingActiveConfiguration = restoreSnapshotFlow && outgoingSnapshot.activeConfiguration() != null + ? outgoingSnapshot.activeConfiguration() + : activeFlowContext.getConfigurationContext().toConnectorConfiguration(); + final Map originalActiveConfiguration = toConfigurationMap(outgoingActiveConfiguration); final Map originalWorkingConfiguration = originalWorkingConfigurationContext == null ? originalActiveConfiguration : toConfigurationMap(originalWorkingConfigurationContext.toConnectorConfiguration()); boolean workingContextReleased = false; @@ -1533,13 +1674,28 @@ public void replaceConnector(final Connector replacement, final BundleCoordinate } } + if (restoreSnapshotFlow) { + // A missing Connector leaves the managed group empty, so the persisted flow is restored to reattach its queues + restorePersistedFlow(outgoingSnapshot.flow(), outgoingSnapshot.parameterContext(), + outgoingSnapshot.parameterSecretReferences(), true); + } + activeFlowContext.reload(bundle, replacementLog, replacementActiveConfiguration); connectorDetails = new ConnectorDetails(replacement, replacementCoordinate, replacementLog); bundleCoordinate = replacementCoordinate; - extensionMissing = replacement instanceof GhostConnector; + extensionMissing = replacementMissing; componentType = extensionMissing ? "(Missing) " + getSimpleClassName(componentCanonicalClass) : replacement.getClass().getSimpleName(); initializationContext = replacementInitializationContext; + + // The loaded bundle and whether the extension is missing have changed, so the snapshot is installed again even when it is kept. + synchronized (flowEvolutionLock) { + final ConnectorFlowSnapshot replacementSnapshot = outgoingSnapshot == null || replacementMissing + ? authoritativeFlowSnapshot + : new ConnectorFlowSnapshot(outgoingSnapshot.flow(), outgoingSnapshot.parameterContext(), outgoingSnapshot.parameterSecretReferences(), + outgoingSnapshot.bundle(), replacementActiveConfiguration.toConnectorConfiguration()); + installAuthoritativeSnapshot(replacementSnapshot); + } } catch (final Throwable failure) { if (workingContextModified) { releaseWorkingFlowContext(workingContextState); @@ -1619,6 +1775,691 @@ public boolean isExtensionMissing() { return extensionMissing; } + @Override + public boolean isPendingFlowEvolution() { + synchronized (flowEvolutionLock) { + if (extensionMissing) { + return false; + } + + final ConnectorFlowSnapshot snapshot = authoritativeFlowSnapshot; + final Bundle snapshotBundle = snapshot == null ? null : snapshot.bundle(); + return snapshotBundle != null && !sameBundle(snapshotBundle, bundleCoordinate); + } + } + + @Override + public FlowEvolutionStatus getReportedFlowEvolutionStatus() { + return flowEvolutionProgress.get().reportedStatus(); + } + + private boolean isEvolveDrainComplete() { + return flowEvolutionProgress.get().isDrainComplete(); + } + + private boolean isApplyingEvolvedFlow() { + return getReportedFlowEvolutionStatus() == FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE; + } + + boolean hasFlowEvolutionFailed() { + return flowEvolutionProgress.get().hasFailed(); + } + + private VersionedProcessGroup getAuthoritativeManagedProcessGroup() { + final ConnectorFlowSnapshot snapshot = authoritativeFlowSnapshot; + return snapshot == null ? null : snapshot.flow(); + } + + @Override + public ConnectorFlowSnapshot getAuthoritativeFlowSnapshot() { + return authoritativeFlowSnapshot; + } + + @Override + public boolean restorePendingFlowEvolution(final VersionedConnector persisted, final List activeConfiguration, + final List workingConfiguration) throws FlowUpdateException { + final Bundle managedFlowBundle = resolveManagedFlowBundle(persisted); + final VersionedProcessGroup persistedManagedGroup = persisted.getManagedProcessGroup(); + final Map parameterSecretReferences = ParameterSecretReferences.convertManagedParameterSecretReferences(persisted); + // Components in the persisted group may name NAR versions that are no longer installed. A missing coordinate + // is rewritten only when exactly one compatible bundle is installed. A ghost has no initialization context, + // and its coordinates have to stay as persisted. + if (!extensionMissing) { + resolvePersistedBundles(persistedManagedGroup); + } + + if (extensionMissing && persistedManagedGroup != null) { + // Adopt before inheritConfiguration. A flow save with no snapshot omits the managed group, and inherit + // rebuilds the live group before the persisted one is installed below. + adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); + return false; + } + + if (!extensionMissing && !sameManagedBundle(managedFlowBundle) && persistedManagedGroup != null) { + // Skip inheritConfiguration. Its applyUpdate would replace the pre-upgrade group with the new bundle's + // flow. The restored group keeps the previous bundle, so the next start evolves it. + restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, true); + loadConfigurationsWithoutRebuildingFlow(activeConfiguration, workingConfiguration); + adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); + return true; + } + + return false; + } + + @Override + public void restorePersistedManagedFlow(final VersionedConnector persisted) { + if (!extensionMissing) { + throw new IllegalStateException("Cannot restore the persisted managed flow for " + this + " because its extension is not missing"); + } + + final VersionedProcessGroup persistedManagedGroup = persisted.getManagedProcessGroup(); + if (persistedManagedGroup == null) { + return; + } + + final Bundle managedFlowBundle = resolveManagedFlowBundle(persisted); + final Map parameterSecretReferences = ParameterSecretReferences.convertManagedParameterSecretReferences(persisted); + + // Install the persisted flow while ghosted so queues exist before the FlowFile repository recovers. + // Components stay stopped: a ghost cannot start, and resuming would run them under a missing extension. + try { + restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, false); + } catch (final Exception e) { + logger.error("{} failed to restore the persisted managed flow while ghosted; " + + "queued FlowFiles may not rejoin until NiFi restarts after the Connector becomes loadable again", this, e); + markManagedFlowRestoreFailed(); + } + adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); + } + + @Override + public void restoreTroubleshootingManagedFlow(final VersionedConnector persisted) throws FlowUpdateException { + final Bundle managedFlowBundle = resolveManagedFlowBundle(persisted); + final VersionedProcessGroup persistedManagedGroup = persisted.getManagedProcessGroup(); + final Map parameterSecretReferences = ParameterSecretReferences.convertManagedParameterSecretReferences(persisted); + + if (extensionMissing && persistedManagedGroup != null) { + adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); + restoreTroubleshootingFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences); + return; + } + + if (sameManagedBundle(managedFlowBundle) && persistedManagedGroup != null) { + try { + restorePersistedFlow(persistedManagedGroup, null, Map.of(), true); + adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); + } catch (final Exception e) { + logger.error("{} failed to restore the managed flow while restoring Troubleshooting", this, e); + throw new FlowUpdateException("Failed to restore Managed Process Group from persisted flow: " + e.getMessage(), e); + } + } + } + + @Override + public void ensureAuthoritativeFlowSnapshot() { + if (getAuthoritativeManagedProcessGroup() != null || extensionMissing) { + return; + } + + // Without a snapshot, a later NAR upgrade has no pre-upgrade flow to evolve. + verifyCanCaptureAuthoritativeSnapshot(); + final ConnectorFlowSnapshot snapshot = createAuthoritativeSnapshot(); + + synchronized (flowEvolutionLock) { + // Another thread may have installed a snapshot, such as the pre-upgrade flow, while the live flow was being captured + if (getAuthoritativeManagedProcessGroup() != null) { + return; + } + + verifyCanCaptureAuthoritativeSnapshot(); + installAuthoritativeSnapshot(snapshot); + } + } + + private void restoreTroubleshootingFlow(final VersionedProcessGroup persistedManagedGroup, final VersionedParameterContext parameterContext, + final Map parameterSecretReferences) throws FlowUpdateException { + logger.info("{} was persisted in Troubleshooting mode; restoring Managed Process Group from persisted snapshot", this); + try { + restorePersistedFlow(persistedManagedGroup, parameterContext, parameterSecretReferences, false); + } catch (final Exception e) { + logger.error("{} failed to restore the managed flow while restoring Troubleshooting", this, e); + throw new FlowUpdateException("Failed to restore Managed Process Group from persisted flow: " + e.getMessage(), e); + } + } + + /** + * A group saved before managedFlowBundle existed is attributed to the connector bundle stored in the flow definition. + */ + private static Bundle resolveManagedFlowBundle(final VersionedConnector versionedConnector) { + if (versionedConnector.getManagedFlowBundle() != null) { + return versionedConnector.getManagedFlowBundle(); + } + if (versionedConnector.getManagedProcessGroup() != null) { + return versionedConnector.getBundle(); + } + return null; + } + + private boolean sameManagedBundle(final Bundle managedFlowBundle) { + if (managedFlowBundle == null || bundleCoordinate == null) { + return true; + } + return sameBundle(managedFlowBundle, bundleCoordinate); + } + + /** + * Rewrites processor and controller service bundles in a persisted group to the only installed alternative when + * the exact coordinate is missing. A ghost Connector keeps the snapshot exactly as persisted. + */ + void resolvePersistedBundles(final VersionedProcessGroup group) { + if (extensionMissing || group == null || initializationContext == null) { + return; + } + + initializationContext.resolveBundles(group, BundleCompatibility.RESOLVE_BUNDLE); + } + + void adoptAuthoritativeSnapshot(final VersionedProcessGroup flow, final VersionedParameterContext parameterContext, + final Map parameterSecretReferences, final Bundle managedFlowBundle) { + installAuthoritativeSnapshot(new ConnectorFlowSnapshot(flow, parameterContext, parameterSecretReferences, managedFlowBundle, + activeFlowContext.getConfigurationContext().toConnectorConfiguration())); + } + + void restorePersistedFlow(final VersionedProcessGroup flow, final VersionedParameterContext parameterContext, + final Map parameterSecretReferences, final boolean resumeComponents) { + final ParameterSecretReferences.Resolution resolution = resolvePersistedParameterSecrets(parameterContext, parameterSecretReferences); + if (!resolution.undecryptableParameters().isEmpty()) { + logger.warn("{} could not decrypt the persisted values of sensitive parameters {}; components are left stopped", this, resolution.undecryptableParameters()); + } + + if (resumeComponents && unresolvedParameterSecretReferences.isEmpty() && resolution.undecryptableParameters().isEmpty()) { + activeFlowContext.restorePersistedFlow(flow, resolution.parameterContext()); + } else { + activeFlowContext.restorePersistedFlow(flow, resolution.parameterContext(), false); + } + } + + private ParameterSecretReferences.Resolution resolvePersistedParameterSecrets(final VersionedParameterContext parameterContext, + final Map parameterSecretReferences) { + final ParameterSecretReferences.Resolution resolution = snapshotMapper.resolve(parameterContext, parameterSecretReferences, initializationContext.getSecretsManager()); + unresolvedParameterSecretReferences = Map.copyOf(resolution.unresolvedReferences()); + return resolution; + } + + @Override + public void prepareFlowEvolution() { + synchronized (flowEvolutionLock) { + if (!isPendingFlowEvolution()) { + throw new IllegalStateException("Cannot prepare flow evolution for " + this + " because no evolution is pending"); + } + // Hook progress outlives an attempt only once every node has drained, so the outgoing flow is no longer needed. + final boolean drainCompletedInEarlierAttempt = isEvolveDrainComplete(); + if (!stateTransition.trySetCurrentState(ConnectorState.STOPPED, ConnectorState.DRAINING) + && !stateTransition.trySetCurrentState(ConnectorState.UPDATE_FAILED, ConnectorState.DRAINING)) { + throw new IllegalStateException("Cannot prepare flow evolution for " + this + " from state " + getCurrentState()); + } + + flowEvolutionProgress.set(new FlowEvolutionProgress(drainCompletedInEarlierAttempt + ? FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE + : FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, null)); + final Bundle postUpgradeBundle = loadedBundle(); + final ConnectorFlowSnapshot outgoingSnapshot = authoritativeFlowSnapshot; + final Bundle preUpgradeBundle = outgoingSnapshot == null || outgoingSnapshot.bundle() == null ? postUpgradeBundle : outgoingSnapshot.bundle(); + final StandardFlowEvolutionContext context = new StandardFlowEvolutionContext(new PreUpgradeFlowContext(activeFlowContext, preUpgradeBundle), postUpgradeBundle); + latestFlowEvolutionAttempt = new FlowEvolutionAttempt(context, drainCompletedInEarlierAttempt); + // Only a start request begins an evolution, so the connector is desired RUNNING while it drains and once the + // upgraded flow is applied. A node that joins while this connector is draining inherits the flow mapped from the + // desired state, so it also starts and enters the same evolution. + stateTransition.setDesiredState(ConnectorState.RUNNING); + } + } + + private boolean isFlowEvolutionInProgress() { + synchronized (flowEvolutionLock) { + // Desired state cannot say this. stop() sets the desired state to STOPPED before it aborts the evolution. + // The drain status cannot say this either, because a pending evolution reports EVOLVE_DRAIN_PENDING before its attempt + // begins, while a user-requested drain may also be running. + final StandardFlowEvolutionContext context = currentFlowEvolutionContext(); + return getCurrentState() == ConnectorState.DRAINING + && context != null + && !context.isFailed() + && !hasFlowEvolutionFailed(); + } + } + + private void runFlowEvolutionPreflight(final StandardFlowEvolutionContext context) throws FlowUpdateException { + verifyFlowEvolutionContext(context); + if (!isEvolveDrainComplete()) { + refreshPreUpgradeParameterSecrets(context); + } + + final List ghostResults = new ArrayList<>(); + validateManagedFlowComponents(ghostResults); + if (!ghostResults.isEmpty()) { + final String explanation = ghostResults.getFirst().getExplanation(); + failFlowEvolution(context, explanation, null); + throw new FlowUpdateException(explanation); + } + + verifyFlowEvolutionContext(context); + } + + private void refreshPreUpgradeParameterSecrets(final StandardFlowEvolutionContext context) throws FlowUpdateException { + final ConnectorFlowSnapshot snapshot = authoritativeFlowSnapshot; + if (snapshot == null || snapshot.parameterContext() == null) { + verifyFlowEvolutionContext(context); + unresolvedParameterSecretReferences = Map.of(); + return; + } + + final ParameterSecretReferences.Resolution resolution = snapshotMapper.resolve( + snapshot.parameterContext(), snapshot.parameterSecretReferences(), initializationContext.getSecretsManager()); + if (!resolution.unresolvedReferences().isEmpty()) { + final Map.Entry unresolved = resolution.unresolvedReferences().entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .findFirst() + .orElseThrow(); + final SecretReference reference = unresolved.getValue(); + final String secretName = reference.getFullyQualifiedName() == null ? reference.getSecretName() : reference.getFullyQualifiedName(); + final String explanation = "Flow evolution cannot start: secret [%s] used by parameter [%s] could not be resolved. " + .formatted(secretName, unresolved.getKey()) + + "Restore the secret in its provider, then start the Connector to resume the upgrade."; + verifyFlowEvolutionContext(context); + unresolvedParameterSecretReferences = Map.copyOf(resolution.unresolvedReferences()); + failFlowEvolution(context, explanation, null); + throw new FlowUpdateException(explanation); + } + + verifyFlowEvolutionContext(context); + unresolvedParameterSecretReferences = Map.of(); + if (!resolution.parameterValues().isEmpty()) { + activeFlowContext.getParameterContext().updateParameters(resolution.parameterValues()); + } + } + + @Override + public Future evolveFlow(final ExecutorService executor) throws FlowUpdateException { + Objects.requireNonNull(executor, "Executor Service is required"); + + synchronized (flowEvolutionLock) { + final StandardFlowEvolutionContext context = currentFlowEvolutionContext(); + verifyFlowEvolutionContext(context); + final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; + if (attempt.evolveFuture != null) { + return attempt.evolveFuture; + } + + attempt.evolveFuture = executor.submit(() -> { + runEvolveDrainPhase(context); + return null; + }); + return attempt.evolveFuture; + } + } + + private void runEvolveDrainPhase(final StandardFlowEvolutionContext context) throws FlowUpdateException { + runFlowEvolutionPreflight(context); + if (isEvolveDrainComplete()) { + return; + } + + verifyFlowEvolutionContext(context); + final CompletableFuture connectorFuture; + try { + connectorFuture = invokeFlowEvolutionHook(context); + } catch (final FlowUpdateException e) { + failFlowEvolution(context, e.getMessage(), e); + throw e; + } + + try { + synchronized (flowEvolutionLock) { + verifyFlowEvolutionContext(context); + latestFlowEvolutionAttempt.prepareFuture = connectorFuture; + } + } catch (final FlowUpdateException e) { + connectorFuture.cancel(true); + throw e; + } + + try { + connectorFuture.get(); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new FlowUpdateException("Interrupted while waiting for flow evolution hook for " + this, e); + } catch (final CancellationException e) { + throw new FlowUpdateException("Flow evolution hook was cancelled for " + this, e); + } catch (final ExecutionException e) { + final Throwable cause = e.getCause() == null ? e : e.getCause(); + failFlowEvolution(context, cause.getMessage(), cause); + throw new FlowUpdateException("Flow evolution hook failed for " + this, cause); + } + + completeEvolveDrainPhase(context); + } + + private void completeEvolveDrainPhase(final StandardFlowEvolutionContext context) throws FlowUpdateException { + // The hook may start processors so queues can empty. Those processors must be stopped before the upgraded + // flow is verified, so no FlowFile reaches a connection the upgraded flow removes after it has been checked. + verifyFlowEvolutionContext(context); + if (!stopPreUpgradeFlow()) { + failFlowEvolution(context, "Failed to stop the pre-upgrade flow", null); + throw new FlowUpdateException("Failed to stop the pre-upgrade flow for " + this); + } + + verifyUpgradedFlow(context); + + synchronized (flowEvolutionLock) { + verifyFlowEvolutionContext(context); + flowEvolutionProgress.updateAndGet(progress -> progress.withDrainStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE)); + } + } + + /** + * Fails the evolution if the upgraded flow cannot replace the active flow, for example because it removes a + * connection that still holds FlowFiles. + */ + private void verifyUpgradedFlow(final StandardFlowEvolutionContext context) throws FlowUpdateException { + verifyFlowEvolutionContext(context); + final VersionedExternalFlow proposedFlow; + try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(getConnector().getClass().getClassLoader())) { + proposedFlow = getConnector().getActiveFlow(getWorkingFlowContext()); + } catch (final Exception failure) { + failFlowEvolution(context, failure.getMessage(), failure); + throw new FlowUpdateException("Failed to determine the upgraded flow for " + this, failure); + } + if (proposedFlow == null || proposedFlow.getFlowContents() == null) { + failFlowEvolution(context, "Upgraded flow was not returned", null); + throw new FlowUpdateException("Upgraded flow was not returned for " + this); + } + + verifyFlowEvolutionContext(context); + try { + activeFlowContext.verifyUpdateFlow(proposedFlow); + } catch (final FlowUpdateException e) { + failFlowEvolution(context, e.getMessage(), e); + throw e; + } + } + + private void verifyFlowEvolutionContext(final StandardFlowEvolutionContext context) throws FlowUpdateException { + if (currentFlowEvolutionContext() != context || context == null || context.isFailed() || hasFlowEvolutionFailed() || getCurrentState() != ConnectorState.DRAINING) { + throw new FlowUpdateException("Flow evolution was cancelled for " + this); + } + } + + /** + * @return the context of the current or most recent attempt, or null when no attempt has begun while the evolution is pending + */ + private StandardFlowEvolutionContext currentFlowEvolutionContext() { + final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; + return attempt == null ? null : attempt.context; + } + + private CompletableFuture invokeFlowEvolutionHook(final FlowEvolutionContext evolutionContext) throws FlowUpdateException { + try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(getConnector().getClass().getClassLoader())) { + return Objects.requireNonNull( + getConnector().prepareForFlowEvolution(evolutionContext), + "Connector prepareForFlowEvolution must return a CompletableFuture"); + } + } + + /** + * {@link Connector#applyUpdate} must be safe to run again on a flow it has already partly updated, because a start + * after a failed apply resumes after the hook and applies again. + */ + @Override + public void beginEvolvedFlowUpdate() throws FlowUpdateException { + // Checked again after the drain barrier because an attempt that resumes after the hook skips the evolve-drain phase, and the + // persisted flow is replaced once the upgraded flow is applied. + verifyUpgradedFlow(currentFlowEvolutionContext()); + + synchronized (flowEvolutionLock) { + if (!isFlowEvolutionInProgress() || !isEvolveDrainComplete()) { + throw new FlowUpdateException("Cannot apply the upgraded flow for " + this + " because the evolve-drain phase is not complete"); + } + + // Leaving DRAINING closes the evolution attempt, and prepareForUpdate follows as for any configuration update. + // The status stays EVOLVE_DRAIN_COMPLETE until the upgraded flow is applied so a peer still waiting on the drain + // barrier passes it. The desired state stays RUNNING, because only a start request begins an evolution. + stateTransition.setCurrentState(ConnectorState.PREPARING_FOR_UPDATE); + } + } + + /** + * Marks this evolution failed and cancels its hook after releasing the evolution lock. The hook future is copied + * under the lock so a newer evolution is not cancelled. This does not cancel the evolve-drain task, because it runs + * on that task and cancelling it would interrupt the task before it stops the pre-upgrade flow. + * + * @param expectedContext the evolution to close + * @return false when the context is already closed or has been replaced + */ + private boolean closeFlowEvolutionContext(final StandardFlowEvolutionContext expectedContext) { + final CompletableFuture prepareFuture; + synchronized (flowEvolutionLock) { + final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; + if (attempt == null || attempt.context.isFailed() || attempt.context != expectedContext) { + return false; + } + + attempt.context.fail(); + prepareFuture = attempt.prepareFuture; + } + + cancel(prepareFuture); + return true; + } + + /** + * Marks the current evolution failed and cancels its hook and evolve-drain task. The futures are copied under the + * evolution lock so a newer evolution started after this close is not cancelled. + */ + private void closeCurrentFlowEvolution() { + final CompletableFuture prepareFuture; + final Future evolveDrainTask; + synchronized (flowEvolutionLock) { + final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; + if (attempt == null || attempt.context.isFailed()) { + return; + } + + attempt.context.fail(); + prepareFuture = attempt.prepareFuture; + evolveDrainTask = attempt.evolveFuture; + } + + cancel(evolveDrainTask); + cancel(prepareFuture); + } + + private void cancel(final Future future) { + if (future != null) { + future.cancel(true); + } + } + + private void failFlowEvolution(final StandardFlowEvolutionContext context, final String explanation, final Throwable cause) { + if (!closeFlowEvolutionContext(context)) { + return; + } + + finishFlowEvolutionFailure(explanation, cause); + } + + void failFlowEvolution(final String explanation, final Throwable cause) { + closeCurrentFlowEvolution(); + finishFlowEvolutionFailure(explanation, cause); + } + + /** + * Retries stopping the pre-upgrade flow after {@link #finishFlowEvolutionFailure} left the connector STOPPING. + * Completes pending stop futures and honors a desired RUNNING state when the stop succeeds. + */ + void retryPreUpgradeStop(final FlowEngine scheduler) { + if (getCurrentState() != ConnectorState.STOPPING) { + return; + } + + scheduler.schedule(() -> retryPreUpgradeStop(scheduler, 0), 0, TimeUnit.SECONDS); + } + + private void retryPreUpgradeStop(final FlowEngine scheduler, final int attempt) { + if (getCurrentState() != ConnectorState.STOPPING) { + return; + } + + if (stopPreUpgradeFlow()) { + synchronized (flowEvolutionLock) { + if (getCurrentState() != ConnectorState.STOPPING) { + return; + } + stateTransition.setCurrentState(ConnectorState.STOPPED); + } + logger.info("Successfully stopped the pre-upgrade flow for {} after a failed evolution", this); + + final ConnectorState desiredState = getDesiredState(); + if (desiredState == ConnectorState.RUNNING) { + logger.info("{} was requested to be RUNNING while stopping the pre-upgrade flow so will attempt to start again", this); + start(scheduler, new CompletableFuture<>()); + } + return; + } + + final long delaySeconds = Math.min(60L, 1L << Math.min(attempt, 5)); + logger.warn("Failed to stop the pre-upgrade flow for {}. Will try again in {} seconds", this, delaySeconds); + scheduler.schedule(() -> retryPreUpgradeStop(scheduler, attempt + 1), delaySeconds, TimeUnit.SECONDS); + } + + private void finishFlowEvolutionFailure(final String explanation, final Throwable cause) { + if (!isEvolveDrainComplete() && !stopPreUpgradeFlow()) { + publishFlowEvolutionFailure(explanation, cause); + synchronized (flowEvolutionLock) { + stateTransition.setDesiredState(ConnectorState.STOPPED); + stateTransition.setCurrentState(ConnectorState.STOPPING); + } + return; + } + + publishFlowEvolutionFailure(explanation, cause); + synchronized (flowEvolutionLock) { + stateTransition.setDesiredState(ConnectorState.STOPPED); + stateTransition.setCurrentState(ConnectorState.STOPPED); + // A peer may not have drained yet, so the next attempt drains again. An attempt that started after this + // node's drain had already completed keeps that progress, because the drain barrier may already have passed + // and the upgraded flow may have been partly applied. + final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; + if (attempt == null || !attempt.drainCompletedInEarlierAttempt) { + flowEvolutionProgress.updateAndGet(progress -> progress.replaceDrainStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING)); + } + } + } + + private void publishFlowEvolutionFailure(final String explanation, final Throwable cause) { + final String concreteExplanation = explanation == null || explanation.isBlank() + ? cause == null ? "Unknown flow evolution failure" : cause.getClass().getSimpleName() + : explanation; + final FlowEvolutionProgress previous = flowEvolutionProgress.getAndUpdate(progress -> progress.withFailureIfAbsent(concreteExplanation)); + if (!previous.hasFailed()) { + getComponentLog().error("Flow evolution failed: {}", concreteExplanation, cause); + } + } + + private static boolean isBlockingValidationFailure(final ValidationResult result) { + return !result.isValid() && !isFlowEvolutionFailure(result); + } + + private static boolean isFlowEvolutionFailure(final ValidationResult result) { + return FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()); + } + + private static ValidationResult createFlowEvolutionFailure(final String explanation) { + return new ValidationResult.Builder() + .subject(FLOW_EVOLUTION_VALIDATION_SUBJECT) + .valid(false) + .explanation(explanation) + .build(); + } + + /** + * @return whether the pre-upgrade flow stopped + */ + private boolean stopPreUpgradeFlow() { + try { + final CompletableFuture stopped = activeFlowContext.getRootGroup().getLifecycle().stop(); + if (stopped != null) { + stopped.get(1, TimeUnit.MINUTES); + } + return true; + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Interrupted while stopping the pre-upgrade flow for {}", this, e); + return false; + } catch (final Exception e) { + logger.warn("Failed to stop the pre-upgrade flow for {}", this, e); + return false; + } + } + + /** + * Captures the live flow outside the evolution lock, because capturing resolves secrets, then installs it under the lock + * after checking again that it may be installed. + */ + void captureAuthoritativeSnapshot() { + verifyCanCaptureAuthoritativeSnapshot(); + final ConnectorFlowSnapshot snapshot = createAuthoritativeSnapshot(); + + synchronized (flowEvolutionLock) { + verifyCanCaptureAuthoritativeSnapshot(); + installAuthoritativeSnapshot(snapshot); + } + } + + private void verifyCanCaptureAuthoritativeSnapshot() { + // Applying the upgraded flow after the evolve-drain phase records the new bundle, which is what ends the pending evolution. + if (isPendingFlowEvolution() && !isEvolveDrainComplete()) { + throw new IllegalStateException("Cannot capture an authoritative snapshot for " + this + " while flow evolution is pending"); + } + } + + /** + * Installs the snapshot and brings the drain status in line with whether an evolution is now pending. This is the only + * writer of the snapshot. It must also be called, with the current snapshot, whenever the loaded bundle or whether the + * extension is missing changes. + */ + private void installAuthoritativeSnapshot(final ConnectorFlowSnapshot snapshot) { + synchronized (flowEvolutionLock) { + authoritativeFlowSnapshot = snapshot; + + // Once the snapshot records the loaded bundle no evolution is pending, so no attempt is open and neither its drain progress + // nor its failure applies. + if (!isPendingFlowEvolution()) { + flowEvolutionProgress.set(FlowEvolutionProgress.NONE); + latestFlowEvolutionAttempt = null; + return; + } + + // A node that still has the outgoing flow reports it as pending even before its own attempt begins, so a peer + // does not apply the upgraded flow while this node may still need to drain. + flowEvolutionProgress.updateAndGet(progress -> progress.replaceDrainStatus(FlowEvolutionStatus.INACTIVE, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING)); + } + } + + private ConnectorFlowSnapshot createAuthoritativeSnapshot() { + return snapshotMapper.capture(activeFlowContext, loadedBundle(), initializationContext.getSecretsManager()); + } + + private Bundle loadedBundle() { + return new Bundle(bundleCoordinate.getGroup(), bundleCoordinate.getId(), bundleCoordinate.getVersion()); + } + + private static boolean sameBundle(final Bundle bundle, final BundleCoordinate coordinate) { + return coordinate != null + && Objects.equals(bundle.getGroup(), coordinate.getGroup()) + && Objects.equals(bundle.getArtifact(), coordinate.getId()) + && Objects.equals(bundle.getVersion(), coordinate.getVersion()); + } + @Override public List fetchAllowableValues(final String stepName, final String propertyName) { final WorkingFlowContextState workingContextState = acquireWorkingFlowContext(); @@ -2556,14 +3397,23 @@ private ConnectorAction createStartAction(final boolean stopped, final boolean t } else if (!stopped) { allowed = false; reason = "Connector is not stopped"; + } else if (isExtensionMissing()) { + allowed = false; + reason = "Connector's extension is missing"; + } else if (managedFlowRestoreFailed) { + allowed = false; + reason = "Cannot start " + this + " because its managed flow was not installed while it was ghosted; " + + "restart NiFi so queued FlowFiles rejoin the restored connections before starting"; } else { final Collection validationResults = getValidationErrors(); - if (validationResults.isEmpty()) { + final boolean blockingFailure = validationResults.stream().anyMatch(StandardConnectorNode::isBlockingValidationFailure); + if (!blockingFailure) { allowed = true; reason = null; } else { allowed = false; reason = "Connector is not valid: " + validationResults.stream() + .filter(StandardConnectorNode::isBlockingValidationFailure) .map(ValidationResult::getExplanation) .collect(Collectors.joining("; ")); } @@ -2787,18 +3637,25 @@ public void resetValidationState() { @Override public ValidationStatus getValidationStatus() { - return validationState.get().getStatus(); + return getValidationState().getStatus(); } @Override public ValidationState getValidationState() { - return validationState.get(); + final ValidationState current = validationState.get(); + final String failureExplanation = flowEvolutionProgress.get().failureExplanation(); + if (failureExplanation == null) { + return current; + } + + final List errors = new ArrayList<>(current.getValidationErrors()); + errors.add(createFlowEvolutionFailure(failureExplanation)); + return new ValidationState(ValidationStatus.INVALID, errors); } @Override public Collection getValidationErrors() { - final ValidationState state = validationState.get(); - return state.getValidationErrors(); + return getValidationState().getValidationErrors(); } @Override @@ -2849,17 +3706,18 @@ public ValidationState performValidation() { } validationState.set(resultState); + final ValidationState published = getValidationState(); - if (resultState.getStatus() == ValidationStatus.VALID) { + if (published.getStatus() == ValidationStatus.VALID) { logger.info("Validation completed for {}. Connector is valid.", this); } else { logger.info("Validation completed for {}. Connector is invalid: {}", this, - resultState.getValidationErrors().stream() + published.getValidationErrors().stream() .map(ValidationResult::getExplanation) .collect(Collectors.joining("; "))); } - return resultState; + return published; } } @@ -3051,6 +3909,57 @@ private List fetchAllowableValues(final String stepName, final S return allowableValues; } + /** + * Progress through a pending flow evolution. The drain status is kept when the evolution fails, so a retry knows whether + * this node has already drained the outgoing flow. + * + * @param drainStatus {@link FlowEvolutionStatus#INACTIVE} when no evolution is pending, otherwise this node's evolve-drain progress + * @param failureExplanation why the evolution failed, or null when it has not failed + */ + private record FlowEvolutionProgress(FlowEvolutionStatus drainStatus, String failureExplanation) { + private static final FlowEvolutionProgress NONE = new FlowEvolutionProgress(FlowEvolutionStatus.INACTIVE, null); + + FlowEvolutionStatus reportedStatus() { + return hasFailed() ? FlowEvolutionStatus.FAILED : drainStatus; + } + + boolean isDrainComplete() { + return drainStatus == FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE; + } + + boolean hasFailed() { + return failureExplanation != null; + } + + FlowEvolutionProgress withDrainStatus(final FlowEvolutionStatus status) { + return new FlowEvolutionProgress(status, failureExplanation); + } + + FlowEvolutionProgress replaceDrainStatus(final FlowEvolutionStatus expected, final FlowEvolutionStatus replacement) { + return drainStatus == expected ? withDrainStatus(replacement) : this; + } + + FlowEvolutionProgress withFailureIfAbsent(final String explanation) { + return hasFailed() ? this : new FlowEvolutionProgress(drainStatus, explanation); + } + } + + /** + * One attempt at a pending flow evolution. The futures are each set at most once per attempt, and are read and written + * only while holding the evolution lock, so closing the attempt cancels this attempt's work and never a newer attempt's. + */ + private static final class FlowEvolutionAttempt { + private final StandardFlowEvolutionContext context; + private final boolean drainCompletedInEarlierAttempt; + private CompletableFuture prepareFuture; + private Future evolveFuture; + + private FlowEvolutionAttempt(final StandardFlowEvolutionContext context, final boolean drainCompletedInEarlierAttempt) { + this.context = context; + this.drainCompletedInEarlierAttempt = drainCompletedInEarlierAttempt; + } + } + private static final class WorkingFlowContextState { private final FrameworkFlowContext context; private int useCount; diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java index 10fe9b49af02..4f5aa96b4138 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java @@ -34,6 +34,7 @@ public class StandardConnectorRepoInitializationContext implements ConnectorRepo private final ConnectorRequestReplicator requestReplicator; private final ConnectorConfigurationProvider connectorConfigurationProvider; private final Duration connectorSyncTimeout; + private final Duration connectorFlowEvolutionTimeout; public StandardConnectorRepoInitializationContext(final FlowManager flowManager, final ExtensionManager extensionManager, @@ -42,7 +43,8 @@ public StandardConnectorRepoInitializationContext(final FlowManager flowManager, final NodeTypeProvider nodeTypeProvider, final ConnectorRequestReplicator requestReplicator, final ConnectorConfigurationProvider connectorConfigurationProvider, - final Duration connectorSyncTimeout) { + final Duration connectorSyncTimeout, + final Duration connectorFlowEvolutionTimeout) { this.flowManager = flowManager; this.extensionManager = extensionManager; this.secretsManager = secretsManager; @@ -51,6 +53,7 @@ public StandardConnectorRepoInitializationContext(final FlowManager flowManager, this.requestReplicator = requestReplicator; this.connectorConfigurationProvider = connectorConfigurationProvider; this.connectorSyncTimeout = connectorSyncTimeout; + this.connectorFlowEvolutionTimeout = connectorFlowEvolutionTimeout; } @Override @@ -92,4 +95,9 @@ public ConnectorConfigurationProvider getConnectorConfigurationProvider() { public Duration getConnectorSyncTimeout() { return connectorSyncTimeout; } + + @Override + public Duration getConnectorFlowEvolutionTimeout() { + return connectorFlowEvolutionTimeout; + } } 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 9493225a8700..09c247621f4f 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,7 +30,6 @@ import org.apache.nifi.flow.VersionedConnector; import org.apache.nifi.flow.VersionedConnectorState; import org.apache.nifi.flow.VersionedConnectorValueReference; -import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.nar.ExtensionManager; import org.apache.nifi.nar.NarCloseable; @@ -54,9 +53,12 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -64,6 +66,9 @@ public class StandardConnectorRepository implements ConnectorRepository { private static final Logger logger = LoggerFactory.getLogger(StandardConnectorRepository.class); private static final Duration SYNC_POLL_INTERVAL = Duration.ofSeconds(2); + private static final List FLOW_EVOLUTION_POLL_INTERVALS = List.of( + Duration.ofSeconds(2), Duration.ofSeconds(5), Duration.ofSeconds(10), Duration.ofSeconds(30)); + private static final Duration DEFAULT_FLOW_EVOLUTION_DRAIN_TIMEOUT = Duration.ofMinutes(30); /** * Soft cardinality limit beyond which a WARN is emitted when a {@link ConnectorConfigurationProvider} @@ -75,6 +80,9 @@ public class StandardConnectorRepository implements ConnectorRepository { private final Map connectors = new ConcurrentHashMap<>(); private final Set connectorsBeingMigrated = ConcurrentHashMap.newKeySet(); private final FlowEngine lifecycleExecutor = new FlowEngine(8, "NiFi Connector Lifecycle"); + private final ExecutorService flowEvolutionCoordinatorExecutor = Executors.newThreadPerTaskExecutor( + Thread.ofVirtual().name("NiFi Connector Flow Evolution Coordinator-", 1).factory()); + private final Map> evolveThenStartFuturesByConnectorId = new ConcurrentHashMap<>(); private volatile FlowManager flowManager; private volatile ExtensionManager extensionManager; @@ -83,6 +91,7 @@ public class StandardConnectorRepository implements ConnectorRepository { private volatile AssetManager assetManager; private volatile ConnectorConfigurationProvider configurationProvider; private volatile Duration syncTimeout; + private volatile Duration flowEvolutionDrainTimeout = DEFAULT_FLOW_EVOLUTION_DRAIN_TIMEOUT; @Override public void initialize(final ConnectorRepositoryInitializationContext context) { @@ -94,6 +103,7 @@ public void initialize(final ConnectorRepositoryInitializationContext context) { this.assetManager = context.getAssetManager(); this.configurationProvider = context.getConnectorConfigurationProvider(); this.syncTimeout = context.getConnectorSyncTimeout(); + this.flowEvolutionDrainTimeout = canonicalFlowEvolutionDrainTimeout(context.getConnectorFlowEvolutionTimeout()); logger.debug("Successfully initialized ConnectorRepository with configurationProvider={}, syncTimeout={}", configurationProvider != null ? configurationProvider.getClass().getSimpleName() : "null", syncTimeout); } @@ -243,6 +253,24 @@ public ConnectorSyncResult syncConnector(final VersionedConnector versionedConne || currentState == ConnectorState.UPDATE_FAILED || isConfigurationUpdated(connector, persistedActiveConfig, effectiveActiveConfig, persistedWorkingConfig, effectiveWorkingConfig); final boolean restoringTroubleshooting = effectiveScheduledState == VersionedConnectorState.TROUBLESHOOTING; + // inheritConfiguration rebuilds the managed group from the loaded bundle. After a NAR upgrade the persisted + // group still belongs to the previous bundle and may hold the queues the evolution hook has to drain, so that + // group has to be installed instead of rebuilt. A same-bundle sync keeps the rebuilt flow and the snapshot the + // Connector already holds. + final boolean evolutionPending; + try { + evolutionPending = connector.restorePendingFlowEvolution(versionedConnector, effectiveActiveConfig, effectiveWorkingConfig); + } catch (final Exception e) { + logger.error("{} failed to restore the pre-upgrade flow", connector, e); + connector.markInvalid("Flow Synchronization Failure", e.getMessage()); + return ConnectorSyncResult.failed(connector); + } + if (evolutionPending) { + if (restoringTroubleshooting) { + connector.restoreTroubleshootingState(); + } + return ConnectorSyncResult.synced(connector, effectiveScheduledState); + } // Configuration must be inherited even when the effective state is TROUBLESHOOTING. The Connector's managed // Parameter Context is intentionally not registered with the global ParameterContextManager (see @@ -250,13 +278,14 @@ public ConnectorSyncResult syncConnector(final VersionedConnector versionedConne // re-populate that Parameter Context by letting the Connector's applyUpdate run with the persisted active // configuration, which is exactly what inheritConfiguration does. // - // For a TROUBLESHOOTING restoration, the Connector's authoritative active flow that inheritConfiguration - // produces is then immediately overlaid by restoreTroubleshootingFlow with the user's persisted Managed - // Process Group snapshot. The structural overlay preserves the in-memory Parameter Context binding, so the - // Connector-supplied parameter values remain available, while the user's flow modifications are the ones - // running. The transient Connector-supplied flow shape is invisible outside this synchronization cycle: flow - // synchronization completes before the FlowFile Repository attaches FlowFiles to queues, so no FlowFile - // movement can observe it. + // For a TROUBLESHOOTING restoration, the flow inheritConfiguration produces is then replaced by the persisted + // managed group, which holds the user's edits. That restore preserves the in-memory Parameter Context binding, + // so the Connector-supplied parameter values remain available. The transient Connector-supplied flow shape is + // invisible outside this synchronization cycle: flow synchronization completes before the FlowFile Repository + // attaches FlowFiles to queues, so no FlowFile movement can observe it. + // + // Outside of Troubleshooting, only a Connector whose extension is missing has its persisted managed group + // installed. Any other Connector keeps the rebuilt flow and the snapshot that applyUpdate captured. if (configChanged || restoringTroubleshooting) { logger.info("{} configuration needs synchronization", connector); try { @@ -280,27 +309,30 @@ public ConnectorSyncResult syncConnector(final VersionedConnector versionedConne } if (restoringTroubleshooting) { - final VersionedProcessGroup persistedManagedGroup = versionedConnector.getManagedProcessGroup(); - if (persistedManagedGroup == null) { + try { + connector.restoreTroubleshootingManagedFlow(versionedConnector); + } catch (final FlowUpdateException e) { + connector.markInvalid("Flow Synchronization Failure", e.getMessage()); + return ConnectorSyncResult.failed(connector); + } + } else if (connector.isExtensionMissing()) { + connector.restorePersistedManagedFlow(versionedConnector); + } + + // A reconnecting node may re-sync an existing Connector without inheriting configuration and without holding a snapshot + connector.ensureAuthoritativeFlowSnapshot(); + + if (restoringTroubleshooting) { + if (versionedConnector.getManagedProcessGroup() == null) { logger.warn("{} effective scheduled state is TROUBLESHOOTING but no Managed Process Group snapshot was persisted; leaving Managed Process Group unchanged", connector); - } else { - logger.info("{} was persisted in Troubleshooting mode; restoring Managed Process Group from persisted snapshot", connector); - try { - connector.getActiveFlowContext().restoreTroubleshootingFlow(persistedManagedGroup); - } catch (final Exception e) { - logger.error("{} failed to restore Managed Process Group from Troubleshooting snapshot", connector, e); - connector.markInvalid("Flow Synchronization Failure", - "Failed to restore Managed Process Group from Troubleshooting snapshot: " + e.getMessage()); - return ConnectorSyncResult.failed(connector); - } } if (connector.getCurrentState() != ConnectorState.TROUBLESHOOTING) { // Use restoreTroubleshootingState rather than enterTroubleshooting because the former does not stop // running components within the Managed Process Group. Components inside the Managed Process Group that - // were persisted as RUNNING have just been restored to the RUNNING state by restoreTroubleshootingFlow above; - // calling enterTroubleshooting here would immediately stop them, violating the contract that persisted - // user modifications (including running processors) should survive a NiFi restart while in Troubleshooting. + // were persisted as RUNNING have just been restored; calling enterTroubleshooting here would immediately + // stop them, violating the contract that persisted user modifications (including running processors) + // should survive a NiFi restart while in Troubleshooting. connector.restoreTroubleshootingState(); } @@ -586,10 +618,155 @@ private void syncFromProviderForRead(final ConnectorNode connector) { } @Override - public Future startConnector(final ConnectorNode connector) { + public Future startConnector(final ConnectorNode connector, final ConnectorUpdateContext persistenceContext) { + Objects.requireNonNull(persistenceContext, "Flow persistence context is required"); + + final String connectorId = connector.getIdentifier(); + final CompletableFuture runningEvolution = evolveThenStartFuturesByConnectorId.get(connectorId); + if (runningEvolution != null) { + return runningEvolution; + } + if (!connector.isPendingFlowEvolution()) { + return connector.start(lifecycleExecutor); + } + + final CompletableFuture evolutionFuture = new CompletableFuture<>(); + final CompletableFuture existingEvolution = evolveThenStartFuturesByConnectorId.putIfAbsent(connectorId, evolutionFuture); + if (existingEvolution != null) { + return existingEvolution; + } + + try { + connector.prepareFlowEvolution(); + } catch (final Throwable failure) { + evolutionFuture.completeExceptionally(failure); + evolveThenStartFuturesByConnectorId.remove(connectorId, evolutionFuture); + if (failure instanceof final Error error) { + throw error; + } + return evolutionFuture; + } + + try { + flowEvolutionCoordinatorExecutor.submit(() -> evolveThenStart(connector, evolutionFuture, persistenceContext)); + } catch (final Throwable failure) { + try { + connector.abortUpdate(failure); + } catch (final Throwable cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + evolutionFuture.completeExceptionally(failure); + evolveThenStartFuturesByConnectorId.remove(connectorId, evolutionFuture); + if (failure instanceof final Error error) { + throw error; + } + } + + return evolutionFuture; + } + + private void evolveThenStart(final ConnectorNode connector, final CompletableFuture evolutionFuture, final ConnectorUpdateContext persistenceContext) { + boolean startAttempted = false; + try { + final Future startFuture = runFlowEvolution(connector, persistenceContext); + startAttempted = true; + // The evolution is complete once its start is issued. A later START or STOP then acts on the connector directly. + evolveThenStartFuturesByConnectorId.remove(connector.getIdentifier(), evolutionFuture); + startFuture.get(); + evolutionFuture.complete(null); + } catch (final Throwable failure) { + if (failure instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + + if (startAttempted) { + logger.error("{} was evolved but did not start", connector, failure); + } else { + logger.error("Flow evolution failed for {}", connector, failure); + } + + handleFlowEvolutionFailure(connector, evolutionFuture, failure, startAttempted); + + if (failure instanceof final Error error) { + throw error; + } + } finally { + evolveThenStartFuturesByConnectorId.remove(connector.getIdentifier(), evolutionFuture); + } + } + + /** + * Runs the evolve-drain phase of the evolution, then applies the upgraded flow as a configuration update. + * + * @return the future for starting the evolved connector + */ + private Future runFlowEvolution(final ConnectorNode connector, final ConnectorUpdateContext persistenceContext) throws Throwable { + awaitFlowEvolutionDrain(connector, connector.evolveFlow(flowEvolutionCoordinatorExecutor)); + + // No node applies the upgraded flow until every node that still has the outgoing flow has drained it. + waitForFlowEvolutionStatus(connector); + + // Every node has drained, so as at startup the preparation is local and no cluster-wide wait for UPDATING is needed. + // A peer that has not yet observed the drain barrier may still be DRAINING or preparing. + connector.beginEvolvedFlowUpdate(); + connector.prepareForUpdate(); + completeUpdate(connector, persistenceContext, Set.of(ConnectorState.PREPARING_FOR_UPDATE, ConnectorState.UPDATING, ConnectorState.DRAINING)); + + // The connector stayed desired RUNNING throughout the evolution, so the flow saved after the apply already records it as running. + logger.info("{} has been successfully evolved; starting", connector); return connector.start(lifecycleExecutor); } + private void awaitFlowEvolutionDrain(final ConnectorNode connector, final Future future) throws Throwable { + try { + future.get(flowEvolutionDrainTimeout.toNanos(), TimeUnit.NANOSECONDS); + } catch (final TimeoutException e) { + final FlowUpdateException timedOut = new FlowUpdateException("Flow evolution drain timed out for " + connector, e); + connector.abortUpdate(timedOut); + throw timedOut; + } catch (final InterruptedException e) { + connector.abortUpdate(e); + throw e; + } catch (final CancellationException e) { + throw new FlowUpdateException("Flow evolution was cancelled for " + connector, e); + } catch (final ExecutionException e) { + final Throwable cause = e.getCause() == null ? e : e.getCause(); + if (cause instanceof final CancellationException cancelled) { + throw new FlowUpdateException("Flow evolution was cancelled for " + connector, cancelled); + } + throw cause; + } + } + + private static Duration canonicalFlowEvolutionDrainTimeout(final Duration timeout) { + if (timeout == null || timeout.isZero() || timeout.isNegative()) { + return DEFAULT_FLOW_EVOLUTION_DRAIN_TIMEOUT; + } + + return timeout; + } + + private void handleFlowEvolutionFailure(final ConnectorNode connector, final CompletableFuture evolutionFuture, + final Throwable failure, final boolean startAttempted) { + // A failed evolution is not saved; the persisted flow stays as it was last saved until the connector is corrected. + // A failed start of the evolved connector is an ordinary failed start, because the upgraded flow has already been saved. + if (!startAttempted) { + try { + // While DRAINING this fails the evolution. Once preparation for the upgraded flow has begun it leaves UPDATE_FAILED. + connector.abortUpdate(failure); + if (connector.getCurrentState() == ConnectorState.STOPPING && connector instanceof final StandardConnectorNode standardConnector) { + standardConnector.retryPreUpgradeStop(lifecycleExecutor); + } + } catch (final Throwable cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + + // Removed before completing, so a START issued once the caller sees this result begins a new attempt instead of receiving this future. + evolveThenStartFuturesByConnectorId.remove(connector.getIdentifier(), evolutionFuture); + evolutionFuture.completeExceptionally(failure); + } + @Override public Future stopConnector(final ConnectorNode connector) { return connector.stop(lifecycleExecutor); @@ -635,6 +812,9 @@ public void applyUpdate(final ConnectorNode connector, final ConnectorUpdateCont throw new IllegalStateException("Cannot apply an update to " + connector + " while it is in Troubleshooting mode; " + "exit Troubleshooting mode before applying updates."); } + if (connector.isPendingFlowEvolution()) { + throw new IllegalStateException("Cannot apply an update to " + connector + " while an upgrade is pending; start the connector instead."); + } if (configurationProvider != null && !configurationProvider.shouldApplyUpdate(connector.getIdentifier())) { logger.info("ConnectorConfigurationProvider indicated framework should not apply update for {}; skipping framework update process", connector); @@ -674,17 +854,7 @@ private void updateConnector(final ConnectorNode connector, final ConnectorState logger.debug("Waiting for {} to transition to UPDATING state", connector); waitForState(connector, Set.of(ConnectorState.UPDATING), Set.of(ConnectorState.PREPARING_FOR_UPDATE)); - // Apply the update to the connector. - logger.info("{} has now completed preparations for update; applying update now", connector); - connector.applyUpdate(); - logger.info("{} has successfully applied update", connector); - - // Now that the update has been applied, save the flow so that the updated configuration is persisted. - context.saveFlow(); - - // Wait for all nodes to complete the update. - waitForState(connector, Set.of(ConnectorState.UPDATED), Set.of(ConnectorState.UPDATING)); - logger.info("{} has successfully completed update on all nodes", connector); + completeUpdate(connector, context, Set.of(ConnectorState.UPDATING)); // If the initial desired state was RUNNING, start the connector again. Otherwise, stop it. // We don't simply leave it be as the prepareForUpdate / update may have changed the state of some components. @@ -704,6 +874,26 @@ private void updateConnector(final ConnectorNode connector, final ConnectorState } } + /** + * Applies and saves an update for a connector that is UPDATING, then waits for every connected node to reach UPDATED. + * + * @param allowableWhileWaiting cluster states that may be observed while waiting for UPDATED + */ + private void completeUpdate(final ConnectorNode connector, final ConnectorUpdateContext context, final Set allowableWhileWaiting) + throws FlowUpdateException, IOException, InterruptedException { + // Apply the update to the connector. + logger.info("{} has now completed preparations for update; applying update now", connector); + connector.applyUpdate(); + logger.info("{} has successfully applied update", connector); + + // Now that the update has been applied, save the flow so that the updated configuration is persisted. + context.saveFlow(); + + // Wait for all nodes to complete the update. + waitForState(connector, Set.of(ConnectorState.UPDATED), allowableWhileWaiting); + logger.info("{} has successfully completed update on all nodes", connector); + } + private void waitForState(final ConnectorNode connector, final Set desiredStates, final Set allowableStates) throws FlowUpdateException, IOException, InterruptedException { @@ -711,7 +901,22 @@ private void waitForState(final ConnectorNode connector, final Set= Duration.ofMinutes(1).toNanos(); + } + + private void sleepForFlowEvolutionPoll(final int pollIndex) throws InterruptedException { + Thread.sleep(FLOW_EVOLUTION_POLL_INTERVALS.get(Math.min(pollIndex, FLOW_EVOLUTION_POLL_INTERVALS.size() - 1))); + } + + private FlowEvolutionStatus getFlowEvolutionStatus(final ConnectorNode connector) throws IOException { + return requestReplicator == null + ? connector.getReportedFlowEvolutionStatus() + : requestReplicator.getFlowEvolutionStatus(connector.getIdentifier()); + } + + @Override + public void shutdown() { + flowEvolutionCoordinatorExecutor.shutdownNow(); + lifecycleExecutor.shutdownNow(); + } + @Override public void beginMigration(final String connectorId) { connectorsBeingMigrated.add(connectorId); @@ -865,6 +1138,9 @@ public void configureConnector(final ConnectorNode connector, final String stepN throw new IllegalStateException("Cannot modify the configuration of " + connector + " while it is in Troubleshooting mode; " + "exit Troubleshooting mode before modifying the Connector configuration."); } + if (connector.getCurrentState() == ConnectorState.DRAINING) { + throw new IllegalStateException("Cannot modify the configuration of " + connector + " while it is draining an upgrade."); + } if (configurationProvider != null) { final ConnectorWorkingConfiguration mergedConfiguration = buildMergedWorkingConfiguration(connector, stepName, configuration); @@ -1074,6 +1350,11 @@ private void syncFromProvider(final ConnectorNode connector) { if (configurationProvider == null) { return; } + // A read must not pull an external edit into the working configuration while the upgrade hook is running. + // The hook and the flow it applies have to use the configuration that was current when evolution started. + if (connector.getCurrentState() == ConnectorState.DRAINING) { + return; + } final String connectorId = connector.getIdentifier(); final Optional externalConfig = configurationProvider.load(connectorId); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java index 79b9613f9de3..15f0c93f56b9 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java @@ -23,6 +23,7 @@ import org.apache.nifi.components.connector.components.ProcessGroupFacade; import org.apache.nifi.flow.Bundle; import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.logging.ComponentLog; @@ -33,6 +34,7 @@ public class StandardFlowContext implements FrameworkFlowContext { private final ProcessGroup managedProcessGroup; + private final AssetManager assetManager; private final ProcessGroupFacadeFactory groupFacadeFactory; private final ParameterContextFacadeFactory parameterContextFacadeFactory; private final FlowContextType flowContextType; @@ -44,8 +46,14 @@ public StandardFlowContext(final ProcessGroup managedProcessGroup, final Mutable final ProcessGroupFacadeFactory groupFacadeFactory, final ParameterContextFacadeFactory parameterContextFacadeFactory, final ComponentLog connectorLog, final FlowContextType flowContextType, final Bundle bundle) { + this(managedProcessGroup, configurationContext, null, groupFacadeFactory, parameterContextFacadeFactory, connectorLog, flowContextType, bundle); + } + public StandardFlowContext(final ProcessGroup managedProcessGroup, final MutableConnectorConfigurationContext configurationContext, final AssetManager assetManager, + final ProcessGroupFacadeFactory groupFacadeFactory, final ParameterContextFacadeFactory parameterContextFacadeFactory, final ComponentLog connectorLog, + final FlowContextType flowContextType, final Bundle bundle) { this.managedProcessGroup = managedProcessGroup; + this.assetManager = assetManager; this.groupFacadeFactory = groupFacadeFactory; this.parameterContextFacadeFactory = parameterContextFacadeFactory; this.flowContextType = flowContextType; @@ -79,7 +87,7 @@ public void verifyUpdateFlow(final VersionedExternalFlow versionedExternalFlow) try { managedProcessGroup.verifyCanUpdate(versionedExternalFlow, true, false); } catch (final IllegalStateException e) { - throw new FlowUpdateException("Flow is not in a state that allows the requested update", e); + throw new FlowUpdateException("Flow is not in a state that allows the requested update: " + e.getMessage(), e); } } @@ -105,23 +113,55 @@ public void updateFlow(final VersionedExternalFlow versionedExternalFlow, final parameterContext = parameterContextFacadeFactory.create(managedProcessGroup); } + /** + * Restores a persisted flow into the managed process group, keeping component identifiers so queued FlowFiles + * reattach. When {@code parameterContext} is non-null its values are applied to the managed parameter context. + * Components resume according to the Process Group's auto-resume setting. + */ + @Override + public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext) { + final VersionedExternalFlow externalFlow = toExternalFlow(persistedFlow, parameterContext); + managedProcessGroup.restoreFlowPreservingIdentifiers(externalFlow); + finishRestorePersistedFlow(externalFlow, parameterContext); + } + + /** + * Restores a persisted flow into the managed process group, keeping component identifiers so queued FlowFiles + * reattach. When {@code resumeComponentState} is false, components are left stopped. + */ @Override - public void restoreTroubleshootingFlow(final VersionedProcessGroup troubleshootingProcessGroup) { + public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext, final boolean resumeComponentState) { + final VersionedExternalFlow externalFlow = toExternalFlow(persistedFlow, parameterContext); + managedProcessGroup.restoreFlowPreservingIdentifiers(externalFlow, resumeComponentState); + finishRestorePersistedFlow(externalFlow, parameterContext); + } + + private VersionedExternalFlow toExternalFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext) { final VersionedExternalFlow externalFlow = new VersionedExternalFlow(); - externalFlow.setFlowContents(troubleshootingProcessGroup); - externalFlow.setParameterContexts(Map.of()); + externalFlow.setFlowContents(persistedFlow); + if (parameterContext == null) { + externalFlow.setParameterContexts(Map.of()); + } else { + externalFlow.setParameterContexts(Map.of(parameterContext.getIdentifier(), parameterContext)); + } final ParameterContext managedGroupParameterContext = managedProcessGroup.getParameterContext(); if (managedGroupParameterContext != null) { - updateParameterContextNames(troubleshootingProcessGroup, managedGroupParameterContext.getName()); + updateParameterContextNames(persistedFlow, managedGroupParameterContext.getName()); } + return externalFlow; + } - managedProcessGroup.restoreFlowPreservingIdentifiers(externalFlow); - + private void finishRestorePersistedFlow(final VersionedExternalFlow externalFlow, final VersionedParameterContext parameterContext) { final ReloadableState currentState = reloadableState; final ProcessGroupFacade rootGroup = groupFacadeFactory.create(managedProcessGroup, currentState.connectorLog()); reloadableState = new ReloadableState(currentState.configurationContext(), currentState.connectorLog(), currentState.bundle(), rootGroup); - parameterContext = parameterContextFacadeFactory.create(managedProcessGroup); + this.parameterContext = parameterContextFacadeFactory.create(managedProcessGroup); + + if (parameterContext != null && parameterContext.getParameters() != null) { + final ConnectorParameterLookup parameterLookup = new ConnectorParameterLookup(externalFlow.getParameterContexts().values(), assetManager); + getParameterContext().updateParameters(parameterLookup.getParameterValues()); + } } private void updateParameterContextNames(final VersionedProcessGroup group, final String parameterContextName) { diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowEvolutionContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowEvolutionContext.java new file mode 100644 index 000000000000..3b6f6d0e632c --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowEvolutionContext.java @@ -0,0 +1,62 @@ +/* + * 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.components.connector.components.FlowContext; +import org.apache.nifi.flow.Bundle; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class StandardFlowEvolutionContext implements FlowEvolutionContext { + private static final String CLOSED_MESSAGE = "Flow evolution has failed and the context can no longer be used"; + + private final FlowContext preUpgradeActiveFlowContext; + private final Bundle postUpgradeBundle; + private final AtomicBoolean failed = new AtomicBoolean(); + + public StandardFlowEvolutionContext(final FlowContext preUpgradeActiveFlowContext, final Bundle postUpgradeBundle) { + this.preUpgradeActiveFlowContext = preUpgradeActiveFlowContext; + this.postUpgradeBundle = postUpgradeBundle; + } + + void fail() { + failed.set(true); + } + + boolean isFailed() { + return failed.get(); + } + + @Override + public FlowContext getPreUpgradeActiveFlowContext() { + ensureOpen(); + return preUpgradeActiveFlowContext; + } + + @Override + public Bundle getPostUpgradeBundle() { + ensureOpen(); + return postUpgradeBundle; + } + + private void ensureOpen() { + if (failed.get()) { + throw new IllegalStateException(CLOSED_MESSAGE); + } + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java index 1b3b865ba2b2..79a90628cf84 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/ExtensionBuilder.java @@ -32,6 +32,7 @@ import org.apache.nifi.components.connector.ConfigurationStep; import org.apache.nifi.components.connector.Connector; import org.apache.nifi.components.connector.ConnectorDetails; +import org.apache.nifi.components.connector.ConnectorFlowSnapshotMapper; import org.apache.nifi.components.connector.ConnectorNode; import org.apache.nifi.components.connector.ConnectorPropertyDescriptor; import org.apache.nifi.components.connector.ConnectorPropertyGroup; @@ -501,6 +502,9 @@ public ConnectorNode buildConnector(final boolean loadInitialFlow) { requireNonNull(stateManagerProvider, "State Manager Provider"); requireNonNull(extensionManager, "Extension Manager"); requireNonNull(managedProcessGroup, "Managed Process Group"); + requireNonNull(flowController, "FlowController"); + final ConnectorFlowSnapshotMapper connectorFlowSnapshotMapper = new ConnectorFlowSnapshotMapper( + extensionManager, serviceProvider, flowController.getPropertyEncryptionProvider()); final Authorizable connectorsAuthorizable = new Authorizable() { @Override @@ -519,7 +523,7 @@ public Resource getResource() { connector = createConnector(); } catch (final Exception e) { logger.error("Could not create Connector of type {} from {} for ID {} due to: {}; creating \"Ghost\" implementation", type, bundleCoordinate, identifier, e.getMessage(), e); - return createGhostConnectorNode(connectorsAuthorizable, e); + return createGhostConnectorNode(connectorsAuthorizable, connectorFlowSnapshotMapper, e); } final String componentType = connector.getClass().getSimpleName(); @@ -539,6 +543,7 @@ public Resource getResource() { activeConfigurationContext, connectorStateTransition, flowContextFactory, + connectorFlowSnapshotMapper, connectorValidationTrigger, false ); @@ -555,7 +560,7 @@ public Resource getResource() { connectorNode.initializeConnector(initContext); } catch (final Exception e) { logger.error("Could not initialize Connector of type {} from {} for ID {}; creating \"Ghost\" implementation", type, bundleCoordinate, identifier, e); - return createGhostConnectorNode(connectorsAuthorizable, e); + return createGhostConnectorNode(connectorsAuthorizable, connectorFlowSnapshotMapper, e); } if (loadInitialFlow) { @@ -563,14 +568,15 @@ public Resource getResource() { connectorNode.loadInitialFlow(); } catch (final Exception e) { logger.error("Failed to load initial flow for {}; creating \"Ghost\" implementation", connectorNode, e); - return createGhostConnectorNode(connectorsAuthorizable, e); + return createGhostConnectorNode(connectorsAuthorizable, connectorFlowSnapshotMapper, e); } } return connectorNode; } - private ConnectorNode createGhostConnectorNode(final Authorizable connectorsAuthorizable, final Exception cause) { + private ConnectorNode createGhostConnectorNode(final Authorizable connectorsAuthorizable, final ConnectorFlowSnapshotMapper connectorFlowSnapshotMapper, + final Exception cause) { final GhostConnector ghostConnector = new GhostConnector(identifier, type, cause); final String simpleClassName = type.contains(".") ? StringUtils.substringAfterLast(type, ".") : type; final String componentType = "(Missing) " + simpleClassName; @@ -593,6 +599,7 @@ private ConnectorNode createGhostConnectorNode(final Authorizable connectorsAuth activeConfigurationContext, connectorStateTransition, flowContextFactory, + connectorFlowSnapshotMapper, connectorValidationTrigger, true ); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java index b80025d07eb0..58a149e0bff9 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java @@ -424,6 +424,8 @@ public class FlowController implements ReportingTaskProvider, FlowAnalysisRulePr private volatile boolean shutdown = false; + private volatile FlowService flowService; + private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private final TimedLock readLock = new TimedLock(rwLock.readLock(), "FlowControllerReadLock", 1); private final TimedLock writeLock = new TimedLock(rwLock.writeLock(), "FlowControllerWriteLock", 1); @@ -971,6 +973,8 @@ private static ConnectorRepository createConnectorRepository(final NiFiPropertie final String syncTimeoutValue = properties.getProperty(NiFiProperties.CONNECTOR_SYNC_TIMEOUT, NiFiProperties.DEFAULT_CONNECTOR_SYNC_TIMEOUT); final long syncTimeoutMillis = FormatUtils.getTimeDuration(syncTimeoutValue, TimeUnit.MILLISECONDS); final Duration connectorSyncTimeout = Duration.ofMillis(syncTimeoutMillis); + final String evolutionTimeoutValue = properties.getProperty(NiFiProperties.CONNECTOR_FLOW_EVOLUTION_TIMEOUT, NiFiProperties.DEFAULT_CONNECTOR_FLOW_EVOLUTION_TIMEOUT); + final long evolutionTimeoutMillis = FormatUtils.getTimeDuration(evolutionTimeoutValue, TimeUnit.MILLISECONDS); final ConnectorRepositoryInitializationContext initializationContext = new StandardConnectorRepoInitializationContext( flowManager, @@ -980,7 +984,8 @@ private static ConnectorRepository createConnectorRepository(final NiFiPropertie nodeTypeProvider, requestReplicator, connectorConfigurationProvider, - connectorSyncTimeout + connectorSyncTimeout, + Duration.ofMillis(evolutionTimeoutMillis) ); synchronized (created) { @@ -1606,7 +1611,7 @@ public void trigger(final ComponentNode component) { continue; } - connectorRepository.startConnector(connectorNode); + connectorRepository.startConnector(connectorNode, this::saveFlowAfterConnectorEvolution); } catch (final Throwable t) { LOG.error("Unable to start {}", connectorNode, t); } @@ -2050,6 +2055,8 @@ public void shutdown(final boolean kill) { loadBalanceClientRegistry.stop(); } + connectorRepository.shutdown(); + if (processScheduler != null) { processScheduler.shutdown(); } @@ -2520,11 +2527,15 @@ public void startProcessGroup(final ProcessGroup processGroup) { } } + public void setFlowService(final FlowService flowService) { + this.flowService = flowService; + } + public void startConnector(final ConnectorNode connectorNode) { writeLock.lock(); try { if (initialized.get()) { - connectorRepository.startConnector(connectorNode); + connectorRepository.startConnector(connectorNode, this::saveFlowAfterConnectorEvolution); } else { startConnectorsAfterInitialization.add(connectorNode); } @@ -2533,6 +2544,15 @@ public void startConnector(final ConnectorNode connectorNode) { } } + private void saveFlowAfterConnectorEvolution() throws IOException { + final FlowService currentFlowService = flowService; + if (currentFlowService == null) { + throw new IllegalStateException("Cannot persist the flow because the Flow Service is not set"); + } + + currentFlowService.saveFlowChanges(); + } + public boolean isInitialized() { return initialized.get(); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java index 25da34effb92..8d9502a16a04 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/StandardFlowService.java @@ -208,6 +208,8 @@ private StandardFlowService( if (clusterCoordinator != null) { clusterCoordinator.setFlowService(this); } + + controller.setFlowService(this); this.revisionManager = revisionManager; this.narManager = narManager; this.parameterContextAssetSynchronizer = parameterContextAssetSynchronizer; diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/FlowControllerFlowContextFactory.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/FlowControllerFlowContextFactory.java index 341ba781b361..c24607c12982 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/FlowControllerFlowContextFactory.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/flow/FlowControllerFlowContextFactory.java @@ -71,8 +71,8 @@ public FlowControllerFlowContextFactory(final FlowController flowController, fin @Override public FrameworkFlowContext createActiveFlowContext(final String connectorId, final ComponentLog connectorLogger, final Bundle bundle) { - return new StandardFlowContext(activeManagedProcessGroup, activeConfigurationContext, processGroupFacadeFactory, - parameterContextFacadeFactory, connectorLogger, FlowContextType.ACTIVE, bundle); + return new StandardFlowContext(activeManagedProcessGroup, activeConfigurationContext, flowController.getConnectorAssetManager(), + processGroupFacadeFactory, parameterContextFacadeFactory, connectorLogger, FlowContextType.ACTIVE, bundle); } @Override @@ -85,8 +85,8 @@ public FrameworkFlowContext createWorkingFlowContext(final String connectorId, f final MutableConnectorConfigurationContext workingConfigurationContext = activeConfigurationContext.clone(); - return new StandardFlowContext(processGroup, workingConfigurationContext, processGroupFacadeFactory, - parameterContextFacadeFactory, connectorLogger, FlowContextType.WORKING, bundle); + return new StandardFlowContext(processGroup, workingConfigurationContext, flowController.getConnectorAssetManager(), + processGroupFacadeFactory, parameterContextFacadeFactory, connectorLogger, FlowContextType.WORKING, bundle); } private void copyGroupContents(final ProcessGroup sourceGroup, final ProcessGroup destinationGroup, final String componentIdSeed) { diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedDataflowMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedDataflowMapper.java index 086a74c54d3c..eed2239b5295 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedDataflowMapper.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/serialization/VersionedDataflowMapper.java @@ -43,8 +43,6 @@ import org.apache.nifi.nar.ExtensionManager; import org.apache.nifi.parameter.ParameterContext; import org.apache.nifi.registry.flow.FlowRegistryClientNode; -import org.apache.nifi.registry.flow.mapping.ComponentIdLookup; -import org.apache.nifi.registry.flow.mapping.FlowMappingOptions; import org.apache.nifi.registry.flow.mapping.VersionedComponentFlowMapper; import org.apache.nifi.registry.flow.mapping.VersionedComponentStateLookup; import org.apache.nifi.security.encryption.PropertyEncryptionProvider; @@ -66,20 +64,7 @@ public VersionedDataflowMapper(final FlowController flowController, final Extens this.stateLookup = stateLookup; final VersionedComponentStateLookup versionedComponentStateLookup = createStateLookup(); - - final FlowMappingOptions mappingOptions = new FlowMappingOptions.Builder() - .mapSensitiveConfiguration(true) - .mapPropertyDescriptors(false) - .stateLookup(versionedComponentStateLookup) - .propertyEncryptionProvider(propertyEncryptionProvider) - .componentIdLookup(ComponentIdLookup.VERSIONED_OR_GENERATE) - .mapInstanceIdentifiers(true) - .mapControllerServiceReferencesToVersionedId(false) - .mapFlowRegistryClientId(true) - .mapAssetReferences(true) - .build(); - - flowMapper = new VersionedComponentFlowMapper(extensionManager, mappingOptions); + flowMapper = VersionedComponentFlowMapper.forPersistedFlow(extensionManager, propertyEncryptionProvider, versionedComponentStateLookup); } public VersionedDataflow createMapping() { diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java new file mode 100644 index 000000000000..29769019b36d --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java @@ -0,0 +1,110 @@ +/* + * 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.components.ConfigVerificationResult; +import org.apache.nifi.components.connector.components.FlowContext; +import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedProcessGroup; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Connector that counts its flow evolution hook, update preparation, apply and start calls. The hook can return a future + * that never completes, and start can fail a given number of times. + */ +public class FlowEvolutionHookConnector extends AbstractConnector { + + volatile FlowEvolutionContext context; + volatile Bundle preUpgradeBundle; + volatile int hookCalls; + volatile int prepareCalls; + volatile int applyCalls; + volatile boolean leaveFutureIncomplete; + volatile CompletableFuture evolutionFuture; + volatile int remainingStartFailures; + final AtomicInteger startCalls = new AtomicInteger(); + final CountDownLatch hookEntered = new CountDownLatch(1); + final CountDownLatch evolutionFuturePublished = new CountDownLatch(1); + + @Override + public VersionedExternalFlow getInitialFlow() { + return null; + } + + @Override + public VersionedExternalFlow getActiveFlow(final FlowContext flowContext) { + final VersionedExternalFlow flow = new VersionedExternalFlow(); + flow.setFlowContents(new VersionedProcessGroup()); + return flow; + } + + @Override + public void prepareForUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException { + prepareCalls++; + } + + @Override + public List getConfigurationSteps() { + return List.of(); + } + + @Override + public void applyUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException { + applyCalls++; + } + + @Override + public void start(final FlowContext activeContext) throws FlowUpdateException { + startCalls.incrementAndGet(); + if (remainingStartFailures > 0) { + remainingStartFailures--; + throw new FlowUpdateException("Intentional start failure"); + } + } + + @Override + protected void onStepConfigured(final String stepName, final FlowContext workingContext) { + } + + @Override + public List verifyConfigurationStep(final String stepName, final Map overrides, final FlowContext flowContext) { + return List.of(); + } + + @Override + public CompletableFuture prepareForFlowEvolution(final FlowEvolutionContext evolutionContext) throws FlowUpdateException { + context = evolutionContext; + preUpgradeBundle = evolutionContext.getPreUpgradeActiveFlowContext().getBundle(); + hookCalls++; + hookEntered.countDown(); + + if (leaveFutureIncomplete) { + evolutionFuture = new CompletableFuture<>(); + } else { + evolutionFuture = CompletableFuture.completedFuture(null); + } + evolutionFuturePublished.countDown(); + return evolutionFuture; + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java index cc3e1315aa59..de59c2ce6048 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java @@ -82,6 +82,7 @@ import org.apache.nifi.python.PythonBridge; import org.apache.nifi.reporting.BulletinRepository; import org.apache.nifi.scheduling.SchedulingStrategy; +import org.apache.nifi.security.encryption.InternalPassThroughPropertyEncryptionProvider; import org.apache.nifi.util.NiFiProperties; import org.apache.nifi.validation.RuleViolationsManager; import org.junit.jupiter.api.AfterEach; @@ -173,6 +174,7 @@ public void setup() { when(flowController.getConnectorRepository()).thenReturn(connectorRepository); when(flowController.getValidationTrigger()).thenReturn(mock(ValidationTrigger.class)); when(flowController.getConnectorValidationTrigger()).thenReturn(mock(ConnectorValidationTrigger.class)); + when(flowController.getPropertyEncryptionProvider()).thenReturn(new InternalPassThroughPropertyEncryptionProvider()); doAnswer(invocation -> { return createConnection(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2), invocation.getArgument(3), invocation.getArgument(4)); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java new file mode 100644 index 000000000000..eed7f03b62f1 --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java @@ -0,0 +1,171 @@ +/* + * 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.components.connector.components.ParameterValue; +import org.apache.nifi.components.connector.secrets.SecretsManager; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.parameter.Parameter; +import org.apache.nifi.parameter.ParameterContext; +import org.apache.nifi.parameter.ParameterDescriptor; +import org.apache.nifi.parameter.StandardParameterValueMapper; +import org.apache.nifi.security.encryption.InternalPassThroughPropertyEncryptionProvider; +import org.apache.nifi.security.encryption.PropertyEncryptionProvider; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class TestParameterSecretReferences { + private static final String PARAMETER_CONTEXT_NAME = "Managed Parameters"; + + private static final PropertyEncryptionProvider PROPERTY_ENCRYPTION_PROVIDER = new InternalPassThroughPropertyEncryptionProvider(); + + @Test + void testMatchSensitiveParametersToUniqueSecretReferences() { + final SecretReference firstReference = new SecretReference("provider-1", "Provider 1", "first", "Provider 1.group.first"); + final SecretReference secondReference = new SecretReference("provider-2", "Provider 2", "second", "Provider 2.group.second"); + final Secret firstSecret = secret("shared"); + final Secret secondSecret = secret("shared"); + final ParameterContext parameterContext = parameterContext( + parameter("Bound One", "unique", true), + parameter("Bound Two", "unique", true), + parameter("Ambiguous", "shared", true), + parameter("Plain", "unique", false), + parameter("Empty", "", true), + assetParameter("Asset")); + + final Map matched = ParameterSecretReferences.matchSensitiveParametersToSecretReferences(parameterContext, + Map.of(firstReference, secret("unique"), secondReference, secret("other"))); + assertEquals(Map.of("Bound One", firstReference, "Bound Two", firstReference), matched); + + final Map ambiguous = ParameterSecretReferences.matchSensitiveParametersToSecretReferences(parameterContext, + Map.of(firstReference, firstSecret, secondReference, secondSecret)); + assertFalse(ambiguous.containsKey("Ambiguous")); + } + + @Test + void testResolveDecryptsPersistedValuesAndTakesCurrentSecrets() { + final SecretReference resolvedReference = new SecretReference("provider", "Provider", "resolved", "Provider.group.resolved"); + final SecretReference missingReference = new SecretReference("provider", "Provider", "missing", "Provider.group.missing"); + final SecretReference nullableReference = new SecretReference(null, "Provider", "nullable", null); + final VersionedParameterContext persisted = versionedContext( + versionedParameter("Resolved", encrypt("Resolved", "old"), true), + versionedParameter("Missing", encrypt("Missing", "old"), true), + versionedParameter("Generated", encrypt("Generated", "Bearer generated"), true), + versionedParameter("Undecryptable", "enc{not-hexadecimal}", true), + versionedParameter("Nullable", encrypt("Nullable", "old"), true), + versionedParameter("Plain", "plain", false)); + final SecretsManager secretsManager = mock(SecretsManager.class); + final Secret currentSecret = secret("current"); + final Secret nullableSecret = secret("nullable"); + when(secretsManager.getSecrets(anySet(), eq(false))).thenReturn(Map.of(resolvedReference, currentSecret, nullableReference, nullableSecret)); + + final ParameterSecretReferences.Resolution resolution = ParameterSecretReferences.resolve(persisted, + Map.of("Resolved", resolvedReference, "Missing", missingReference, "Nullable", nullableReference), secretsManager, PROPERTY_ENCRYPTION_PROVIDER); + + assertEquals("current", getParameter(resolution.parameterContext(), "Resolved").getValue()); + assertNull(getParameter(resolution.parameterContext(), "Missing").getValue()); + assertEquals("Bearer generated", getParameter(resolution.parameterContext(), "Generated").getValue()); + assertNull(getParameter(resolution.parameterContext(), "Undecryptable").getValue()); + assertEquals("nullable", getParameter(resolution.parameterContext(), "Nullable").getValue()); + assertEquals("plain", getParameter(resolution.parameterContext(), "Plain").getValue()); + assertEquals(Map.of("Missing", missingReference), resolution.unresolvedReferences()); + assertEquals(Set.of("Undecryptable"), resolution.undecryptableParameters()); + assertEquals(Set.of("Resolved", "Nullable"), resolution.parameterValues().stream().map(ParameterValue::getName).collect(Collectors.toSet())); + assertEquals(encrypt("Generated", "Bearer generated"), getParameter(persisted, "Generated").getValue()); + } + + private static String encrypt(final String parameterName, final String value) { + final Parameter parameter = parameter(parameterName, value, true); + return new StandardParameterValueMapper(PROPERTY_ENCRYPTION_PROVIDER).getMapped(PARAMETER_CONTEXT_NAME, parameter, value); + } + + private static ParameterContext parameterContext(final Parameter... parameters) { + final ParameterContext parameterContext = mock(ParameterContext.class); + final Map parameterMap = new HashMap<>(); + for (final Parameter parameter : parameters) { + parameterMap.put(parameter.getDescriptor(), parameter); + } + when(parameterContext.getParameters()).thenReturn(parameterMap); + return parameterContext; + } + + private static Parameter parameter(final String name, final String value, final boolean sensitive) { + return new Parameter.Builder() + .name(name) + .value(value) + .sensitive(sensitive) + .build(); + } + + private static Parameter assetParameter(final String name) { + final Asset asset = mock(Asset.class); + when(asset.getIdentifier()).thenReturn("asset-id"); + when(asset.getName()).thenReturn("asset"); + when(asset.getFile()).thenReturn(new File("target/asset")); + return new Parameter.Builder() + .name(name) + .sensitive(true) + .referencedAssets(List.of(asset)) + .build(); + } + + private static VersionedParameterContext versionedContext(final VersionedParameter... parameters) { + final VersionedParameterContext context = new VersionedParameterContext(); + context.setIdentifier("context-id"); + context.setName(PARAMETER_CONTEXT_NAME); + context.setParameters(Set.of(parameters)); + return context; + } + + private static VersionedParameter versionedParameter(final String name, final String value, final boolean sensitive) { + final VersionedParameter parameter = new VersionedParameter(); + parameter.setName(name); + parameter.setValue(value); + parameter.setSensitive(sensitive); + return parameter; + } + + private static VersionedParameter getParameter(final VersionedParameterContext context, final String name) { + return context.getParameters().stream() + .filter(parameter -> name.equals(parameter.getName())) + .findFirst() + .orElseThrow(); + } + + private static Secret secret(final String value) { + final Secret secret = mock(Secret.class); + when(secret.getValue()).thenReturn(value); + return secret; + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java index c1dff2faebc5..6409d2856064 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java @@ -23,6 +23,10 @@ import org.apache.nifi.components.ValidationResult; import org.apache.nifi.components.connector.components.FlowContext; import org.apache.nifi.components.connector.components.FlowContextType; +import org.apache.nifi.components.connector.components.ParameterContextFacade; +import org.apache.nifi.components.connector.components.ParameterValue; +import org.apache.nifi.components.connector.components.ProcessGroupFacade; +import org.apache.nifi.components.connector.components.ProcessGroupLifecycle; import org.apache.nifi.components.connector.secrets.SecretsManager; import org.apache.nifi.components.state.Scope; import org.apache.nifi.components.state.StateManager; @@ -30,26 +34,39 @@ import org.apache.nifi.components.state.StateMap; import org.apache.nifi.components.validation.ValidationState; import org.apache.nifi.components.validation.ValidationStatus; +import org.apache.nifi.connectable.Position; import org.apache.nifi.controller.MockStateManagerProvider; import org.apache.nifi.controller.ProcessorNode; import org.apache.nifi.controller.flow.FlowManager; import org.apache.nifi.controller.queue.QueueSize; +import org.apache.nifi.controller.service.ControllerServiceProvider; import org.apache.nifi.controller.state.StandardStateMap; import org.apache.nifi.engine.FlowEngine; import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.ExecutionEngine; import org.apache.nifi.flow.VersionedConfigurationStep; +import org.apache.nifi.flow.VersionedConnector; import org.apache.nifi.flow.VersionedConnectorValueReference; import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.groups.FlowFileConcurrency; +import org.apache.nifi.groups.FlowFileOutboundPolicy; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.migration.ConnectorPropertyConfiguration; import org.apache.nifi.nar.ExtensionManager; import org.apache.nifi.nar.InstanceClassLoader; +import org.apache.nifi.parameter.Parameter; +import org.apache.nifi.parameter.StandardParameterValueMapper; +import org.apache.nifi.security.encryption.InternalPassThroughPropertyEncryptionProvider; import org.apache.nifi.util.MockComponentLog; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -64,12 +81,14 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.RunnableScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; @@ -78,6 +97,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; @@ -90,6 +110,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -107,6 +128,7 @@ public class TestStandardConnectorNode { private static final String SECOND_SECRET_VALUE = "second"; private FlowEngine scheduler; + private ExecutorService flowEvolutionExecutor; @Mock private ExtensionManager extensionManager; @@ -116,6 +138,8 @@ public class TestStandardConnectorNode { private AssetManager assetManager; @Mock private SecretsManager secretsManager; + @Mock + private ParameterContextFacade parameterContextFacade; private FlowContextFactory flowContextFactory; private StateManagerProvider stateManagerProvider; @@ -126,12 +150,28 @@ public void setUp() { MockitoAnnotations.openMocks(this); // Multiple Threads configured to support concurrent lifecycle operations scheduler = new FlowEngine(2, "flow-engine"); + flowEvolutionExecutor = Executors.newVirtualThreadPerTaskExecutor(); stateManagerProvider = new MockStateManagerProvider(); when(managedProcessGroup.purge()).thenReturn(CompletableFuture.completedFuture(null)); when(managedProcessGroup.getQueueSize()).thenReturn(new QueueSize(0, 0L)); + when(managedProcessGroup.getIdentifier()).thenReturn("managed-group"); + when(managedProcessGroup.getProcessGroupIdentifier()).thenReturn("managed-group"); + when(managedProcessGroup.getVersionedComponentId()).thenReturn(Optional.of("managed-group-versioned")); + when(managedProcessGroup.getName()).thenReturn("Managed Group"); + when(managedProcessGroup.getPosition()).thenReturn(new Position(0, 0)); + when(managedProcessGroup.getFlowFileConcurrency()).thenReturn(FlowFileConcurrency.UNBOUNDED); + when(managedProcessGroup.getFlowFileOutboundPolicy()).thenReturn(FlowFileOutboundPolicy.STREAM_WHEN_AVAILABLE); + when(managedProcessGroup.getExecutionEngine()).thenReturn(ExecutionEngine.INHERITED); when(managedProcessGroup.findAllProcessors()).thenReturn(List.of()); when(managedProcessGroup.findAllControllerServices()).thenReturn(Set.of()); + when(managedProcessGroup.getProcessors()).thenReturn(Set.of()); + when(managedProcessGroup.getProcessGroups()).thenReturn(Set.of()); + when(managedProcessGroup.getInputPorts()).thenReturn(Set.of()); + when(managedProcessGroup.getOutputPorts()).thenReturn(Set.of()); + when(managedProcessGroup.getRemoteProcessGroups()).thenReturn(Set.of()); + when(managedProcessGroup.getControllerServices(false)).thenReturn(Set.of()); + when(managedProcessGroup.getConnections()).thenReturn(Set.of()); flowContextFactory = new FlowContextFactory() { @Override @@ -139,6 +179,12 @@ public FrameworkFlowContext createActiveFlowContext(final String connectorId, fi final MutableConnectorConfigurationContext activeConfigurationContext = new StandardConnectorConfigurationContext(assetManager, secretsManager); final ProcessGroupFacadeFactory processGroupFacadeFactory = mock(ProcessGroupFacadeFactory.class); final ParameterContextFacadeFactory parameterContextFacadeFactory = mock(ParameterContextFacadeFactory.class); + when(parameterContextFacadeFactory.create(managedProcessGroup)).thenReturn(parameterContextFacade); + final ProcessGroupLifecycle lifecycle = mock(ProcessGroupLifecycle.class); + when(lifecycle.stop()).thenReturn(CompletableFuture.completedFuture(null)); + final ProcessGroupFacade rootGroup = mock(ProcessGroupFacade.class); + when(rootGroup.getLifecycle()).thenReturn(lifecycle); + when(processGroupFacadeFactory.create(managedProcessGroup, connectorLogger)).thenReturn(rootGroup); return new StandardFlowContext(managedProcessGroup, activeConfigurationContext, processGroupFacadeFactory, parameterContextFacadeFactory, connectorLogger, FlowContextType.ACTIVE, bundle); } @@ -157,7 +203,7 @@ public FrameworkFlowContext createWorkingFlowContext(final String connectorId, f } @AfterEach - public void teardown() { + public void teardown() throws Exception { if (startBlockingConnector != null) { startBlockingConnector.releaseStart(); } @@ -165,6 +211,9 @@ public void teardown() { if (scheduler != null) { scheduler.close(); } + if (flowEvolutionExecutor != null) { + flowEvolutionExecutor.close(); + } } @Test @@ -486,6 +535,58 @@ public void testStartWhileStopIsPendingForInFlightStartLeavesConnectorRunning() assertEquals(ConnectorState.RUNNING, connectorNode.getDesiredState()); } + @Test + @Timeout(value = 10, unit = TimeUnit.SECONDS) + public void testFailedStartSupersededByStopCompletesStartFutureExceptionally() throws Exception { + final StartBlockingConnector connector = createStartBlockingConnector(); + connector.failStart(); + final StandardConnectorNode connectorNode = createConnectorNode(connector); + + final Future startFuture = connectorNode.start(scheduler); + assertTrue(connector.awaitStartEntered(5, TimeUnit.SECONDS)); + final Future stopFuture = connectorNode.stop(scheduler); + connector.releaseStart(); + + stopFuture.get(5, TimeUnit.SECONDS); + final ExecutionException exception = assertThrows(ExecutionException.class, () -> startFuture.get(5, TimeUnit.SECONDS)); + assertInstanceOf(IllegalStateException.class, exception.getCause()); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + } + + @Test + @Timeout(value = 10, unit = TimeUnit.SECONDS) + public void testStaleStartRetryDoesNotStartConnectorAgain() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + connector.remainingStartFailures = 1; + final StandardConnectorNode connectorNode = createConnectorNode(connector); + + final Future failedStart = connectorNode.start(scheduler); + final RunnableScheduledFuture retry = awaitDelayedTask(); + connectorNode.stop(scheduler).get(5, TimeUnit.SECONDS); + connectorNode.start(scheduler).get(5, TimeUnit.SECONDS); + assertEquals(ConnectorState.RUNNING, connectorNode.getCurrentState()); + + // Run the retry of the failed start now instead of waiting for its delay to elapse + assertTrue(scheduler.remove(retry)); + retry.run(); + + failedStart.get(5, TimeUnit.SECONDS); + assertEquals(2, connector.startCalls.get()); + assertEquals(ConnectorState.RUNNING, connectorNode.getCurrentState()); + } + + private RunnableScheduledFuture awaitDelayedTask() throws InterruptedException { + while (true) { + for (final Runnable task : scheduler.getQueue()) { + if (task instanceof final RunnableScheduledFuture scheduledTask && scheduledTask.getDelay(TimeUnit.SECONDS) > 1) { + return scheduledTask; + } + } + + Thread.sleep(10L); + } + } + @Test public void testCannotDeleteWhenStarting() throws Exception { // Use a slow-starting connector to test deletion during STARTING state @@ -889,14 +990,31 @@ public void testReplaceConnectorMigratesConfigurationUsingReplacement() throws F @Test public void testReplaceConnectorWithGhostMarksExtensionMissing() throws FlowUpdateException { final StandardConnectorNode connectorNode = createConnectorNode(new TrackingConnector()); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("outgoing"), null, Map.of(), new Bundle("org.apache.nifi", "test-standard-connector-node", "1.0.0")); final GhostConnector ghostConnector = new GhostConnector(connectorNode.getIdentifier(), connectorNode.getCanonicalClassName(), new Exception("Instantiation failed")); - final BundleCoordinate replacementCoordinate = new BundleCoordinate("org.apache.nifi", "test-standard-connector-node", "2.0.0"); - - connectorNode.replaceConnector(ghostConnector, replacementCoordinate, new MockComponentLog("GhostConnector", ghostConnector)); + replaceConnector(connectorNode, ghostConnector, "2.0.0"); assertSame(ghostConnector, connectorNode.getConnector()); assertTrue(connectorNode.isExtensionMissing()); assertEquals("(Missing) TrackingConnector", connectorNode.getComponentType()); + + final ConnectorAction startWhileGhosted = findAction(connectorNode, "START"); + assertFalse(startWhileGhosted.isAllowed()); + assertTrue(startWhileGhosted.getReasonNotAllowed().contains("extension is missing"), startWhileGhosted.getReasonNotAllowed()); + final IllegalStateException ghostStartFailure = assertThrows(IllegalStateException.class, connectorNode::verifyCanStart); + assertTrue(ghostStartFailure.getMessage().contains("extension is missing"), ghostStartFailure.getMessage()); + + connectorNode.markManagedFlowRestoreFailed(); + replaceConnector(connectorNode, new TrackingConnector(), "2.0.0"); + connectorNode.performValidation(); + + assertFalse(connectorNode.isExtensionMissing()); + assertTrue(connectorNode.isManagedFlowRestoreFailed()); + final ConnectorAction start = findAction(connectorNode, "START"); + assertFalse(start.isAllowed()); + assertTrue(start.getReasonNotAllowed().contains("restart NiFi"), start.getReasonNotAllowed()); + final IllegalStateException failure = assertThrows(IllegalStateException.class, connectorNode::verifyCanStart); + assertTrue(failure.getMessage().contains("restart NiFi"), failure.getMessage()); } @Test @@ -905,6 +1023,8 @@ public void testReplaceConnectorRestoresConfigurationWhenCallbackFails() throws final StandardConnectorNode connectorNode = createConnectorNode(original); seedActiveConfiguration(connectorNode, "active-step", Map.of("active-property", new StringLiteralValue("active-value"))); connectorNode.setConfiguration("step", createStepConfiguration()); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("outgoing"), null, Map.of(), new Bundle("org.apache.nifi", "test-standard-connector-node", "1.0.0")); + final ConnectorFlowSnapshot originalSnapshot = connectorNode.getAuthoritativeFlowSnapshot(); final FrameworkFlowContext originalWorkingFlowContext = connectorNode.getWorkingFlowContext(); final FailingStepConnector replacement = new FailingStepConnector("step") { @Override @@ -923,6 +1043,9 @@ public void migrateProperties(final ConnectorPropertyConfiguration configuration assertEquals("active-value", connectorNode.getActiveFlowContext().getConfigurationContext().getProperty("active-step", "active-property").getValue()); assertEquals("testValue", connectorNode.getWorkingFlowContext().getConfigurationContext().getProperty("step", "testProperty").getValue()); assertEquals("1.0.0", connectorNode.getWorkingFlowContext().getBundle().getVersion()); + assertSame(originalSnapshot, connectorNode.getAuthoritativeFlowSnapshot()); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertEquals("1.0.0", connectorNode.getBundleCoordinate().getVersion()); } @Test @@ -1033,6 +1156,19 @@ public void migrateProperties(final ConnectorPropertyConfiguration configuration assertEquals("working-value", connectorNode.getWorkingFlowContext().getConfigurationContext().getProperty("working-step", "property").getValue()); } + + private void replaceConnector(final StandardConnectorNode connectorNode, final Connector replacement, final String version) throws FlowUpdateException { + final BundleCoordinate replacementCoordinate = new BundleCoordinate("org.apache.nifi", "test-standard-connector-node", version); + connectorNode.replaceConnector(replacement, replacementCoordinate, new MockComponentLog("ReplacementConnector", replacement)); + } + + private static ConnectorAction findAction(final StandardConnectorNode connectorNode, final String actionName) { + return connectorNode.getAvailableActions().stream() + .filter(action -> actionName.equals(action.getName())) + .findFirst() + .orElseThrow(); + } + @Test @Timeout(10) public void testRecreationRefreshDoesNotOverwriteConcurrentReplace() throws Exception { @@ -2039,6 +2175,302 @@ public void testInheritingConfigurationKeepsTransitivelyGatedRequiredPropertyIrr connectorNode.verifyCanStart(); } + + @Test + public void testEvolveFlowReturnsSameTaskWhileHookIsPending() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + connector.leaveFutureIncomplete = true; + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + + connectorNode.prepareFlowEvolution(); + final Future evolution = connectorNode.evolveFlow(flowEvolutionExecutor); + assertTrue(connector.evolutionFuturePublished.await(5, TimeUnit.SECONDS)); + + assertSame(evolution, connectorNode.evolveFlow(flowEvolutionExecutor)); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); + // The hook stays blocked, so the task has to be interrupted before the executor is closed. + evolution.cancel(true); + } + + @Test + public void testAbortUpdateInterruptsBlockedFlowEvolutionHook() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + connector.leaveFutureIncomplete = true; + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + + connectorNode.prepareFlowEvolution(); + final Future evolution = connectorNode.evolveFlow(flowEvolutionExecutor); + assertTrue(connector.hookEntered.await(5, TimeUnit.SECONDS)); + assertTrue(connector.evolutionFuturePublished.await(5, TimeUnit.SECONDS)); + + connectorNode.abortUpdate(new FlowUpdateException("cancel")); + assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); + assertThrows(CancellationException.class, () -> evolution.get(2, TimeUnit.SECONDS)); + // When the abort lands before the evolve-drain task records the hook future, the task cancels it after abortUpdate returns + assertThrows(CancellationException.class, () -> connector.evolutionFuture.get(5, TimeUnit.SECONDS)); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertEvolutionContextClosed(connector.context); + } + + @Test + public void testBeginEvolvedFlowUpdateWithQueuedFlowFilesInRemovedConnection() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + connectorNode.prepareFlowEvolution(); + connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS); + assertEquals(outgoingSnapshotBundle().getVersion(), connector.preUpgradeBundle.getVersion()); + + doThrow(new IllegalStateException("Connection queue-1 has queued FlowFiles")) + .when(managedProcessGroup).verifyCanUpdate(any(VersionedExternalFlow.class), eq(true), eq(false)); + + final FlowUpdateException failure = assertThrows(FlowUpdateException.class, connectorNode::beginEvolvedFlowUpdate); + assertTrue(failure.getMessage().contains("queue-1"), failure.getMessage()); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertEquals(outgoingSnapshotBundle().getVersion(), connectorNode.getAuthoritativeFlowSnapshot().bundle().getVersion()); + assertEquals(0, connector.applyCalls); + } + + @Test + public void testBeginEvolvedFlowUpdateRequiresCompletedEvolveDrain() throws Exception { + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + assertThrows(FlowUpdateException.class, connectorNode::beginEvolvedFlowUpdate); + + connectorNode.prepareFlowEvolution(); + assertThrows(FlowUpdateException.class, connectorNode::beginEvolvedFlowUpdate); + assertEquals(ConnectorState.DRAINING, connectorNode.getCurrentState()); + } + + @Test + public void testStaleEvolutionTaskReleasedDuringNextEvolution() throws Exception { + final GatedActiveFlowConnector connector = new GatedActiveFlowConnector(); + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + connectorNode.prepareFlowEvolution(); + final Future evolution = connectorNode.evolveFlow(flowEvolutionExecutor); + assertTrue(connector.reachedActiveFlow.await(5, TimeUnit.SECONDS)); + + connectorNode.abortUpdate(new FlowUpdateException("cancel")); + connectorNode.prepareFlowEvolution(); + connector.releaseActiveFlow.countDown(); + + assertThrows(CancellationException.class, () -> evolution.get(5, TimeUnit.SECONDS)); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); + assertEquals(ConnectorState.DRAINING, connectorNode.getCurrentState()); + assertTrue(connectorNode.getValidationErrors().stream().noneMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()))); + } + + @Test + public void testRevalidationAndRetryAfterFlowEvolutionFailure() throws Exception { + final ConnectorValidationTrigger validationTrigger = mock(ConnectorValidationTrigger.class); + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector(), validationTrigger); + connectorNode.markInvalid("Existing Failure", "existing failure"); + + connectorNode.failFlowEvolution("first evolution failure", null); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertEquals(2, connectorNode.getValidationErrors().size()); + assertEquals(1, connectorNode.getValidationErrors().stream() + .filter(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject())) + .count()); + + connectorNode.performValidation(); + assertEquals(1, connectorNode.getValidationErrors().stream() + .filter(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject())) + .count()); + connectorNode.resetValidationState(); + assertEquals(1, connectorNode.getValidationErrors().stream() + .filter(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject())) + .count()); + + connectorNode.markInvalid("Replacement Failure", "replacement failure"); + connectorNode.failFlowEvolution("duplicate evolution failure", null); + assertEquals(2, connectorNode.getValidationErrors().size()); + final ValidationResult evolutionFailure = connectorNode.getValidationErrors().stream() + .filter(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject())) + .findFirst() + .orElseThrow(); + assertEquals("first evolution failure", evolutionFailure.getExplanation()); + assertEquals(1, ((MockComponentLog) connectorNode.getComponentLog()).getErrorMessages().stream() + .filter(message -> message.getMsg().contains("Flow evolution failed")) + .count()); + + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + connectorNode.prepareFlowEvolution(); + + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); + assertTrue(connectorNode.getValidationErrors().stream() + .noneMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()))); + assertTrue(connectorNode.getValidationErrors().stream() + .anyMatch(result -> "Replacement Failure".equals(result.getSubject()))); + } + + @Test + public void testFlowEvolutionFailureWhenPreUpgradeFlowDoesNotStop() throws Exception { + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); + final ProcessGroupLifecycle lifecycle = connectorNode.getActiveFlowContext().getRootGroup().getLifecycle(); + when(lifecycle.stop()) + .thenReturn(CompletableFuture.failedFuture(new TimeoutException("still running"))) + .thenReturn(CompletableFuture.completedFuture(null)); + + connectorNode.failFlowEvolution("hook started processors that would not stop", null); + + assertEquals(ConnectorState.STOPPING, connectorNode.getCurrentState()); + assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertTrue(connectorNode.getValidationErrors().stream() + .anyMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()))); + + connectorNode.retryPreUpgradeStop(scheduler); + + final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (connectorNode.getCurrentState() != ConnectorState.STOPPED && System.nanoTime() < deadline) { + Thread.sleep(50); + } + + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); + } + + @Test + public void testStartWhilePreUpgradeFlowIsStopping() throws Exception { + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); + final ProcessGroupLifecycle lifecycle = connectorNode.getActiveFlowContext().getRootGroup().getLifecycle(); + when(lifecycle.stop()) + .thenReturn(CompletableFuture.failedFuture(new TimeoutException("still running"))) + .thenReturn(CompletableFuture.completedFuture(null)); + + connectorNode.failFlowEvolution("hook started processors that would not stop", null); + assertEquals(ConnectorState.STOPPING, connectorNode.getCurrentState()); + + final Future startFuture = connectorNode.start(scheduler); + connectorNode.retryPreUpgradeStop(scheduler); + startFuture.get(5, TimeUnit.SECONDS); + + assertEquals(ConnectorState.RUNNING, connectorNode.getCurrentState()); + } + + @Test + public void testEvolveFlowRejectsMissingManagedComponents() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + final ProcessorNode missingProcessor = mock(ProcessorNode.class); + when(missingProcessor.isExtensionMissing()).thenReturn(true); + when(missingProcessor.getCanonicalClassName()).thenReturn("org.example.MissingProcessor"); + when(missingProcessor.getBundleCoordinate()).thenReturn(new BundleCoordinate("org.example", "missing-processor", "1.0.0")); + when(managedProcessGroup.findAllProcessors()).thenReturn(List.of(missingProcessor)); + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + + connectorNode.prepareFlowEvolution(); + final ExecutionException processorFailure = assertThrows(ExecutionException.class, + () -> connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS)); + assertTrue(processorFailure.getCause().getMessage().contains("MissingProcessor"), processorFailure.getCause().getMessage()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertEquals(0, connector.hookCalls); + } + + @Test + public void testFlowEvolutionWithMissingSecretThenRestoredSecret() throws Exception { + final SecretReference secretReference = new SecretReference("provider-id", "Provider", "password", "Provider.group.password"); + final AtomicReference currentSecret = new AtomicReference<>(); + when(secretsManager.getSecrets(anySet(), eq(false))).thenAnswer(invocation -> { + final Secret secret = currentSecret.get(); + return secret == null ? Map.of() : Map.of(secretReference, secret); + }); + + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector(), secretsManager); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), + persistedParameterContext("Source Database Password"), Map.of("Source Database Password", secretReference), + outgoingSnapshotBundle()); + + connectorNode.prepareFlowEvolution(); + final ExecutionException failure = assertThrows(ExecutionException.class, + () -> connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS)); + assertTrue(failure.getCause().getMessage().contains("Provider.group.password"), failure.getCause().getMessage()); + assertTrue(failure.getCause().getMessage().contains("Source Database Password"), failure.getCause().getMessage()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + + final Secret restoredSecret = mock(Secret.class); + when(restoredSecret.getValue()).thenReturn("current-password"); + currentSecret.set(restoredSecret); + connectorNode.prepareFlowEvolution(); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); + assertTrue(connectorNode.getValidationErrors().stream() + .noneMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()))); + connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS); + + final ArgumentCaptor> valuesCaptor = ArgumentCaptor.forClass(Collection.class); + verify(parameterContextFacade).updateParameters(valuesCaptor.capture()); + assertEquals("current-password", valuesCaptor.getValue().iterator().next().getValue()); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE, connectorNode.getReportedFlowEvolutionStatus()); + } + + @Test + public void testRestorePersistedFlowKeepsComponentsStoppedWhenSecretMissing() throws Exception { + final SecretReference secretReference = new SecretReference("provider-id", "Provider", "password", "Provider.group.password"); + when(secretsManager.getSecrets(anySet(), eq(false))).thenReturn(Map.of()); + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector(), secretsManager); + clearInvocations(managedProcessGroup); + + connectorNode.restorePersistedFlow(flowGroup("pre-upgrade"), + persistedParameterContext("Source Database Password"), Map.of("Source Database Password", secretReference), true); + + verify(managedProcessGroup).restoreFlowPreservingIdentifiers(any(VersionedExternalFlow.class), eq(false)); + } + + @Test + public void testRestorePendingFlowEvolutionRestoresDerivedSensitiveParameter() throws Exception { + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); + clearInvocations(parameterContextFacade); + final String connectionUrl = "jdbc:postgresql://database:5432/source?password=derived"; + final VersionedParameterContext parameterContext = persistedParameterContext("Connection URL"); + final VersionedParameter parameter = parameterContext.getParameters().iterator().next(); + parameter.setValue(new StandardParameterValueMapper(new InternalPassThroughPropertyEncryptionProvider()) + .getMapped(parameterContext.getName(), new Parameter.Builder().name("Connection URL").value(connectionUrl).sensitive(true).build(), connectionUrl)); + final VersionedConnector persisted = new VersionedConnector(); + persisted.setManagedProcessGroup(flowGroup("pre-upgrade")); + persisted.setManagedParameterContext(parameterContext); + persisted.setManagedFlowBundle(outgoingSnapshotBundle()); + + assertTrue(connectorNode.restorePendingFlowEvolution(persisted, List.of(), List.of())); + + final ArgumentCaptor> valuesCaptor = ArgumentCaptor.forClass(Collection.class); + verify(parameterContextFacade).updateParameters(valuesCaptor.capture()); + assertEquals(connectionUrl, valuesCaptor.getValue().iterator().next().getValue()); + assertTrue(connectorNode.isPendingFlowEvolution()); + } + + private static VersionedProcessGroup flowGroup(final String name) { + final VersionedProcessGroup group = new VersionedProcessGroup(); + group.setName(name); + group.setIdentifier(name); + return group; + } + + private static Bundle outgoingSnapshotBundle() { + return new Bundle("org.apache.nifi", "test-standard-connector-node", "0.9.0"); + } + + private static VersionedParameterContext persistedParameterContext(final String parameterName) { + final VersionedParameter parameter = new VersionedParameter(); + parameter.setName(parameterName); + parameter.setSensitive(true); + parameter.setValue("persisted-value"); + final VersionedParameterContext context = new VersionedParameterContext(); + context.setIdentifier("managed-parameters"); + context.setName("Managed Parameters"); + context.setParameters(Set.of(parameter)); + return context; + } + private static Bundle createConnectorBundle() { final Bundle bundle = new Bundle(); bundle.setGroup("org.apache.nifi"); @@ -2124,6 +2556,14 @@ private StandardConnectorNode createConnectorNode(final Connector connector) thr return createConnectorNode(connector, defaultSecretsManager); } + private StandardConnectorNode createConnectorNode(final Connector connector, final ConnectorValidationTrigger validationTrigger) throws FlowUpdateException { + final SecretsManager defaultSecretsManager = mock(SecretsManager.class); + when(defaultSecretsManager.getAllSecrets()).thenReturn(List.of()); + when(defaultSecretsManager.getSecrets(anySet())).thenReturn(Collections.emptyMap()); + when(defaultSecretsManager.getSecrets(anySet(), anyBoolean())).thenReturn(Collections.emptyMap()); + return createConnectorNode(connector, defaultSecretsManager, new StandardConnectorStateTransition("TestConnectorNode"), validationTrigger); + } + private StandardConnectorNode createConnectorNode(final Connector connector, final ConnectorStateTransition stateTransition) throws FlowUpdateException { final SecretsManager defaultSecretsManager = mock(SecretsManager.class); when(defaultSecretsManager.getAllSecrets()).thenReturn(List.of()); @@ -2138,10 +2578,17 @@ private StandardConnectorNode createConnectorNode(final Connector connector, fin private StandardConnectorNode createConnectorNode(final Connector connector, final SecretsManager initializedSecretsManager, final ConnectorStateTransition stateTransition) throws FlowUpdateException { - final ConnectorValidationTrigger validationTrigger = new SynchronousConnectorValidationTrigger(); + return createConnectorNode(connector, initializedSecretsManager, stateTransition, new SynchronousConnectorValidationTrigger()); + } + + private StandardConnectorNode createConnectorNode(final Connector connector, final SecretsManager initializedSecretsManager, + final ConnectorStateTransition stateTransition, final ConnectorValidationTrigger validationTrigger) throws FlowUpdateException { + final FlowManager flowManager = mock(FlowManager.class); + final ConnectorFlowSnapshotMapper snapshotMapper = new ConnectorFlowSnapshotMapper( + extensionManager, mock(ControllerServiceProvider.class), new InternalPassThroughPropertyEncryptionProvider()); final StandardConnectorNode node = new StandardConnectorNode( "test-connector-id", - mock(FlowManager.class), + flowManager, extensionManager, stateManagerProvider, null, @@ -2151,6 +2598,7 @@ private StandardConnectorNode createConnectorNode(final Connector connector, fin new StandardConnectorConfigurationContext(assetManager, secretsManager), stateTransition, flowContextFactory, + snapshotMapper, validationTrigger, false); @@ -3132,6 +3580,7 @@ private static class StartBlockingConnector extends AbstractConnector { private final CountDownLatch stopEnteredLatch = new CountDownLatch(1); private volatile boolean starting = false; private volatile boolean stoppedWhileStarting = false; + private volatile boolean failStart = false; @Override public VersionedExternalFlow getInitialFlow() { @@ -3180,6 +3629,10 @@ public void start(final FlowContext activeContext) throws FlowUpdateException { } finally { starting = false; } + + if (failStart) { + throw new FlowUpdateException("Intentional start failure"); + } } @Override @@ -3203,11 +3656,22 @@ public void releaseStart() { startReleaseLatch.countDown(); } + public void failStart() { + failStart = true; + } + public boolean wasStoppedWhileStarting() { return stoppedWhileStarting; } } + private static void assertEvolutionContextClosed(final FlowEvolutionContext context) { + final IllegalStateException preUpgradeFailure = assertThrows(IllegalStateException.class, context::getPreUpgradeActiveFlowContext); + assertTrue(preUpgradeFailure.getMessage().contains("can no longer be used")); + final IllegalStateException postUpgradeFailure = assertThrows(IllegalStateException.class, context::getPostUpgradeBundle); + assertTrue(postUpgradeFailure.getMessage().contains("can no longer be used")); + } + /** * Test connector that allows control over when drainFlowFiles completes via a CompletableFuture */ @@ -3351,4 +3815,23 @@ public boolean wasStopCalled() { } } + private static final class GatedActiveFlowConnector extends FlowEvolutionHookConnector { + final CountDownLatch reachedActiveFlow = new CountDownLatch(1); + final CountDownLatch releaseActiveFlow = new CountDownLatch(1); + + @Override + public VersionedExternalFlow getActiveFlow(final FlowContext flowContext) { + reachedActiveFlow.countDown(); + try { + if (!releaseActiveFlow.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to return the active flow"); + } + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting to return the active flow", e); + } + return super.getActiveFlow(flowContext); + } + } + } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java index 95cc423f641f..236dbf98c328 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java @@ -23,22 +23,33 @@ import org.apache.nifi.components.ConfigVerificationResult; import org.apache.nifi.components.connector.components.FlowContext; import org.apache.nifi.components.connector.components.FlowContextType; +import org.apache.nifi.components.connector.components.ProcessGroupFacade; +import org.apache.nifi.components.connector.components.ProcessGroupLifecycle; import org.apache.nifi.components.connector.secrets.SecretsManager; +import org.apache.nifi.connectable.Position; import org.apache.nifi.controller.MockStateManagerProvider; import org.apache.nifi.controller.ParameterProviderNode; import org.apache.nifi.controller.flow.FlowManager; import org.apache.nifi.controller.queue.QueueSize; +import org.apache.nifi.controller.service.ControllerServiceProvider; import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.ComponentType; +import org.apache.nifi.flow.ExecutionEngine; 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.flow.VersionedControllerService; import org.apache.nifi.flow.VersionedExternalFlow; import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.flow.VersionedProcessor; +import org.apache.nifi.groups.FlowFileConcurrency; +import org.apache.nifi.groups.FlowFileOutboundPolicy; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.migration.ConnectorPropertyConfiguration; import org.apache.nifi.nar.ExtensionManager; +import org.apache.nifi.security.encryption.InternalPassThroughPropertyEncryptionProvider; import org.apache.nifi.util.MockComponentLog; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -57,12 +68,16 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; @@ -87,6 +102,8 @@ public class TestStandardConnectorRepository { + private static final ConnectorUpdateContext NO_OP_PERSISTENCE = () -> { }; + @Test public void testAddAndGetConnectors() { final StandardConnectorRepository repository = new StandardConnectorRepository(); @@ -146,7 +163,7 @@ public void testRestoreConnectorDoesNotCleanUpAssetsBeforeSynchronization() { // At restore time the Connector's managed flow has not yet been synchronized: its Managed Process Group // and managed Parameter Context are empty, so its flow contexts reference no assets. Deleting assets here // would discard assets that the Connector's not-yet-restored flow still references. A Connector restored in - // Troubleshooting mode relies on these assets surviving until restoreTroubleshootingFlow re-establishes the + // Troubleshooting mode relies on these assets surviving until the persisted managed flow re-establishes the // references, so restoreConnector must not delete any assets. final Asset asset = mock(Asset.class); when(asset.getIdentifier()).thenReturn("asset-1"); @@ -550,6 +567,13 @@ public void testGetConnectorLocalOnlyDoesNotCallProvider() { assertNotNull(result); verifyNoInteractions(provider); verify(connector, never()).setName(anyString()); + + when(connector.getCurrentState()).thenReturn(ConnectorState.DRAINING); + reset(provider); + final ConnectorNode draining = repository.getConnector("connector-1", ConnectorSyncMode.SYNC_WITH_PROVIDER); + + assertNotNull(draining); + verifyNoInteractions(provider); } @Test @@ -1860,12 +1884,9 @@ public void testSyncConnectorTroubleshootingInheritsConfigurationThenOverlaysSna repository.restoreConnector(connector); final VersionedProcessGroup persistedManagedGroup = new VersionedProcessGroup(); - // The Connector's managed Parameter Context is not registered with the global ParameterContextManager and is - // therefore not persisted in flow.json. When restoring a Connector whose effective scheduled state is - // TROUBLESHOOTING, the framework must run inheritConfiguration so the Connector re-populates its in-memory - // Parameter Context from the persisted active configuration. The Connector-supplied flow shape that produces - // is then overlaid by restoreTroubleshootingFlow with the user's persisted snapshot before the FlowFile Repository - // attaches FlowFiles to queues, so the transient Connector flow shape is invisible to data movement. + // Troubleshooting rebuilds the managed Parameter Context from the active configuration and current secrets. + // Restoring the persisted flow must preserve those rebuilt values while overlaying the persisted managed group + // before the FlowFile Repository attaches FlowFiles to its queues. final List activeConfig = List.of( createVersionedStep("step1", Map.of("prop1", createStringLiteralRef("new-value")))); final VersionedConnector versioned = createVersionedConnector("connector-1", "Test Connector", @@ -1877,10 +1898,10 @@ public void testSyncConnectorTroubleshootingInheritsConfigurationThenOverlaysSna assertEquals(ConnectorSyncResult.Outcome.SYNCED_CONFIG_UNCHANGED, result.getOutcome()); assertEquals(VersionedConnectorState.TROUBLESHOOTING, result.getEffectiveScheduledState()); - final FrameworkFlowContext activeFlowContext = connector.getActiveFlowContext(); - final InOrder inOrder = inOrder(connector, activeFlowContext); + final InOrder inOrder = inOrder(connector); inOrder.verify(connector).inheritConfiguration(eq(activeConfig), eq(activeConfig), any()); - inOrder.verify(activeFlowContext).restoreTroubleshootingFlow(persistedManagedGroup); + inOrder.verify(connector).restoreTroubleshootingManagedFlow(versioned); + inOrder.verify(connector).ensureAuthoritativeFlowSnapshot(); inOrder.verify(connector).restoreTroubleshootingState(); } @@ -1901,7 +1922,7 @@ public void testSyncConnectorTroubleshootingPreservesExistingTroubleshootingStat assertEquals(ConnectorSyncResult.Outcome.SYNCED_CONFIG_UNCHANGED, result.getOutcome()); verify(connector).inheritConfiguration(eq(List.of()), eq(List.of()), any()); - verify(connector.getActiveFlowContext()).restoreTroubleshootingFlow(persistedManagedGroup); + verify(connector).restoreTroubleshootingManagedFlow(versioned); // Connector is already in TROUBLESHOOTING; restoreTroubleshootingState should not be invoked again. verify(connector, never()).restoreTroubleshootingState(); } @@ -1921,18 +1942,17 @@ public void testSyncConnectorTroubleshootingWithoutSnapshotLeavesManagedGroupUnc assertEquals(ConnectorSyncResult.Outcome.SYNCED_CONFIG_UNCHANGED, result.getOutcome()); verify(connector).inheritConfiguration(eq(List.of()), eq(List.of()), any()); - verify(connector.getActiveFlowContext(), never()).restoreTroubleshootingFlow(any()); + verify(connector).restoreTroubleshootingManagedFlow(versioned); verify(connector).restoreTroubleshootingState(); } @Test - public void testSyncConnectorTroubleshootingSnapshotRestoreFailureMarksInvalid() { + public void testSyncConnectorTroubleshootingSnapshotRestoreFailureMarksInvalid() throws Exception { final StandardConnectorRepository repository = createRepositoryWithProvider(null); final ConnectorNode connector = createConnectorNodeWithEmptyWorkingConfig("connector-1", "Test Connector"); when(connector.getCurrentState()).thenReturn(ConnectorState.STOPPED); - final FrameworkFlowContext activeFlowContext = connector.getActiveFlowContext(); - doThrow(new RuntimeException("Snapshot restore failure")).when(activeFlowContext).restoreTroubleshootingFlow(any()); + doThrow(new FlowUpdateException("Snapshot restore failure")).when(connector).restoreTroubleshootingManagedFlow(any()); repository.restoreConnector(connector); final VersionedProcessGroup persistedManagedGroup = new VersionedProcessGroup(); @@ -1965,9 +1985,10 @@ public void testSyncConnectorTroubleshootingInheritConfigurationFailureSkipsSnap final ConnectorSyncResult result = repository.syncConnector(versioned); assertEquals(ConnectorSyncResult.Outcome.FAILED, result.getOutcome()); - // inheritConfiguration ran first and failed; the managed flow snapshot must not be overlaid and the + // inheritConfiguration ran first and failed; the managed flow must not be restored and the // Connector must not transition into TROUBLESHOOTING. - verify(connector.getActiveFlowContext(), never()).restoreTroubleshootingFlow(any()); + verify(connector, never()).restorePersistedManagedFlow(any()); + verify(connector, never()).restoreTroubleshootingManagedFlow(any()); verify(connector, never()).restoreTroubleshootingState(); } @@ -2842,6 +2863,10 @@ private VersionedConnector createVersionedConnector(final String id, final Strin } private StandardConnectorNode createRealConnectorNode(final String identifier, final Connector connector) throws FlowUpdateException { + return createRealConnectorNode(identifier, connector, false); + } + + private StandardConnectorNode createRealConnectorNode(final String identifier, final Connector connector, final boolean extensionMissing) throws FlowUpdateException { final ExtensionManager extensionManager = mock(ExtensionManager.class); final AssetManager assetManager = mock(AssetManager.class); final SecretsManager secretsManager = mock(SecretsManager.class); @@ -2851,6 +2876,27 @@ private StandardConnectorNode createRealConnectorNode(final String identifier, f final ProcessGroup managedProcessGroup = mock(ProcessGroup.class); when(managedProcessGroup.purge()).thenReturn(CompletableFuture.completedFuture(null)); when(managedProcessGroup.getQueueSize()).thenReturn(new QueueSize(0, 0L)); + when(managedProcessGroup.getIdentifier()).thenReturn("managed-group"); + when(managedProcessGroup.getProcessGroupIdentifier()).thenReturn("managed-group"); + when(managedProcessGroup.getVersionedComponentId()).thenReturn(Optional.of("managed-group-versioned")); + when(managedProcessGroup.getName()).thenReturn("Managed Group"); + when(managedProcessGroup.getPosition()).thenReturn(new Position(0, 0)); + when(managedProcessGroup.getFlowFileConcurrency()).thenReturn(FlowFileConcurrency.UNBOUNDED); + when(managedProcessGroup.getFlowFileOutboundPolicy()).thenReturn(FlowFileOutboundPolicy.STREAM_WHEN_AVAILABLE); + when(managedProcessGroup.getExecutionEngine()).thenReturn(ExecutionEngine.INHERITED); + when(managedProcessGroup.getProcessors()).thenReturn(Set.of()); + when(managedProcessGroup.getProcessGroups()).thenReturn(Set.of()); + when(managedProcessGroup.getInputPorts()).thenReturn(Set.of()); + when(managedProcessGroup.getOutputPorts()).thenReturn(Set.of()); + when(managedProcessGroup.getRemoteProcessGroups()).thenReturn(Set.of()); + when(managedProcessGroup.getControllerServices(false)).thenReturn(Set.of()); + when(managedProcessGroup.getConnections()).thenReturn(Set.of()); + final ProcessGroupLifecycle lifecycle = mock(ProcessGroupLifecycle.class); + when(lifecycle.stop()).thenReturn(CompletableFuture.completedFuture(null)); + final ProcessGroupFacade rootGroup = mock(ProcessGroupFacade.class); + when(rootGroup.getLifecycle()).thenReturn(lifecycle); + final ProcessGroupFacadeFactory groupFacadeFactory = mock(ProcessGroupFacadeFactory.class); + when(groupFacadeFactory.create(any(ProcessGroup.class), any(ComponentLog.class))).thenReturn(rootGroup); final FlowContextFactory flowContextFactory = new FlowContextFactory() { @Override @@ -2858,7 +2904,7 @@ public FrameworkFlowContext createActiveFlowContext(final String connectorId, fi final MutableConnectorConfigurationContext activeConfigurationContext = new StandardConnectorConfigurationContext(assetManager, secretsManager); return new StandardFlowContext(managedProcessGroup, activeConfigurationContext, - mock(ProcessGroupFacadeFactory.class), mock(ParameterContextFacadeFactory.class), + groupFacadeFactory, mock(ParameterContextFacadeFactory.class), connectorLogger, FlowContextType.ACTIVE, bundle); } @@ -2866,7 +2912,7 @@ public FrameworkFlowContext createActiveFlowContext(final String connectorId, fi public FrameworkFlowContext createWorkingFlowContext(final String connectorId, final ComponentLog connectorLogger, final MutableConnectorConfigurationContext currentConfiguration, final Bundle bundle) { return new StandardFlowContext(managedProcessGroup, currentConfiguration, - mock(ProcessGroupFacadeFactory.class), mock(ParameterContextFacadeFactory.class), + groupFacadeFactory, mock(ParameterContextFacadeFactory.class), connectorLogger, FlowContextType.WORKING, bundle); } }; @@ -2888,11 +2934,14 @@ public void trigger(final ConnectorNode node) { final BundleCoordinate bundleCoordinate = new BundleCoordinate("org.apache.nifi", "test-standard-connector-node", "1.0.0"); final ConnectorDetails connectorDetails = new ConnectorDetails(connector, bundleCoordinate, componentLog); + final FlowManager flowManager = mock(FlowManager.class); + final ConnectorFlowSnapshotMapper snapshotMapper = new ConnectorFlowSnapshotMapper( + extensionManager, mock(ControllerServiceProvider.class), new InternalPassThroughPropertyEncryptionProvider()); final StandardConnectorNode node = new StandardConnectorNode( - identifier, mock(FlowManager.class), extensionManager, new MockStateManagerProvider(), null, connectorDetails, + identifier, flowManager, extensionManager, new MockStateManagerProvider(), null, connectorDetails, "TestConnector", connector.getClass().getCanonicalName(), new StandardConnectorConfigurationContext(assetManager, secretsManager), - stateTransition, flowContextFactory, validationTrigger, false); + stateTransition, flowContextFactory, snapshotMapper, validationTrigger, extensionMissing); final FrameworkConnectorInitializationContext initializationContext = mock(FrameworkConnectorInitializationContext.class); when(initializationContext.getSecretsManager()).thenReturn(secretsManager); @@ -2916,6 +2965,10 @@ private void seedWorkingConfiguration(final StandardConnectorNode connectorNode, } private StandardConnectorRepository createRepositoryWithShortTimeout(final ConnectorConfigurationProvider provider) { + return createRepositoryWithShortTimeout(provider, Duration.ofMinutes(30)); + } + + private StandardConnectorRepository createRepositoryWithShortTimeout(final ConnectorConfigurationProvider provider, final Duration flowEvolutionTimeout) { final StandardConnectorRepository repository = new StandardConnectorRepository(); final ConnectorRepositoryInitializationContext initContext = mock(ConnectorRepositoryInitializationContext.class); when(initContext.getFlowManager()).thenReturn(mock(FlowManager.class)); @@ -2923,6 +2976,7 @@ private StandardConnectorRepository createRepositoryWithShortTimeout(final Conne when(initContext.getAssetManager()).thenReturn(mock(AssetManager.class)); when(initContext.getConnectorConfigurationProvider()).thenReturn(provider); when(initContext.getConnectorSyncTimeout()).thenReturn(Duration.ofSeconds(5)); + when(initContext.getConnectorFlowEvolutionTimeout()).thenReturn(flowEvolutionTimeout); repository.initialize(initContext); return repository; } @@ -3217,6 +3271,231 @@ public List verifyConfigurationStep(final String stepN } } + @Test + public void testSyncInfersMissingManagedFlowBundleAndRegistersEvolution() throws Exception { + final StandardConnectorNode connectorNode = createRealConnectorNode("connector-1", new FlowEvolutionHookConnector()); + final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null); + repository.restoreConnector(connectorNode); + final VersionedProcessGroup persisted = flowGroup("outgoing-flow"); + final Bundle outgoingBundle = new Bundle("org.apache.nifi", "test-standard-connector-node", "0.9.0"); + final VersionedConnector versioned = versionedConnector(outgoingBundle, persisted); + assertNull(versioned.getManagedFlowBundle()); + + final ConnectorSyncResult result = repository.syncConnector(versioned); + + assertNotEquals(ConnectorSyncResult.Outcome.FAILED, result.getOutcome()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertEquals("0.9.0", connectorNode.getAuthoritativeFlowSnapshot().bundle().getVersion()); + } + + /** + * A reconnecting node re-syncs an existing Connector that has no snapshot yet, so the live flow is captured. + */ + @Test + public void testSyncWithoutPersistedFlowUsesLoadedBundleWithoutEvolution() throws Exception { + final StandardConnectorNode connectorNode = createRealConnectorNode("connector-1", new FlowEvolutionHookConnector()); + final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null); + repository.restoreConnector(connectorNode); + final Bundle matchingBundle = new Bundle("org.apache.nifi", "test-standard-connector-node", "1.0.0"); + + final ConnectorSyncResult result = repository.syncConnector(versionedConnector(matchingBundle, null)); + + assertNotEquals(ConnectorSyncResult.Outcome.FAILED, result.getOutcome()); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertEquals("1.0.0", connectorNode.getAuthoritativeFlowSnapshot().bundle().getVersion()); + } + + /** + * A persisted group on the loaded bundle is not adopted, so the node keeps the snapshot it holds: the live flow, or the + * pre-upgrade flow of an evolution that has not run on this node yet. + */ + @Test + public void testSameBundleSyncKeepsHeldSnapshot() throws Exception { + final Bundle loadedBundle = new Bundle("org.apache.nifi", "test-standard-connector-node", "1.0.0"); + + final StandardConnectorNode liveNode = createRealConnectorNode("connector-1", new FlowEvolutionHookConnector()); + final StandardConnectorRepository liveRepository = createRepositoryWithShortTimeout(null); + liveRepository.restoreConnector(liveNode); + final ConnectorSyncResult liveResult = liveRepository.syncConnector(versionedConnector(loadedBundle, flowGroup("persisted-flow"))); + assertNotEquals(ConnectorSyncResult.Outcome.FAILED, liveResult.getOutcome()); + assertFalse(liveNode.isPendingFlowEvolution()); + assertNotEquals("persisted-flow", liveNode.getAuthoritativeFlowSnapshot().flow().getName()); + + final StandardConnectorNode pendingNode = pendingEvolutionNode("connector-1", new FlowEvolutionHookConnector()); + final StandardConnectorRepository pendingRepository = createRepositoryWithShortTimeout(null); + pendingRepository.restoreConnector(pendingNode); + final ConnectorSyncResult pendingResult = pendingRepository.syncConnector(versionedConnector(loadedBundle, flowGroup("persisted-flow"))); + assertNotEquals(ConnectorSyncResult.Outcome.FAILED, pendingResult.getOutcome()); + assertTrue(pendingNode.isPendingFlowEvolution()); + assertEquals(outgoingSnapshotBundle().getVersion(), pendingNode.getAuthoritativeFlowSnapshot().bundle().getVersion()); + } + + @Test + public void testPersistedComponentBundleResolution() throws Exception { + final StandardConnectorNode ambiguous = createRealConnectorNode("connector-1", new FlowEvolutionHookConnector()); + final StandardConnectorRepository ambiguousRepository = createRepositoryWithShortTimeout(null); + ambiguousRepository.restoreConnector(ambiguous); + useBundleLookup(ambiguous, List.of( + componentBundle("org.apache.nifi", "processor-nar", "2.0.0"), + componentBundle("org.apache.nifi", "processor-nar", "3.0.0"))); + final VersionedProcessGroup ambiguousFlow = componentGroup("outgoing-flow", componentBundle("org.apache.nifi", "processor-nar", "1.0.0")); + ambiguousRepository.syncConnector(versionedConnector(new Bundle("org.apache.nifi", "test-nar", "1.0.0"), ambiguousFlow)); + assertEquals("1.0.0", ambiguousFlow.getProcessors().iterator().next().getBundle().getVersion()); + assertEquals("1.0.0", ambiguous.getAuthoritativeFlowSnapshot().flow().getProcessors().iterator().next().getBundle().getVersion()); + + final StandardConnectorNode ghost = createRealConnectorNode("connector-1", new FlowEvolutionHookConnector(), true); + final StandardConnectorRepository ghostRepository = createRepositoryWithShortTimeout(null); + ghostRepository.restoreConnector(ghost); + useBundleLookup(ghost, List.of(componentBundle("org.apache.nifi", "processor-nar", "2.0.0"))); + final VersionedProcessGroup ghostFlow = componentGroup("ghost-flow", componentBundle("org.apache.nifi", "processor-nar", "1.0.0")); + ghostRepository.syncConnector(versionedConnector(new Bundle("org.apache.nifi", "test-nar", "1.0.0"), ghostFlow)); + assertTrue(ghost.isExtensionMissing()); + assertEquals("1.0.0", ghostFlow.getProcessors().iterator().next().getBundle().getVersion()); + assertEquals("1.0.0", ghost.getAuthoritativeFlowSnapshot().flow().getProcessors().iterator().next().getBundle().getVersion()); + } + + @Test + public void testGhostSyncRestoreFailureFlagsConnectorAndAdoptsSnapshot() throws Exception { + final StandardConnectorNode connectorNode = createRealConnectorNode("connector-1", new FlowEvolutionHookConnector(), true); + final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null); + repository.restoreConnector(connectorNode); + doThrow(new IllegalStateException("Expected restore failure")).when(connectorNode.getActiveFlowContext().getManagedProcessGroup()) + .restoreFlowPreservingIdentifiers(any(), eq(false)); + final VersionedProcessGroup persisted = flowGroup("ghost-flow"); + + final ConnectorSyncResult result = repository.syncConnector( + versionedConnector(new Bundle("org.apache.nifi", "test-nar", "1.0.0"), persisted)); + + assertNotEquals(ConnectorSyncResult.Outcome.FAILED, result.getOutcome()); + assertTrue(connectorNode.isManagedFlowRestoreFailed()); + assertEquals("ghost-flow", connectorNode.getAuthoritativeFlowSnapshot().flow().getName()); + } + + @Test + public void testPersistenceFailureAfterApplyLeavesUpdateFailedAndLaterStartRunsNewFlow() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + final StandardConnectorNode connectorNode = pendingEvolutionNode("persistence-failure", connector); + final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null); + final ConnectorUpdateContext persistenceContext = () -> { + throw new IllegalStateException("Expected persistence failure"); + }; + + assertThrows(ExecutionException.class, () -> repository.startConnector(connectorNode, persistenceContext).get(5, TimeUnit.SECONDS)); + assertEquals(ConnectorState.UPDATE_FAILED, connectorNode.getCurrentState()); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertEquals(FlowEvolutionStatus.INACTIVE, connectorNode.getReportedFlowEvolutionStatus()); + assertEquals(1, connector.hookCalls); + assertEquals(1, connector.prepareCalls); + assertEquals(1, connector.applyCalls); + + repository.startConnector(connectorNode, persistenceContext).get(5, TimeUnit.SECONDS); + assertEquals(1, connector.hookCalls); + assertEquals(1, connector.prepareCalls); + assertEquals(1, connector.applyCalls); + assertEquals(ConnectorState.RUNNING, connectorNode.getCurrentState()); + } + + @Test + public void testFlowEvolutionDrainTimeoutFailsEvolution() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + connector.leaveFutureIncomplete = true; + final StandardConnectorNode connectorNode = pendingEvolutionNode("drain-timeout", connector); + final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null, Duration.ofMillis(500)); + + assertThrows(ExecutionException.class, () -> repository.startConnector(connectorNode, NO_OP_PERSISTENCE).get(5, TimeUnit.SECONDS)); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertEquals(0, connector.applyCalls); + assertTrue(connectorNode.getValidationErrors().stream() + .anyMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()) && result.getExplanation().contains("timed out"))); + } + + @Test + public void testConfigurationUpdateSavesAgainWithRestoredState() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + final StandardConnectorNode connectorNode = createRealConnectorNode("configuration-save", connector); + final AssetManager assetManager = mock(AssetManager.class); + final StandardConnectorRepository repository = createRepositoryWithProviderAndAssetManager(null, assetManager); + repository.addConnector(connectorNode); + repository.startConnector(connectorNode, NO_OP_PERSISTENCE).get(5, TimeUnit.SECONDS); + final List savedStates = new CopyOnWriteArrayList<>(); + + repository.applyUpdate(connectorNode, () -> savedStates.add(connectorNode.getDesiredState())); + verify(assetManager, timeout(5000)).getAssets("configuration-save"); + assertEquals(List.of(ConnectorState.UPDATED, ConnectorState.RUNNING), savedStates); + assertEquals(1, connector.prepareCalls); + assertEquals(1, connector.applyCalls); + assertEquals(ConnectorState.RUNNING, connectorNode.getDesiredState()); + } + + private StandardConnectorNode pendingEvolutionNode(final String identifier, final Connector connector) throws Exception { + final StandardConnectorNode connectorNode = createRealConnectorNode(identifier, connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + return connectorNode; + } + + private VersionedConnector versionedConnector(final Bundle bundle, final VersionedProcessGroup managed) { + final VersionedConnector versioned = createVersionedConnector("connector-1", "Connector", VersionedConnectorState.ENABLED, List.of()); + versioned.setBundle(bundle); + versioned.setManagedProcessGroup(managed); + versioned.setType(FlowEvolutionHookConnector.class.getName()); + return versioned; + } + + private static void useBundleLookup(final StandardConnectorNode connectorNode, final List availableBundles) { + final ComponentBundleLookup bundleLookup = mock(ComponentBundleLookup.class); + when(bundleLookup.getAvailableBundles(anyString())).thenReturn(availableBundles); + connectorNode.initializeConnector(new StandardConnectorInitializationContext.Builder() + .identifier(connectorNode.getIdentifier()) + .name("Connector") + .componentLog(connectorNode.getComponentLog()) + .secretsManager(mock(SecretsManager.class)) + .assetManager(mock(AssetManager.class)) + .componentBundleLookup(bundleLookup) + .build()); + } + + private static VersionedProcessGroup flowGroup(final String name) { + final VersionedProcessGroup group = new VersionedProcessGroup(); + group.setName(name); + group.setIdentifier(name); + return group; + } + + private static Bundle outgoingSnapshotBundle() { + return new Bundle("org.apache.nifi", "test-standard-connector-node", "0.9.0"); + } + + private static Bundle componentBundle(final String group, final String artifact, final String version) { + final Bundle bundle = new Bundle(); + bundle.setGroup(group); + bundle.setArtifact(artifact); + bundle.setVersion(version); + return bundle; + } + + private static VersionedProcessGroup componentGroup(final String name, final Bundle bundle) { + final VersionedProcessor processor = new VersionedProcessor(); + processor.setIdentifier("processor-1"); + processor.setName("Generate"); + processor.setType("org.example.Generate"); + processor.setBundle(bundle); + processor.setComponentType(ComponentType.PROCESSOR); + + final VersionedControllerService service = new VersionedControllerService(); + service.setIdentifier("service-1"); + service.setName("Service"); + service.setType("org.example.Service"); + service.setBundle(new Bundle(bundle.getGroup(), bundle.getArtifact(), bundle.getVersion())); + service.setComponentType(ComponentType.CONTROLLER_SERVICE); + + final VersionedProcessGroup group = flowGroup(name); + group.setProcessors(new HashSet<>(Set.of(processor))); + group.setControllerServices(new HashSet<>(Set.of(service))); + return group; + } + private static class MigratingConnector extends TrackingConnector { private java.util.function.Consumer migration = config -> { }; diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java index 993b63f3d675..6b24eee538b3 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java @@ -17,19 +17,35 @@ package org.apache.nifi.components.connector; +import org.apache.nifi.asset.Asset; +import org.apache.nifi.asset.AssetManager; import org.apache.nifi.components.connector.components.FlowContextType; +import org.apache.nifi.components.connector.components.ParameterContextFacade; +import org.apache.nifi.components.connector.components.ParameterValue; import org.apache.nifi.components.connector.components.ProcessGroupFacade; import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.VersionedAsset; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.logging.ComponentLog; +import org.apache.nifi.parameter.ParameterContext; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.io.File; +import java.util.List; +import java.util.Optional; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -class TestStandardFlowContext { +public class TestStandardFlowContext { @Test void testReloadReplacesStateAfterCreatingRootGroup() { @@ -66,4 +82,44 @@ void testReloadReplacesStateAfterCreatingRootGroup() { assertSame(replacementConfiguration, flowContext.getConfigurationContext()); assertSame(replacementRootGroup, flowContext.getRootGroup()); } + + @Test + public void testRestorePersistedFlowResolvesParameterAssets() { + final Asset asset = mock(Asset.class); + when(asset.getFile()).thenReturn(new File("target/asset.txt")); + final AssetManager assetManager = mock(AssetManager.class); + when(assetManager.getAsset("asset-1")).thenReturn(Optional.of(asset)); + + final ParameterContext managedParameterContext = mock(ParameterContext.class); + when(managedParameterContext.getName()).thenReturn("managed-parameters"); + final ProcessGroup managedProcessGroup = mock(ProcessGroup.class); + when(managedProcessGroup.getParameterContext()).thenReturn(managedParameterContext); + + final ParameterContextFacade parameterContextFacade = mock(ParameterContextFacade.class); + final StandardFlowContext flowContext = new StandardFlowContext(managedProcessGroup, + mock(MutableConnectorConfigurationContext.class), assetManager, mock(ProcessGroupFacadeFactory.class), + group -> parameterContextFacade, mock(ComponentLog.class), FlowContextType.ACTIVE, new Bundle()); + + final VersionedAsset versionedAsset = new VersionedAsset(); + versionedAsset.setIdentifier("asset-1"); + versionedAsset.setName("asset.txt"); + final VersionedParameter versionedParameter = new VersionedParameter(); + versionedParameter.setName("Asset Parameter"); + versionedParameter.setReferencedAssets(List.of(versionedAsset)); + final VersionedParameterContext versionedParameterContext = new VersionedParameterContext(); + versionedParameterContext.setIdentifier("parameter-context-1"); + versionedParameterContext.setName("managed-parameters"); + versionedParameterContext.setParameters(Set.of(versionedParameter)); + + flowContext.restorePersistedFlow(new VersionedProcessGroup(), versionedParameterContext); + + final ArgumentCaptor> valuesCaptor = ArgumentCaptor.forClass(List.class); + verify(parameterContextFacade).updateParameters(valuesCaptor.capture()); + final List restoredParameters = valuesCaptor.getValue(); + final ParameterValue restoredAssetParameter = restoredParameters.stream() + .filter(parameter -> "Asset Parameter".equals(parameter.getName())) + .findFirst() + .orElseThrow(); + assertSame(asset, restoredAssetParameter.getAssets().getFirst()); + } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/flow/TestStandardFlowManager.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/flow/TestStandardFlowManager.java index 473962890fdd..88dc6ffc9e8b 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/flow/TestStandardFlowManager.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/flow/TestStandardFlowManager.java @@ -41,6 +41,7 @@ import org.apache.nifi.parameter.ParameterContextManager; import org.apache.nifi.provenance.ProvenanceRepository; import org.apache.nifi.reporting.BulletinRepository; +import org.apache.nifi.security.encryption.InternalPassThroughPropertyEncryptionProvider; import org.apache.nifi.util.NiFiProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -136,6 +137,7 @@ public void testCreateConnectorInitializesConnector() { when(flowController.getRepositoryContextFactory()).thenReturn(repositoryContextFactory); when(flowController.getGarbageCollectionLog()).thenReturn(mock(GarbageCollectionLog.class)); when(flowController.getControllerServiceProvider()).thenReturn(mock(ControllerServiceProvider.class)); + when(flowController.getPropertyEncryptionProvider()).thenReturn(new InternalPassThroughPropertyEncryptionProvider()); when(flowController.getProvenanceRepository()).thenReturn(mock(ProvenanceRepository.class)); when(flowController.getBulletinRepository()).thenReturn(mock(BulletinRepository.class)); when(flowController.getLifecycleStateManager()).thenReturn(mock(LifecycleStateManager.class)); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java index bc9b8623ce38..8fd9a339a74f 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java @@ -738,6 +738,11 @@ public void updateFlow(VersionedExternalFlow proposedFlow, String componentIdSee public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedFlow) { } + @Override + public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedFlow, final boolean resumeComponentState) { + restoreFlowPreservingIdentifiers(proposedFlow); + } + @Override public void synchronizeFlow(final VersionedExternalFlow proposedSnapshot, final FlowSynchronizationOptions synchronizationOptions, final FlowMappingOptions flowMappingOptions) { } diff --git a/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml b/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml index 390c6585d43a..3eed01855a5e 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml +++ b/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml @@ -127,6 +127,7 @@ ./assets org.apache.nifi.asset.StandardConnectorAssetManager ./connector_assets + 30 mins diff --git a/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties b/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties index bbe41a671358..f25efcc09c0d 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties +++ b/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties @@ -142,6 +142,9 @@ nifi.asset.manager.properties.directory=${nifi.asset.manager.properties.director nifi.connector.asset.manager.implementation=${nifi.connector.asset.manager.implementation} nifi.connector.asset.manager.properties.directory=${nifi.connector.asset.manager.properties.directory} +# How long a connector may spend draining during flow evolution. +nifi.connector.flow.evolution.timeout=${nifi.connector.flow.evolution.timeout} + # Connector Configuration Provider nifi.connector.configuration.provider.implementation= diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java index 3723f2f79ff9..78dbf95f1584 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/audit/ConnectorAuditor.java @@ -121,8 +121,8 @@ public void removeConnectorAdvice(final ProceedingJoinPoint proceedingJoinPoint, * @throws Throwable if an error occurs */ @Around("within(org.apache.nifi.web.dao.ConnectorDAO+) && " - + "execution(void startConnector(java.lang.String)) && " - + "args(connectorId) && " + + "execution(void startConnector(java.lang.String, ..)) && " + + "args(connectorId, ..) && " + "target(connectorDAO)") public void startConnectorAdvice(final ProceedingJoinPoint proceedingJoinPoint, final String connectorId, final ConnectorDAO connectorDAO) throws Throwable { final ConnectorNode connector = connectorDAO.getConnector(connectorId, ConnectorSyncMode.LOCAL_ONLY); diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java index 810f08b8283e..bf47bea441d5 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java @@ -3771,7 +3771,9 @@ public ConnectorEntity getConnector(final String id, final boolean clusterNodeRe @Override public void verifyUpdateConnector(final ConnectorDTO connectorDTO) { - final ConnectorNode connector = connectorDAO.getConnector(connectorDTO.getId()); + // Run-status verification shares this method. Loading the provider here would apply an external edit that + // the caller has not synchronized, so start and stop must see only the in-memory configuration. + final ConnectorNode connector = connectorDAO.getConnector(connectorDTO.getId(), ConnectorSyncMode.LOCAL_ONLY); final ConnectorState currentState = connector.getCurrentState(); if ((connectorDTO.getName() != null || connectorDTO.getBundle() != null) && currentState == ConnectorState.TROUBLESHOOTING) { @@ -3782,6 +3784,7 @@ public void verifyUpdateConnector(final ConnectorDTO connectorDTO) { if (connectorDTO.getBundle() != null) { final BundleCoordinate incomingCoordinate = BundleUtils.getBundle(controllerFacade.getExtensionManager(), connector.getCanonicalClassName(), connectorDTO.getBundle()); if (!incomingCoordinate.equals(connector.getBundleCoordinate())) { + verifyClusterConnectedForVersionChange(connectorDTO.getId()); connector.verifyCanUpdateBundle(incomingCoordinate); connector.verifyCanReload(); } @@ -3801,7 +3804,10 @@ public void verifyUpdateConnector(final ConnectorDTO connectorDTO) { } switch (desiredState) { - case RUNNING -> connector.verifyCanStart(); + case RUNNING -> { + verifyExpectedConnectorBundle(connector, connectorDTO.getExpectedBundle()); + connector.verifyCanStart(); + } case STOPPED -> { // Stop is valid from any non-Troubleshooting state; no additional verification required. } @@ -3810,6 +3816,22 @@ public void verifyUpdateConnector(final ConnectorDTO connectorDTO) { } } + private void verifyExpectedConnectorBundle(final ConnectorNode connector, final BundleDTO expectedBundle) { + if (expectedBundle == null) { + return; + } + + final BundleCoordinate expectedCoordinate = BundleUtils.getBundle(controllerFacade.getExtensionManager(), connector.getCanonicalClassName(), expectedBundle); + final BundleCoordinate loadedCoordinate = connector.getBundleCoordinate(); + if (expectedCoordinate.equals(loadedCoordinate)) { + return; + } + + throw new IllegalStateException("Cannot start Connector " + connector.getIdentifier() + + " because this node loaded " + loadedCoordinate + + " but the cluster coordinator expects " + expectedCoordinate); + } + @Override public ConnectorEntity updateConnector(final Revision revision, final ConnectorDTO connectorDTO) { final NiFiUser user = NiFiUserUtils.getNiFiUser(); @@ -3870,11 +3892,17 @@ public ConnectorEntity scheduleConnector(final Revision revision, final String i final RevisionUpdate snapshot = revisionManager.updateRevision(claim, user, () -> { switch (state) { - case RUNNING -> connectorDAO.startConnector(id); + case RUNNING -> connectorDAO.startConnector(id, controllerFacade::saveImmediate); case STOPPED -> connectorDAO.stopConnector(id); default -> throw new IllegalArgumentException("Unsupported scheduled state for Connector: " + state); } - controllerFacade.save(); + // Evolution sets the desired state to RUNNING as soon as it is claimed so a joining node starts too. + // Persisting that state before the hook succeeds makes a failed evolution auto-start on restart. + // The repository saves once the upgraded flow is applied, and a failed evolution puts the desired state back. + final ConnectorNode scheduled = connectorDAO.getConnector(id, ConnectorSyncMode.LOCAL_ONLY); + if (scheduled.getCurrentState() != ConnectorState.DRAINING || !scheduled.isPendingFlowEvolution()) { + controllerFacade.save(); + } final ConnectorNode node = connectorDAO.getConnector(id, ConnectorSyncMode.LOCAL_ONLY); final ConnectorDTO dto = dtoFactory.createConnectorDto(node); @@ -3987,6 +4015,22 @@ public void verifyEndConnectorTroubleshooting(final String id) { connectorDAO.verifyEndTroubleshooting(id); } + /** + * Every node must drain a version change together, and a node that misses the change keeps the outgoing version. The change + * therefore requires every node to be CONNECTED, and acknowledging a disconnected node does not relax this requirement. + */ + private void verifyClusterConnectedForVersionChange(final String connectorId) { + if (clusterCoordinator == null) { + return; + } + + final List unconnectedNodes = getUnconnectedNodes(); + if (!clusterCoordinator.isConnected() || !unconnectedNodes.isEmpty()) { + throw new IllegalStateException("Cannot change the version of Connector " + connectorId + " because the following cluster nodes are not CONNECTED: " + + (unconnectedNodes.isEmpty() ? "this node" : unconnectedNodes) + ". All nodes must be CONNECTED before the version may change."); + } + } + private List getUnconnectedNodes() { if (clusterCoordinator == null) { return List.of(); 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 fe386e574419..5a5657a68eb9 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 @@ -696,6 +696,9 @@ public Response updateRunStatus( requestRunStatus.validateState(); if (isReplicateRequest()) { + if (ScheduledState.RUNNING.name().equals(requestRunStatus.getState()) && getReplicationTarget() == ReplicationTarget.CLUSTER_NODES) { + populateExpectedBundle(id, requestRunStatus); + } return replicate(HttpMethod.PUT, requestRunStatus); } else if (isDisconnectedFromCluster()) { verifyDisconnectedNodeModification(requestRunStatus.isDisconnectedNodeAcknowledged()); @@ -713,7 +716,7 @@ public Response updateRunStatus( final Authorizable connector = lookup.getConnector(id); OperationAuthorizable.authorizeOperation(connector, authorizer, user); }, - () -> serviceFacade.verifyUpdateConnector(createDTOWithDesiredRunStatus(id, requestRunStatus.getState())), + () -> serviceFacade.verifyUpdateConnector(createDTOWithDesiredRunStatus(id, requestRunStatus.getState(), requestRunStatus.getExpectedBundle())), (revision, runStatusEntity) -> { // update the connector final ScheduledState scheduledState = ScheduledState.valueOf(runStatusEntity.getState()); @@ -725,6 +728,19 @@ public Response updateRunStatus( ); } + /** + * Fills the coordinator's loaded bundle onto the run-status request so each node can reject a START in the + * validation phase when its own loaded bundle differs. Avoids an extra replicated GET. + */ + private void populateExpectedBundle(final String connectorId, final ConnectorRunStatusEntity requestRunStatus) { + final ConnectorEntity localConnector = serviceFacade.getConnector(connectorId); + if (localConnector == null || localConnector.getComponent() == null || localConnector.getComponent().getBundle() == null) { + return; + } + + requestRunStatus.setExpectedBundle(localConnector.getComponent().getBundle()); + } + /** * Initiates the draining of FlowFiles for the specified connector. * @@ -1793,10 +1809,11 @@ public Response searchConnector( return noCache(Response.ok(entity)).build(); } - private ConnectorDTO createDTOWithDesiredRunStatus(final String id, final String runStatus) { + private ConnectorDTO createDTOWithDesiredRunStatus(final String id, final String runStatus, final BundleDTO expectedBundle) { final ConnectorDTO dto = new ConnectorDTO(); dto.setId(id); dto.setState(runStatus); + dto.setExpectedBundle(expectedBundle); return dto; } diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java index b1414b65fc13..75e9b8b9109b 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/api/dto/DtoFactory.java @@ -77,6 +77,7 @@ import org.apache.nifi.components.connector.ConnectorPropertyGroup; import org.apache.nifi.components.connector.ConnectorRepository; import org.apache.nifi.components.connector.ConnectorValueReference; +import org.apache.nifi.components.connector.FlowEvolutionStatus; import org.apache.nifi.components.connector.FrameworkFlowContext; import org.apache.nifi.components.connector.NamedStepConfiguration; import org.apache.nifi.components.connector.Secret; @@ -5434,6 +5435,8 @@ public ConnectorDTO createConnectorDto(final ConnectorNode connector) { dto.setBundle(createBundleDto(bundleCoordinate)); dto.setState(connector.getCurrentState().name()); + final FlowEvolutionStatus flowEvolutionStatus = connector.getReportedFlowEvolutionStatus(); + dto.setFlowEvolutionStatus(flowEvolutionStatus == null ? FlowEvolutionStatus.INACTIVE.name() : flowEvolutionStatus.name()); final FrameworkFlowContext activeFlowContext = connector.getActiveFlowContext(); dto.setManagedProcessGroupId(activeFlowContext.getManagedProcessGroup().getIdentifier()); diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java index f32dde5126b8..1aa49b7cd0f8 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/ConnectorDAO.java @@ -54,7 +54,7 @@ public interface ConnectorDAO { void deleteConnector(String id); - void startConnector(String id); + void startConnector(String id, ConnectorUpdateContext persistenceContext); void stopConnector(String id); diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java index 8744d6cf695e..afc0045fc216 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/dao/impl/StandardConnectorDAO.java @@ -190,9 +190,9 @@ public void deleteConnector(final String id) { } @Override - public void startConnector(final String id) { + public void startConnector(final String id, final ConnectorUpdateContext persistenceContext) { final ConnectorNode connector = requireConnector(id, ConnectorSyncMode.LOCAL_ONLY); - getConnectorRepository().startConnector(connector); + getConnectorRepository().startConnector(connector, persistenceContext); } @Override diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/StandardNiFiServiceFacadeTest.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/StandardNiFiServiceFacadeTest.java index 3e0828757f0e..69c681da5498 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/StandardNiFiServiceFacadeTest.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/StandardNiFiServiceFacadeTest.java @@ -43,6 +43,9 @@ import org.apache.nifi.bundle.Bundle; import org.apache.nifi.bundle.BundleCoordinate; import org.apache.nifi.bundle.BundleDetails; +import org.apache.nifi.cluster.coordination.ClusterCoordinator; +import org.apache.nifi.cluster.coordination.node.NodeConnectionState; +import org.apache.nifi.cluster.protocol.NodeIdentifier; import org.apache.nifi.components.Backlog; import org.apache.nifi.components.BacklogReportingException; import org.apache.nifi.components.PropertyDescriptor; @@ -2552,6 +2555,102 @@ public void testVerifyUpdateConnectorRequiresReloadVerificationWhenBundleChanges verify(connectorNode).verifyCanReload(); } + @Test + public void testVerifyUpdateConnectorRejectsVersionChangeWithUnconnectedNode() { + final String connectorId = "connector-id"; + final BundleCoordinate existingCoordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "1.0.0"); + final BundleCoordinate incomingCoordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "2.0.0"); + final ConnectorNode connectorNode = configureConnectorForBundleUpdate(connectorId, "org.apache.nifi.connectors.TestConnector", existingCoordinate, incomingCoordinate); + final NodeIdentifier unconnectedNode = configureClusterWithUnconnectedNode(); + + final ConnectorDTO connectorDTO = new ConnectorDTO(); + connectorDTO.setId(connectorId); + connectorDTO.setBundle(new BundleDTO(incomingCoordinate.getGroup(), incomingCoordinate.getId(), incomingCoordinate.getVersion())); + + final IllegalStateException exception = assertThrows(IllegalStateException.class, () -> serviceFacade.verifyUpdateConnector(connectorDTO)); + + assertTrue(exception.getMessage().contains(unconnectedNode.toString())); + verify(connectorNode, never()).verifyCanReload(); + } + + @Test + public void testVerifyUpdateConnectorRejectsVersionChangeOnDisconnectedLocalNode() { + final String connectorId = "connector-id"; + final BundleCoordinate existingCoordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "1.0.0"); + final BundleCoordinate incomingCoordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "2.0.0"); + configureConnectorForBundleUpdate(connectorId, "org.apache.nifi.connectors.TestConnector", existingCoordinate, incomingCoordinate); + final ClusterCoordinator clusterCoordinator = mock(ClusterCoordinator.class); + when(clusterCoordinator.isConnected()).thenReturn(false); + when(clusterCoordinator.getConnectionStates()).thenReturn(Map.of()); + serviceFacade.setClusterCoordinator(clusterCoordinator); + + final ConnectorDTO connectorDTO = new ConnectorDTO(); + connectorDTO.setId(connectorId); + connectorDTO.setBundle(new BundleDTO(incomingCoordinate.getGroup(), incomingCoordinate.getId(), incomingCoordinate.getVersion())); + + assertThrows(IllegalStateException.class, () -> serviceFacade.verifyUpdateConnector(connectorDTO)); + } + + @Test + public void testVerifyUpdateConnectorRejectsMismatchedExpectedBundle() { + final BundleCoordinate loadedCoordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "1.0.0"); + final BundleCoordinate expectedCoordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "2.0.0"); + final StartRequest startRequest = configureStartRequest(loadedCoordinate, expectedCoordinate); + startRequest.connectorDTO().setExpectedBundle(new BundleDTO(expectedCoordinate.getGroup(), expectedCoordinate.getId(), expectedCoordinate.getVersion())); + + final IllegalStateException exception = assertThrows(IllegalStateException.class, () -> serviceFacade.verifyUpdateConnector(startRequest.connectorDTO())); + + assertTrue(exception.getMessage().contains(loadedCoordinate.toString())); + assertTrue(exception.getMessage().contains(expectedCoordinate.toString())); + verify(startRequest.connectorNode(), never()).verifyCanStart(); + } + + @Test + public void testVerifyUpdateConnectorAcceptsMatchingExpectedBundle() { + final BundleCoordinate coordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "1.0.0"); + final StartRequest startRequest = configureStartRequest(coordinate, coordinate); + startRequest.connectorDTO().setExpectedBundle(new BundleDTO(coordinate.getGroup(), coordinate.getId(), coordinate.getVersion())); + + serviceFacade.verifyUpdateConnector(startRequest.connectorDTO()); + + verify(startRequest.connectorNode()).verifyCanStart(); + } + + @Test + public void testVerifyUpdateConnectorAllowsMissingExpectedBundle() { + final BundleCoordinate coordinate = new BundleCoordinate("org.apache.nifi", "nifi-test-nar", "1.0.0"); + final StartRequest startRequest = configureStartRequest(coordinate, coordinate); + + serviceFacade.verifyUpdateConnector(startRequest.connectorDTO()); + + verify(startRequest.connectorNode()).verifyCanStart(); + } + + private record StartRequest(ConnectorNode connectorNode, ConnectorDTO connectorDTO) { + } + + private StartRequest configureStartRequest(final BundleCoordinate loadedCoordinate, final BundleCoordinate availableCoordinate) { + final String connectorId = "connector-id"; + final ConnectorNode connectorNode = configureConnectorForBundleUpdate(connectorId, "org.apache.nifi.connectors.TestConnector", loadedCoordinate, availableCoordinate); + + final ConnectorDTO connectorDTO = new ConnectorDTO(); + connectorDTO.setId(connectorId); + connectorDTO.setState(ScheduledState.RUNNING.name()); + return new StartRequest(connectorNode, connectorDTO); + } + + private NodeIdentifier configureClusterWithUnconnectedNode() { + final NodeIdentifier connectedNode = new NodeIdentifier("node-1", "node-1.example.com", 8443, "node-1.example.com", 9999, null, null, null, false); + final NodeIdentifier unconnectedNode = new NodeIdentifier("node-2", "node-2.example.com", 8443, "node-2.example.com", 9999, null, null, null, false); + final ClusterCoordinator clusterCoordinator = mock(ClusterCoordinator.class); + when(clusterCoordinator.isConnected()).thenReturn(true); + when(clusterCoordinator.getConnectionStates()).thenReturn(Map.of( + NodeConnectionState.CONNECTED, List.of(connectedNode), + NodeConnectionState.DISCONNECTED, List.of(unconnectedNode))); + serviceFacade.setClusterCoordinator(clusterCoordinator); + return unconnectedNode; + } + @Test public void testGetConnectorClusterNodeRequest() { final String connectorId = "connector-id"; @@ -3761,7 +3860,7 @@ private ConnectorNode configureConnectorForBundleUpdate(final String connectorId serviceFacade.setConnectorDAO(connectorDAO); final ConnectorNode connectorNode = mock(ConnectorNode.class); - when(connectorDAO.getConnector(connectorId)).thenReturn(connectorNode); + when(connectorDAO.getConnector(connectorId, ConnectorSyncMode.LOCAL_ONLY)).thenReturn(connectorNode); when(connectorNode.getCurrentState()).thenReturn(ConnectorState.STOPPED); when(connectorNode.getCanonicalClassName()).thenReturn(type); when(connectorNode.getBundleCoordinate()).thenReturn(existingCoordinate); 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 866da17c9409..24b6a8cf08d7 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 @@ -18,6 +18,7 @@ import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.HttpMethod; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; @@ -41,6 +42,7 @@ import org.apache.nifi.web.Revision; import org.apache.nifi.web.api.dto.AllowableValueDTO; import org.apache.nifi.web.api.dto.BacklogDTO; +import org.apache.nifi.web.api.dto.BundleDTO; import org.apache.nifi.web.api.dto.ComponentStateDTO; import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; import org.apache.nifi.web.api.dto.ConnectorDTO; @@ -111,6 +113,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @@ -534,6 +537,8 @@ public void testUpdateRunStatus() { assertEquals(responseEntity, response.getEntity()); } + assertNull(requestEntity.getExpectedBundle()); + verify(serviceFacade, never()).getConnector(CONNECTOR_ID); verify(serviceFacade).verifyUpdateConnector(any(ConnectorDTO.class)); verify(serviceFacade).scheduleConnector(any(Revision.class), eq(CONNECTOR_ID), eq(ScheduledState.RUNNING)); } @@ -570,6 +575,49 @@ public void testUpdateRunStatusWithNullRevision() { verify(serviceFacade, never()).scheduleConnector(any(Revision.class), anyString(), any(ScheduledState.class)); } + @Test + public void testUpdateRunStatusReplicateFillsExpectedBundleForClusterStart() { + final ConnectorRunStatusEntity requestEntity = createConnectorRunStatusEntity(); + final ConnectorEntity localConnector = createConnectorEntity(); + final BundleDTO localBundle = new BundleDTO("org.apache.nifi", "nifi-test-nar", "1.0.0"); + localConnector.getComponent().setBundle(localBundle); + final Response replicatedResponse = Response.ok().build(); + + final ConnectorResource spyResource = spy(connectorResource); + doReturn(true).when(spyResource).isReplicateRequest(); + doReturn(ApplicationResource.ReplicationTarget.CLUSTER_NODES).when(spyResource).getReplicationTarget(); + doReturn(replicatedResponse).when(spyResource).replicate(eq(HttpMethod.PUT), any(ConnectorRunStatusEntity.class)); + when(serviceFacade.getConnector(CONNECTOR_ID)).thenReturn(localConnector); + + try (Response response = spyResource.updateRunStatus(CONNECTOR_ID, requestEntity)) { + assertEquals(200, response.getStatus()); + } + + assertEquals(localBundle, requestEntity.getExpectedBundle()); + verify(serviceFacade).getConnector(CONNECTOR_ID); + verify(spyResource).replicate(eq(HttpMethod.PUT), same(requestEntity)); + verify(serviceFacade, never()).scheduleConnector(any(Revision.class), anyString(), any(ScheduledState.class)); + } + + @Test + public void testUpdateRunStatusReplicateDoesNotFillExpectedBundleForStop() { + final ConnectorRunStatusEntity requestEntity = createConnectorRunStatusEntity(); + requestEntity.setState("STOPPED"); + final Response replicatedResponse = Response.ok().build(); + + final ConnectorResource spyResource = spy(connectorResource); + doReturn(true).when(spyResource).isReplicateRequest(); + doReturn(replicatedResponse).when(spyResource).replicate(eq(HttpMethod.PUT), any(ConnectorRunStatusEntity.class)); + + try (Response response = spyResource.updateRunStatus(CONNECTOR_ID, requestEntity)) { + assertEquals(200, response.getStatus()); + } + + assertNull(requestEntity.getExpectedBundle()); + verify(serviceFacade, never()).getConnector(CONNECTOR_ID); + verify(spyResource, never()).getReplicationTarget(); + } + @Test public void testGetConnectorPropertyAllowableValues() { final ConnectorPropertyAllowableValuesEntity responseEntity = createConnectorPropertyAllowableValuesEntity(); diff --git a/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions-nar/pom.xml b/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions-nar/pom.xml index 12943dd3e13f..792d44b84c9c 100644 --- a/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions-nar/pom.xml +++ b/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions-nar/pom.xml @@ -31,6 +31,12 @@ nifi-alternate-config-extensions 2.13.0-SNAPSHOT + + + org.apache.nifi + nifi-connector-upgrade-drain-v2 + 2.13.0-SNAPSHOT + org.apache.nifi nifi-standard-services-api-nar diff --git a/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions/pom.xml b/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions/pom.xml index 40f196f997d5..18deca3c0d87 100644 --- a/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions/pom.xml +++ b/nifi-system-tests/nifi-alternate-config-extensions-bundle/nifi-alternate-config-extensions/pom.xml @@ -33,5 +33,10 @@ nifi-utils 2.13.0-SNAPSHOT + + org.apache.nifi + nifi-connector-common + 2.13.0-SNAPSHOT + \ No newline at end of file diff --git a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions-nar/pom.xml b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions-nar/pom.xml index e3321f2639ee..c9107e2b1a1a 100644 --- a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions-nar/pom.xml +++ b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions-nar/pom.xml @@ -44,6 +44,12 @@ nifi-system-test-extensions 2.13.0-SNAPSHOT + + + org.apache.nifi + nifi-connector-upgrade-drain-v1 + 2.13.0-SNAPSHOT + org.apache.nifi nifi-system-test-extensions-services-api-nar diff --git a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/pom.xml b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/pom.xml index 4bbf6653bbe8..b4e4175d89db 100644 --- a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/pom.xml +++ b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/pom.xml @@ -33,5 +33,15 @@ nifi-utils 2.13.0-SNAPSHOT + + org.apache.nifi + nifi-framework-api + 2.13.0-SNAPSHOT + provided + + + com.fasterxml.jackson.core + jackson-databind + \ No newline at end of file diff --git a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/connectors/tests/system/FileConnectorConfigurationProvider.java b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/connectors/tests/system/FileConnectorConfigurationProvider.java new file mode 100644 index 000000000000..cfe04326193a --- /dev/null +++ b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/connectors/tests/system/FileConnectorConfigurationProvider.java @@ -0,0 +1,157 @@ +/* + * 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.connectors.tests.system; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.nifi.components.connector.ConnectorConfigurationProvider; +import org.apache.nifi.components.connector.ConnectorConfigurationProviderInitializationContext; +import org.apache.nifi.components.connector.ConnectorSyncDirective; +import org.apache.nifi.components.connector.ConnectorWorkingConfiguration; +import org.apache.nifi.flow.VersionedConnectorState; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Optional; + +/** + * File-backed provider used by upgrade-drain system tests. {@code load} and {@code getSyncDirective} return the live + * configuration when present and the committed configuration otherwise. {@code save} writes live configuration and + * {@code discard} removes it. + */ +public class FileConnectorConfigurationProvider implements ConnectorConfigurationProvider { + + public static final String STATE_DIRECTORY_PROPERTY = "state.directory"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private Path stateDirectory; + + @Override + public synchronized void initialize(final ConnectorConfigurationProviderInitializationContext context) { + final String configuredDirectory = context.getProperties().get(STATE_DIRECTORY_PROPERTY); + if (configuredDirectory == null || configuredDirectory.isBlank()) { + throw new IllegalStateException("FileConnectorConfigurationProvider requires " + STATE_DIRECTORY_PROPERTY); + } + stateDirectory = Path.of(configuredDirectory); + try { + Files.createDirectories(stateDirectory); + } catch (final IOException e) { + throw new IllegalStateException("Unable to create provider state directory " + stateDirectory, e); + } + } + + @Override + public synchronized Optional load(final String connectorId) { + return readCurrent(connectorId); + } + + @Override + public synchronized void save(final String connectorId, final ConnectorWorkingConfiguration configuration) { + writeAtomically(liveConfiguration(connectorId), configuration); + } + + @Override + public synchronized void discard(final String connectorId) { + try { + Files.deleteIfExists(liveConfiguration(connectorId)); + } catch (final IOException e) { + throw new IllegalStateException("Unable to discard live configuration for " + connectorId, e); + } + } + + @Override + public synchronized void delete(final String connectorId) { + try { + Files.deleteIfExists(liveConfiguration(connectorId)); + Files.deleteIfExists(committedConfiguration(connectorId)); + } catch (final IOException e) { + throw new IllegalStateException("Unable to delete configuration for " + connectorId, e); + } + } + + @Override + public void verifyCreate(final String connectorId) { + } + + @Override + public synchronized ConnectorSyncDirective getSyncDirective(final String connectorId, final VersionedConnectorState proposedScheduledState) { + return readCurrent(connectorId) + .map(ConnectorSyncDirective::allow) + .orElseGet(ConnectorSyncDirective::allow); + } + + @Override + public void storeAsset(final String connectorId, final String nifiUuid, final String assetName, final InputStream content) { + } + + @Override + public void deleteAsset(final String connectorId, final String nifiUuid) { + } + + @Override + public void syncAssets(final String connectorId) { + } + + private Optional readCurrent(final String connectorId) { + final Path live = liveConfiguration(connectorId); + if (Files.exists(live)) { + return Optional.of(read(live)); + } + final Path committed = committedConfiguration(connectorId); + if (Files.exists(committed)) { + return Optional.of(read(committed)); + } + return Optional.empty(); + } + + private ConnectorWorkingConfiguration read(final Path path) { + try { + return objectMapper.readValue(path.toFile(), ConnectorWorkingConfiguration.class); + } catch (final IOException e) { + throw new IllegalStateException("Unable to read provider configuration " + path, e); + } + } + + private void writeAtomically(final Path path, final ConnectorWorkingConfiguration configuration) { + try { + Files.createDirectories(path.getParent()); + final Path temporary = path.resolveSibling(path.getFileName() + ".tmp"); + objectMapper.writeValue(temporary.toFile(), configuration); + try { + Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (final IOException atomicMoveFailure) { + Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING); + } + } catch (final IOException e) { + throw new IllegalStateException("Unable to write provider configuration " + path, e); + } + } + + private Path liveConfiguration(final String connectorId) { + return connectorDirectory(connectorId).resolve("live-config.json"); + } + + private Path committedConfiguration(final String connectorId) { + return connectorDirectory(connectorId).resolve("committed-config.json"); + } + + private Path connectorDirectory(final String connectorId) { + return stateDirectory.resolve(connectorId); + } +} diff --git a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainGenerate.java b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainGenerate.java new file mode 100644 index 000000000000..f860e67f191a --- /dev/null +++ b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainGenerate.java @@ -0,0 +1,104 @@ +/* + * 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.processors.tests.system; + +import org.apache.nifi.annotation.behavior.Stateful; +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.components.state.Scope; +import org.apache.nifi.components.state.StateMap; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.exception.ProcessException; +import org.apache.nifi.processor.util.StandardValidators; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Generates FlowFiles for connector-upgrade tests. It lives in a NAR that the upgrade swap does not remove, + * so a restored pre-upgrade flow can still run after the connector NAR changes. + */ +@Stateful(scopes = Scope.LOCAL, description = "Stores the number of generated FlowFiles under the key " + UpgradeDrainGenerate.COUNT_KEY) +public class UpgradeDrainGenerate extends AbstractProcessor { + + public static final String COUNT_KEY = "count"; + + public static final PropertyDescriptor FILE_SIZE = new PropertyDescriptor.Builder() + .name("File Size") + .description("Accepted so the upgrade flow's File Size property remains valid. Each FlowFile is one byte.") + .required(false) + .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) + .build(); + + public static final PropertyDescriptor GATE_FILE = new PropertyDescriptor.Builder() + .name("Gate File") + .description("When set, FlowFile generation stops after this file exists.") + .required(false) + .addValidator(StandardValidators.NON_BLANK_VALIDATOR) + .build(); + + public static final PropertyDescriptor SECRET_VALUE = new PropertyDescriptor.Builder() + .name("Secret Value") + .description("Sensitive Parameter reference used to test Connector flow restoration.") + .required(false) + .sensitive(true) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final Relationship SUCCESS = new Relationship.Builder() + .name("success") + .description("Generated FlowFiles") + .build(); + + @Override + protected List getSupportedPropertyDescriptors() { + return List.of(FILE_SIZE, GATE_FILE, SECRET_VALUE); + } + + @Override + public Set getRelationships() { + return Set.of(SUCCESS); + } + + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { + final String gateFilePath = context.getProperty(GATE_FILE).getValue(); + if (gateFilePath != null && new File(gateFilePath).exists()) { + context.yield(); + return; + } + + FlowFile flowFile = session.create(); + flowFile = session.write(flowFile, out -> out.write('x')); + session.transfer(flowFile, SUCCESS); + + try { + final StateMap stateMap = session.getState(Scope.LOCAL); + final String countValue = stateMap.get(COUNT_KEY); + final long count = countValue == null ? 0L : Long.parseLong(countValue); + session.setState(Map.of(COUNT_KEY, String.valueOf(count + 1)), Scope.LOCAL); + } catch (final IOException e) { + throw new ProcessException("Failed to update the generated FlowFile count", e); + } + } +} diff --git a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainRelay.java b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainRelay.java new file mode 100644 index 000000000000..2012240dd43d --- /dev/null +++ b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainRelay.java @@ -0,0 +1,53 @@ +/* + * 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.processors.tests.system; + +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.Relationship; +import org.apache.nifi.processor.exception.ProcessException; + +import java.util.Set; + +/** + * Passes each FlowFile through unchanged. It lives in a NAR that the upgrade swap does not remove, + * so a restored pre-upgrade flow can still move queued FlowFiles after the connector NAR changes. + */ +public class UpgradeDrainRelay extends AbstractProcessor { + + public static final Relationship SUCCESS = new Relationship.Builder() + .name("success") + .description("Relayed FlowFiles") + .build(); + + @Override + public Set getRelationships() { + return Set.of(SUCCESS); + } + + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { + final FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + session.transfer(flowFile, SUCCESS); + } +} diff --git a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainTerminate.java b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainTerminate.java new file mode 100644 index 000000000000..14d7f2354e06 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/java/org/apache/nifi/processors/tests/system/UpgradeDrainTerminate.java @@ -0,0 +1,65 @@ +/* + * 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.processors.tests.system; + +import org.apache.nifi.components.PropertyDescriptor; +import org.apache.nifi.flowfile.FlowFile; +import org.apache.nifi.processor.AbstractProcessor; +import org.apache.nifi.processor.ProcessContext; +import org.apache.nifi.processor.ProcessSession; +import org.apache.nifi.processor.exception.ProcessException; +import org.apache.nifi.processor.util.StandardValidators; + +import java.io.File; +import java.util.List; + +/** + * Drops FlowFiles once an optional gate file exists. It lives in a NAR that the upgrade swap does not remove. + */ +public class UpgradeDrainTerminate extends AbstractProcessor { + + public static final PropertyDescriptor GATE_FILE = new PropertyDescriptor.Builder() + .name("Gate File") + .description("When set, FlowFiles are dropped only after this file exists.") + .required(false) + .addValidator(StandardValidators.NON_BLANK_VALIDATOR) + .build(); + + @Override + protected List getSupportedPropertyDescriptors() { + return List.of(GATE_FILE); + } + + @Override + public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { + final String gateFilePath = context.getProperty(GATE_FILE).getValue(); + if (gateFilePath != null) { + final File gateFile = new File(gateFilePath); + if (!gateFile.exists()) { + context.yield(); + return; + } + } + + final FlowFile flowFile = session.get(); + if (flowFile == null) { + return; + } + + session.remove(flowFile); + } +} diff --git a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.ConnectorConfigurationProvider b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.ConnectorConfigurationProvider new file mode 100644 index 000000000000..0eae0a91882a --- /dev/null +++ b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.ConnectorConfigurationProvider @@ -0,0 +1,16 @@ +# 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. + +org.apache.nifi.connectors.tests.system.FileConnectorConfigurationProvider diff --git a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor index d7be6ee8f3d3..a307ad452b77 100644 --- a/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor +++ b/nifi-system-tests/nifi-system-test-extensions2-bundle/nifi-system-test-extensions2/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor @@ -13,4 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -org.apache.nifi.processors.tests.system.FakeGenericProcessor \ No newline at end of file +org.apache.nifi.processors.tests.system.FakeGenericProcessor +org.apache.nifi.processors.tests.system.UpgradeDrainGenerate +org.apache.nifi.processors.tests.system.UpgradeDrainRelay +org.apache.nifi.processors.tests.system.UpgradeDrainTerminate \ No newline at end of file diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1-nar/pom.xml b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1-nar/pom.xml new file mode 100644 index 000000000000..e8494ccbe541 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1-nar/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + + org.apache.nifi + nifi-system-test-nar-provider-bundles + 2.13.0-SNAPSHOT + + + nifi-connector-upgrade-drain-v1-nar + nar + + + + org.apache.nifi + nifi-connector-upgrade-drain-v1 + 2.13.0-SNAPSHOT + + + org.apache.nifi + nifi-standard-services-api-nar + 2.13.0-SNAPSHOT + nar + + + + + + + org.apache.nifi + nifi-nar-maven-plugin + + false + nifi-connector-upgrade-drain-nar + 1.0.0 + + + + + diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/pom.xml b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/pom.xml new file mode 100644 index 000000000000..42499a10ec1d --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/pom.xml @@ -0,0 +1,45 @@ + + + + 4.0.0 + + + org.apache.nifi + nifi-system-test-nar-provider-bundles + 2.13.0-SNAPSHOT + + + nifi-connector-upgrade-drain-v1 + jar + + + + org.apache.nifi + nifi-api + provided + + + org.apache.nifi + nifi-utils + 2.13.0-SNAPSHOT + + + org.apache.nifi + nifi-connector-common + 2.13.0-SNAPSHOT + + + diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java new file mode 100644 index 000000000000..c9e34913ddc7 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java @@ -0,0 +1,240 @@ +/* + * 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.connectors.tests.system; + +import org.apache.nifi.components.ConfigVerificationResult; +import org.apache.nifi.components.connector.AbstractConnector; +import org.apache.nifi.components.connector.BundleCompatibility; +import org.apache.nifi.components.connector.ConfigurationStep; +import org.apache.nifi.components.connector.ConnectorPropertyDescriptor; +import org.apache.nifi.components.connector.ConnectorPropertyGroup; +import org.apache.nifi.components.connector.FlowUpdateException; +import org.apache.nifi.components.connector.PropertyType; +import org.apache.nifi.components.connector.components.FlowContext; +import org.apache.nifi.components.connector.util.VersionedFlowUtils; +import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.Position; +import org.apache.nifi.flow.VersionedConnection; +import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.flow.VersionedProcessor; +import org.apache.nifi.processor.util.StandardValidators; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Pre-upgrade connector. Its flow queues FlowFiles on a connection that the version 2 connector removes. + */ +public class UpgradeDrainConnector extends AbstractConnector { + + public static final String GATE_FILE_PATH_NAME = "Gate File Path"; + public static final String EVOLUTION_MODE_NAME = "Evolution Mode"; + public static final String REMOVE_CONNECTION_NAME = "Remove Connection"; + public static final String COMMENT_NAME = "Comment"; + public static final String UPGRADE_SECRET_NAME = "Upgrade Secret"; + public static final String REMOVED_CONNECTION_NAME = "Removed Connection"; + + static final ConnectorPropertyDescriptor GATE_FILE_PATH = new ConnectorPropertyDescriptor.Builder() + .name(GATE_FILE_PATH_NAME) + .description("Relative path of the file that lets the terminating processor run.") + .required(true) + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor EVOLUTION_MODE = new ConnectorPropertyDescriptor.Builder() + .name(EVOLUTION_MODE_NAME) + .description("How the upgraded connector handles removed connections.") + .required(true) + .defaultValue("DRAIN") + .allowableValues("DRAIN", "INHERITED_DRAIN", "NO_OP") + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor REMOVE_CONNECTION = new ConnectorPropertyDescriptor.Builder() + .name(REMOVE_CONNECTION_NAME) + .description("When true, the upgraded flow drops the connection that queues generated FlowFiles.") + .required(true) + .defaultValue("true") + .allowableValues("true", "false") + .type(PropertyType.STRING) + .addValidator(StandardValidators.BOOLEAN_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor COMMENT = new ConnectorPropertyDescriptor.Builder() + .name(COMMENT_NAME) + .description("Comment copied onto the generating processor.") + .required(false) + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor UPGRADE_SECRET = new ConnectorPropertyDescriptor.Builder() + .name(UPGRADE_SECRET_NAME) + .description("Secret copied into the managed Parameter Context for upgrade restoration tests.") + .required(false) + .type(PropertyType.SECRET) + .build(); + + public static final String LEGACY_NOTE_NAME = "Legacy Note"; + + static final ConnectorPropertyDescriptor LEGACY_NOTE = new ConnectorPropertyDescriptor.Builder() + .name(LEGACY_NOTE_NAME) + .description("Optional note retained only by this version.") + .required(false) + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + public static final String REMOVED_PROCESSOR_CHAIN_NAME = "Removed Processor Chain"; + + static final ConnectorPropertyDescriptor REMOVED_PROCESSOR_CHAIN = new ConnectorPropertyDescriptor.Builder() + .name(REMOVED_PROCESSOR_CHAIN_NAME) + .description("When true, generated FlowFiles queue on the connection from a processor the upgrade removes to the terminator that stays.") + .required(false) + .defaultValue("false") + .allowableValues("true", "false") + .type(PropertyType.STRING) + .addValidator(StandardValidators.BOOLEAN_VALIDATOR) + .build(); + + private static final ConnectorPropertyGroup PROPERTY_GROUP = new ConnectorPropertyGroup.Builder() + .name("Upgrade") + .addProperty(GATE_FILE_PATH) + .addProperty(EVOLUTION_MODE) + .addProperty(REMOVE_CONNECTION) + .addProperty(COMMENT) + .addProperty(UPGRADE_SECRET) + .addProperty(LEGACY_NOTE) + .addProperty(REMOVED_PROCESSOR_CHAIN) + .build(); + + private static final ConfigurationStep CONFIG_STEP = new ConfigurationStep.Builder() + .name("Upgrade") + .propertyGroups(List.of(PROPERTY_GROUP)) + .build(); + + private static final Bundle GATE_BUNDLE = new Bundle("org.apache.nifi", "nifi-system-test-extensions2-nar", "2.13.0-SNAPSHOT"); + private static final String ROOT_GROUP_ID = "upgrade-drain-root"; + private static final String GENERATE_TYPE = "org.apache.nifi.processors.tests.system.UpgradeDrainGenerate"; + private static final String RELAY_TYPE = "org.apache.nifi.processors.tests.system.UpgradeDrainRelay"; + private static final String TERMINATE_TYPE = "org.apache.nifi.processors.tests.system.UpgradeDrainTerminate"; + + @Override + protected void onStepConfigured(final String stepName, final FlowContext workingContext) { + } + + @Override + public VersionedExternalFlow getInitialFlow() { + return buildFlow(null); + } + + @Override + public VersionedExternalFlow getActiveFlow(final FlowContext flowContext) { + return buildFlow(flowContext); + } + + @Override + public List getConfigurationSteps() { + return List.of(CONFIG_STEP); + } + + @Override + public List verifyConfigurationStep(final String stepName, final Map overrides, final FlowContext flowContext) { + return List.of(); + } + + @Override + public void applyUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException { + getInitializationContext().updateFlow(activeContext, buildFlow(workingContext), BundleCompatibility.RESOLVE_BUNDLE); + } + + private VersionedExternalFlow buildFlow(final FlowContext flowContext) { + final VersionedProcessGroup rootGroup = VersionedFlowUtils.createProcessGroup(ROOT_GROUP_ID, "Upgrade Drain"); + final VersionedProcessor generate = VersionedFlowUtils.addProcessor(rootGroup, GENERATE_TYPE, GATE_BUNDLE, "GenerateFlowFile", new Position(0, 0)); + generate.getProperties().put("File Size", "1 B"); + generate.setSchedulingPeriod("100 millis"); + final String gateFile = property(flowContext, GATE_FILE_PATH); + if (gateFile != null) { + generate.getProperties().put("Gate File", gateFile); + } + + final String comment = property(flowContext, COMMENT); + if (comment != null && !comment.isBlank()) { + generate.setComments(comment); + } + + // Identifiers are assigned by how many components of that type already exist. Generate and Terminate are added + // first, in both versions, so they keep their identifiers. The relay and the removed processor come after them. + // The queued connection is added last so the upgraded flow, which creates only two connections, does not reuse + // its identifier. That connection is deleted, and a non-empty queue there requires a drain. + final boolean removedProcessorChain = Boolean.parseBoolean(property(flowContext, REMOVED_PROCESSOR_CHAIN)); + final Position terminatePosition = removedProcessorChain ? new Position(1200, 0) : new Position(400, 0); + final VersionedProcessor terminate = VersionedFlowUtils.addProcessor(rootGroup, TERMINATE_TYPE, GATE_BUNDLE, "TerminateFlowFile", terminatePosition); + if (gateFile != null) { + terminate.getProperties().put("Gate File", gateFile); + } + + if (removedProcessorChain) { + final VersionedProcessor relay = VersionedFlowUtils.addProcessor(rootGroup, RELAY_TYPE, GATE_BUNDLE, "RelayFlowFile", new Position(400, 0)); + final VersionedProcessor removed = VersionedFlowUtils.addProcessor(rootGroup, RELAY_TYPE, GATE_BUNDLE, "RemovedFlowFile", new Position(800, 0)); + final VersionedConnection relayInput = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(generate), + VersionedFlowUtils.createConnectableComponent(relay), Set.of("success")); + relayInput.setName("Relay Input Connection"); + final VersionedConnection removedInput = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(relay), + VersionedFlowUtils.createConnectableComponent(removed), Set.of("success")); + removedInput.setName("Removed Input Connection"); + final VersionedConnection queued = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(removed), + VersionedFlowUtils.createConnectableComponent(terminate), Set.of("success")); + queued.setName(REMOVED_CONNECTION_NAME); + } else { + final VersionedConnection connection = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(generate), + VersionedFlowUtils.createConnectableComponent(terminate), Set.of("success")); + connection.setName(REMOVED_CONNECTION_NAME); + } + + final VersionedExternalFlow flow = new VersionedExternalFlow(); + flow.setFlowContents(rootGroup); + final String upgradeSecret = property(flowContext, UPGRADE_SECRET); + if (upgradeSecret != null) { + generate.getProperties().put("Secret Value", "#{" + UPGRADE_SECRET_NAME + "}"); + final VersionedParameter parameter = new VersionedParameter(); + parameter.setName(UPGRADE_SECRET_NAME); + parameter.setSensitive(true); + parameter.setValue(upgradeSecret); + final VersionedParameterContext parameterContext = new VersionedParameterContext(); + parameterContext.setName("Upgrade Drain Parameters"); + parameterContext.setParameters(Set.of(parameter)); + rootGroup.setParameterContextName(parameterContext.getName()); + flow.setParameterContexts(Map.of(parameterContext.getName(), parameterContext)); + } + return flow; + } + + private static String property(final FlowContext flowContext, final ConnectorPropertyDescriptor descriptor) { + if (flowContext == null) { + return descriptor.getDefaultValue(); + } + final String value = flowContext.getConfigurationContext().getProperty(CONFIG_STEP, descriptor).getValue(); + return value == null ? descriptor.getDefaultValue() : value; + } +} diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector new file mode 100644 index 000000000000..ce8ca264fe13 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v1/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector @@ -0,0 +1,15 @@ +# 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. +org.apache.nifi.connectors.tests.system.UpgradeDrainConnector diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2-nar/pom.xml b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2-nar/pom.xml new file mode 100644 index 000000000000..89fbe6ccf253 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2-nar/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + + org.apache.nifi + nifi-system-test-nar-provider-bundles + 2.13.0-SNAPSHOT + + + nifi-connector-upgrade-drain-v2-nar + nar + + + + org.apache.nifi + nifi-connector-upgrade-drain-v2 + 2.13.0-SNAPSHOT + + + org.apache.nifi + nifi-standard-services-api-nar + 2.13.0-SNAPSHOT + nar + + + + + + + org.apache.nifi + nifi-nar-maven-plugin + + false + nifi-connector-upgrade-drain-nar + 2.0.0 + + + + + diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/pom.xml b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/pom.xml new file mode 100644 index 000000000000..385236b47f84 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/pom.xml @@ -0,0 +1,45 @@ + + + + 4.0.0 + + + org.apache.nifi + nifi-system-test-nar-provider-bundles + 2.13.0-SNAPSHOT + + + nifi-connector-upgrade-drain-v2 + jar + + + + org.apache.nifi + nifi-api + provided + + + org.apache.nifi + nifi-utils + 2.13.0-SNAPSHOT + + + org.apache.nifi + nifi-connector-common + 2.13.0-SNAPSHOT + + + diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java new file mode 100644 index 000000000000..2a872183aa8f --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/java/org/apache/nifi/connectors/tests/system/UpgradeDrainConnector.java @@ -0,0 +1,339 @@ +/* + * 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.connectors.tests.system; + +import org.apache.nifi.components.ConfigVerificationResult; +import org.apache.nifi.components.connector.AbstractConnector; +import org.apache.nifi.components.connector.BundleCompatibility; +import org.apache.nifi.components.connector.ConfigurationStep; +import org.apache.nifi.components.connector.ConnectorPropertyDescriptor; +import org.apache.nifi.components.connector.ConnectorPropertyGroup; +import org.apache.nifi.components.connector.FlowEvolutionContext; +import org.apache.nifi.components.connector.FlowUpdateException; +import org.apache.nifi.components.connector.PropertyType; +import org.apache.nifi.components.connector.components.FlowContext; +import org.apache.nifi.components.connector.components.ProcessGroupFacade; +import org.apache.nifi.components.connector.components.ProcessorFacade; +import org.apache.nifi.components.connector.util.VersionedFlowUtils; +import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.Position; +import org.apache.nifi.flow.VersionedConnection; +import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.flow.VersionedProcessor; +import org.apache.nifi.processor.util.StandardValidators; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +/** + * Post-upgrade connector. It drops the pre-upgrade queue connection unless configured to keep or rewire it. + */ +public class UpgradeDrainConnector extends AbstractConnector { + + static final ConnectorPropertyDescriptor GATE_FILE_PATH = new ConnectorPropertyDescriptor.Builder() + .name("Gate File Path") + .description("Relative path of the file that lets the terminating processor run.") + .required(true) + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor EVOLUTION_MODE = new ConnectorPropertyDescriptor.Builder() + .name("Evolution Mode") + .description("How this connector handles connections removed by the upgrade.") + .required(true) + .defaultValue("DRAIN") + .allowableValues("DRAIN", "INHERITED_DRAIN", "NO_OP") + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor REMOVE_CONNECTION = new ConnectorPropertyDescriptor.Builder() + .name("Remove Connection") + .description("When true, the upgraded flow drops the connection that queues generated FlowFiles.") + .required(true) + .defaultValue("true") + .allowableValues("true", "false") + .type(PropertyType.STRING) + .addValidator(StandardValidators.BOOLEAN_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor COMMENT = new ConnectorPropertyDescriptor.Builder() + .name("Comment") + .description("Comment copied onto the generating processor.") + .required(false) + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor UPGRADE_SECRET = new ConnectorPropertyDescriptor.Builder() + .name("Upgrade Secret") + .description("Secret copied into the managed Parameter Context for upgrade restoration tests.") + .required(false) + .type(PropertyType.SECRET) + .build(); + + public static final String DRAIN_LABEL_NAME = "Drain Label"; + + static final ConnectorPropertyDescriptor DRAIN_LABEL = new ConnectorPropertyDescriptor.Builder() + .name(DRAIN_LABEL_NAME) + .description("Label added by the upgraded connector.") + .required(true) + .defaultValue("upgraded") + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor REMOVED_PROCESSOR_CHAIN = new ConnectorPropertyDescriptor.Builder() + .name("Removed Processor Chain") + .description("When true, the upgraded flow replaces the first middle processor and removes the next one.") + .required(false) + .defaultValue("false") + .allowableValues("true", "false") + .type(PropertyType.STRING) + .addValidator(StandardValidators.BOOLEAN_VALIDATOR) + .build(); + + static final ConnectorPropertyDescriptor REWIRED_ENDPOINT = new ConnectorPropertyDescriptor.Builder() + .name("Rewired Endpoint") + .description("When the upgraded flow keeps the queued pre-upgrade connection, which of its endpoints moves to a new relay processor.") + .required(false) + .defaultValue("NONE") + .allowableValues("NONE", "SOURCE", "DESTINATION") + .type(PropertyType.STRING) + .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) + .build(); + + private static final ConnectorPropertyGroup PROPERTY_GROUP = new ConnectorPropertyGroup.Builder() + .name("Upgrade") + .addProperty(GATE_FILE_PATH) + .addProperty(EVOLUTION_MODE) + .addProperty(REMOVE_CONNECTION) + .addProperty(COMMENT) + .addProperty(UPGRADE_SECRET) + .addProperty(DRAIN_LABEL) + .addProperty(REMOVED_PROCESSOR_CHAIN) + .addProperty(REWIRED_ENDPOINT) + .build(); + + private static final ConfigurationStep CONFIG_STEP = new ConfigurationStep.Builder() + .name("Upgrade") + .propertyGroups(List.of(PROPERTY_GROUP)) + .build(); + + private static final Bundle GATE_BUNDLE = new Bundle("org.apache.nifi", "nifi-system-test-extensions2-nar", "2.13.0-SNAPSHOT"); + private static final String ROOT_GROUP_ID = "upgrade-drain-root"; + private static final String GENERATE_TYPE = "org.apache.nifi.processors.tests.system.UpgradeDrainGenerate"; + private static final String RELAY_TYPE = "org.apache.nifi.processors.tests.system.UpgradeDrainRelay"; + private static final String TERMINATE_TYPE = "org.apache.nifi.processors.tests.system.UpgradeDrainTerminate"; + private static final String SWAPPED_PROCESSOR_ID = "upgrade-drain-swapped-processor"; + + @Override + protected void onStepConfigured(final String stepName, final FlowContext workingContext) { + } + + @Override + public VersionedExternalFlow getInitialFlow() { + return buildFlow(null); + } + + @Override + public VersionedExternalFlow getActiveFlow(final FlowContext flowContext) { + final String activeFlowSwitch = readSwitch("upgrade-drain-active-flow.txt"); + if ("NULL".equals(activeFlowSwitch)) { + return null; + } + if ("THROW".equals(activeFlowSwitch)) { + throw new IllegalStateException("active flow failed"); + } + return buildFlow(flowContext); + } + + @Override + public List getConfigurationSteps() { + return List.of(CONFIG_STEP); + } + + @Override + public List verifyConfigurationStep(final String stepName, final Map overrides, final FlowContext flowContext) { + return List.of(); + } + + @Override + public void applyUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException { + if (Files.exists(Path.of("upgrade-drain-apply-fail.txt"))) { + throw new FlowUpdateException("apply failed"); + } + + getInitializationContext().updateFlow(activeContext, buildFlow(workingContext), BundleCompatibility.RESOLVE_BUNDLE); + } + + @Override + public CompletableFuture prepareForFlowEvolution(final FlowEvolutionContext context) throws FlowUpdateException { + final String preparationResult = readSwitch("upgrade-drain-preparation-result.txt"); + if ("NULL_FUTURE".equals(preparationResult)) { + return null; + } + if ("FAILED_FUTURE".equals(preparationResult)) { + return CompletableFuture.failedFuture(new FlowUpdateException("flow evolution preparation failed")); + } + if ("UPDATE_PRE_UPGRADE_FLOW".equals(preparationResult)) { + final FlowContext preUpgradeContext = context.getPreUpgradeActiveFlowContext(); + getInitializationContext().updateFlow(preUpgradeContext, buildFlow(preUpgradeContext), BundleCompatibility.RESOLVE_BUNDLE); + return CompletableFuture.completedFuture(null); + } + + final String mode = property(context.getPreUpgradeActiveFlowContext(), EVOLUTION_MODE); + if ("INHERITED_DRAIN".equals(mode)) { + return drainFlowFiles(context.getPreUpgradeActiveFlowContext()); + } else if ("DRAIN".equals(mode)) { + // Start everything except the generator. Starting the generator as well refills the queue faster than it can empty. + final ProcessGroupFacade rootGroup = context.getPreUpgradeActiveFlowContext().getRootGroup(); + try { + for (final ProcessorFacade processor : rootGroup.getProcessors()) { + if (!"GenerateFlowFile".equals(processor.getDefinition().getName())) { + processor.getLifecycle().start().get(); + } + } + } catch (final Exception e) { + throw new FlowUpdateException("Failed to start the pre-upgrade flow so its queues can drain", e); + } + + while (rootGroup.getConnections().stream().anyMatch(connection -> connection.getQueueSize().getObjectCount() > 0)) { + try { + Thread.sleep(200L); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new FlowUpdateException("Flow evolution was interrupted", e); + } + } + } + + return CompletableFuture.completedFuture(null); + } + + private VersionedExternalFlow buildFlow(final FlowContext flowContext) { + final VersionedProcessGroup rootGroup = VersionedFlowUtils.createProcessGroup(ROOT_GROUP_ID, "Upgrade Drain"); + final VersionedProcessor generate = VersionedFlowUtils.addProcessor(rootGroup, GENERATE_TYPE, GATE_BUNDLE, "GenerateFlowFile", new Position(0, 0)); + generate.getProperties().put("File Size", "1 B"); + generate.setSchedulingPeriod("100 millis"); + final String gateFile = property(flowContext, GATE_FILE_PATH); + if (gateFile != null) { + generate.getProperties().put("Gate File", gateFile); + } + + final String comment = property(flowContext, COMMENT); + if (comment != null && !comment.isBlank()) { + generate.setComments(comment); + } + + final boolean removedProcessorChain = Boolean.parseBoolean(property(flowContext, REMOVED_PROCESSOR_CHAIN)); + if (removedProcessorChain) { + // Terminate is added before the swapped processor so it keeps the pre-upgrade identifier. The swapped + // processor would otherwise receive the relay's count-based identifier and the relay would be renamed + // instead of replaced. Only two connections are created, so the queued pre-upgrade connection is deleted. + final VersionedProcessor terminate = VersionedFlowUtils.addProcessor(rootGroup, TERMINATE_TYPE, GATE_BUNDLE, "TerminateFlowFile", new Position(800, 0)); + if (gateFile != null) { + terminate.getProperties().put("Gate File", gateFile); + } + + final VersionedProcessor swapped = VersionedFlowUtils.addProcessor(rootGroup, RELAY_TYPE, GATE_BUNDLE, "SwappedFlowFile", new Position(400, 0)); + swapped.setIdentifier(SWAPPED_PROCESSOR_ID); + final VersionedConnection swappedInput = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(generate), + VersionedFlowUtils.createConnectableComponent(swapped), Set.of("success")); + swappedInput.setName("Swapped Input Connection"); + final VersionedConnection swappedOutput = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(swapped), + VersionedFlowUtils.createConnectableComponent(terminate), Set.of("success")); + swappedOutput.setName("Swapped Output Connection"); + } else { + final boolean removeConnection = flowContext == null || Boolean.parseBoolean(property(flowContext, REMOVE_CONNECTION)); + if (removeConnection) { + generate.setAutoTerminatedRelationships(Set.of("success")); + } else { + final VersionedProcessor terminate = VersionedFlowUtils.addProcessor(rootGroup, TERMINATE_TYPE, GATE_BUNDLE, "TerminateFlowFile", new Position(400, 0)); + if (gateFile != null) { + terminate.getProperties().put("Gate File", gateFile); + } + + final String rewiredEndpoint = property(flowContext, REWIRED_ENDPOINT); + final VersionedConnection connection; + if ("NONE".equals(rewiredEndpoint)) { + connection = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(generate), + VersionedFlowUtils.createConnectableComponent(terminate), Set.of("success")); + } else { + // Connection identifiers are assigned by count, so the rewired connection is added first to keep the identifier + // of the queued pre-upgrade connection. + final VersionedProcessor relay = VersionedFlowUtils.addProcessor(rootGroup, RELAY_TYPE, GATE_BUNDLE, "RelayFlowFile", new Position(400, 200)); + if ("SOURCE".equals(rewiredEndpoint)) { + connection = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(relay), + VersionedFlowUtils.createConnectableComponent(terminate), Set.of("success")); + VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(generate), + VersionedFlowUtils.createConnectableComponent(relay), Set.of("success")).setName("Relay Input Connection"); + } else { + connection = VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(generate), + VersionedFlowUtils.createConnectableComponent(relay), Set.of("success")); + VersionedFlowUtils.addConnection(rootGroup, VersionedFlowUtils.createConnectableComponent(relay), + VersionedFlowUtils.createConnectableComponent(terminate), Set.of("success")).setName("Relay Output Connection"); + } + } + + connection.setName("Removed Connection"); + } + } + + final VersionedExternalFlow flow = new VersionedExternalFlow(); + flow.setFlowContents(rootGroup); + final String upgradeSecret = property(flowContext, UPGRADE_SECRET); + if (upgradeSecret != null) { + generate.getProperties().put("Secret Value", "#{" + UPGRADE_SECRET.getName() + "}"); + final VersionedParameter parameter = new VersionedParameter(); + parameter.setName(UPGRADE_SECRET.getName()); + parameter.setSensitive(true); + parameter.setValue(upgradeSecret); + final VersionedParameterContext parameterContext = new VersionedParameterContext(); + parameterContext.setName("Upgrade Drain Parameters"); + parameterContext.setParameters(Set.of(parameter)); + rootGroup.setParameterContextName(parameterContext.getName()); + flow.setParameterContexts(Map.of(parameterContext.getName(), parameterContext)); + } + return flow; + } + + private static String property(final FlowContext flowContext, final ConnectorPropertyDescriptor descriptor) { + if (flowContext == null) { + return descriptor.getDefaultValue(); + } + final String value = flowContext.getConfigurationContext().getProperty(CONFIG_STEP, descriptor).getValue(); + return value == null ? descriptor.getDefaultValue() : value; + } + + private static String readSwitch(final String fileName) { + try { + return Files.exists(Path.of(fileName)) ? Files.readString(Path.of(fileName)).trim() : null; + } catch (final IOException e) { + throw new IllegalStateException("Failed to read " + fileName, e); + } + } +} diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector new file mode 100644 index 000000000000..ce8ca264fe13 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/nifi-connector-upgrade-drain-v2/src/main/resources/META-INF/services/org.apache.nifi.components.connector.Connector @@ -0,0 +1,15 @@ +# 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. +org.apache.nifi.connectors.tests.system.UpgradeDrainConnector diff --git a/nifi-system-tests/nifi-system-test-nar-provider-bundles/pom.xml b/nifi-system-tests/nifi-system-test-nar-provider-bundles/pom.xml index 745d7767389a..60b18daf4ae5 100644 --- a/nifi-system-tests/nifi-system-test-nar-provider-bundles/pom.xml +++ b/nifi-system-tests/nifi-system-test-nar-provider-bundles/pom.xml @@ -34,6 +34,10 @@ nifi-connector-change-version-v1-nar nifi-connector-change-version-v2 nifi-connector-change-version-v2-nar + nifi-connector-upgrade-drain-v1 + nifi-connector-upgrade-drain-v1-nar + nifi-connector-upgrade-drain-v2 + nifi-connector-upgrade-drain-v2-nar nifi-nar-provider-assembly diff --git a/nifi-system-tests/nifi-system-test-suite/pom.xml b/nifi-system-tests/nifi-system-test-suite/pom.xml index 5f3eec58a89b..46e6a13c499e 100644 --- a/nifi-system-tests/nifi-system-test-suite/pom.xml +++ b/nifi-system-tests/nifi-system-test-suite/pom.xml @@ -136,6 +136,31 @@ + + copy-connector-upgrade-drain-nars + + copy + + pre-integration-test + + ${project.build.directory}/nifi-connector-upgrade-drain-nars + true + + + org.apache.nifi + nifi-connector-upgrade-drain-v1-nar + ${project.version} + nar + + + org.apache.nifi + nifi-connector-upgrade-drain-v2-nar + ${project.version} + nar + + + + @@ -440,6 +465,18 @@ 2.13.0-SNAPSHOT nar + + org.apache.nifi + nifi-connector-upgrade-drain-v1-nar + 2.13.0-SNAPSHOT + nar + + + org.apache.nifi + nifi-connector-upgrade-drain-v2-nar + 2.13.0-SNAPSHOT + nar + diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/AbstractNarSwapMigrationIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/AbstractNarSwapMigrationIT.java index 6c46cc3b10b9..4339411c237a 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/AbstractNarSwapMigrationIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/AbstractNarSwapMigrationIT.java @@ -26,6 +26,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -35,11 +37,15 @@ * Base class for system tests that exercise a component's migration path by swapping the * {@code nifi-system-test-extensions} NARs for the {@code nifi-alternate-config-extensions} NAR between the * pre-migration setup phase and the assertion phase. Subclasses call {@link #switchOutNars()} once NiFi has been - * stopped for the migration boundary, and this class restores the original layout via {@link #switchNarsBack()} in - * an {@link AfterEach} hook so subsequent tests see the default NAR set. + * stopped for the migration boundary. By default the environment is destroyed after each test, so the next test + * starts from a fresh copy of the assembly and no restore is needed. Subclasses that keep their environment between + * tests have the original layout restored via {@link #switchNarsBack()} in an {@link AfterEach} hook, followed by a + * restart, so subsequent tests see the default NAR set. */ public abstract class AbstractNarSwapMigrationIT extends NiFiSystemIT { + private boolean narsSwapped; + @Override protected boolean isAllowFactoryReuse() { return false; @@ -50,18 +56,43 @@ protected boolean isDestroyEnvironmentAfterEachTest() { return true; } + @Override + protected boolean isDestroyFlowAfterEachTest() { + // A destroyed environment may be left stopped, and its flow is discarded with it + return !isDestroyEnvironmentAfterEachTest(); + } + @AfterEach public void restoreNars() { + // The next test builds a fresh environment from the assembly, so a destroyed environment needs no restore + if (isDestroyEnvironmentAfterEachTest()) { + narsSwapped = false; + return; + } + + if (!narsSwapped && getNiFiInstance().isAccessible()) { + return; + } + // Stop the NiFi instance, ensure that the nifi-system-test-extensions-nar and nifi-alternate-config-extensions bundles // are where they need to be. Then, restart the instance so that everything is in the right state for the next test that // will run getNiFiInstance().stop(); - switchNarsBack(); + if (narsSwapped) { + switchNarsBack(); + narsSwapped = false; + } getNiFiInstance().start(true); } protected void switchOutNars() throws IOException { - final File instanceDir = getNiFiInstance().getInstanceDirectory(); + narsSwapped = true; + for (final File instanceDir : instanceDirectories()) { + switchOutNars(instanceDir); + } + } + + private void switchOutNars(final File instanceDir) throws IOException { final File lib = new File(instanceDir, "lib"); final File alternateConfig = new File(lib, "alternate-config"); @@ -81,9 +112,17 @@ protected void switchOutNars() throws IOException { } protected void switchNarsBack() { - final File instanceDir = getNiFiInstance().getInstanceDirectory(); + for (final File instanceDir : instanceDirectories()) { + switchNarsBack(instanceDir); + } + } + + private void switchNarsBack(final File instanceDir) { final File lib = new File(instanceDir, "lib"); final File alternateConfig = new File(lib, "alternate-config"); + if (findFile(lib, "nifi-system-test-extensions-nar-.*") != null) { + return; + } // Move the nifi-system-test-extensions-nar back to the lib directory moveNars(alternateConfig, "nifi-system-test-extensions-nar-.*", lib); @@ -97,6 +136,23 @@ protected void switchNarsBack() { moveNars(lib, "nifi-alternate-config.*", alternateConfig); } + /** + * Standalone instances report a single directory. A cluster's aggregate instance has no directory of its own, + * so callers have to visit each node. + */ + protected List instanceDirectories() { + final NiFiInstance instance = getNiFiInstance(); + if (instance.getNumberOfNodes() <= 1) { + return List.of(instance.getInstanceDirectory()); + } + + final List directories = new ArrayList<>(); + for (int nodeIndex = 1; nodeIndex <= instance.getNumberOfNodes(); nodeIndex++) { + directories.add(instance.getNodeInstance(nodeIndex).getInstanceDirectory()); + } + return directories; + } + private void deleteRecursively(final File file) throws IOException { Files.walkFileTree(file.toPath(), new FileVisitor<>() { @Override diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java new file mode 100644 index 000000000000..ffb2ae33998b --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java @@ -0,0 +1,66 @@ +/* + * 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; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.nifi.controller.flow.VersionedDataflow; +import org.apache.nifi.flow.VersionedConnector; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.GZIPInputStream; + +/** + * Reads connector sections of a stopped node's conf/flow.json.gz. + */ +public final class FlowDefinitionFiles { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private FlowDefinitionFiles() { + } + + public static VersionedConnector readConnector(final NiFiInstance node, final String connectorId) throws IOException { + final VersionedDataflow dataflow = read(flowFile(node)); + return find(dataflow, connectorId); + } + + private static VersionedConnector find(final VersionedDataflow dataflow, final String connectorId) { + if (dataflow.getConnectors() == null) { + throw new IllegalStateException("flow.json.gz has no connectors"); + } + for (final VersionedConnector connector : dataflow.getConnectors()) { + if (connectorId.equals(connector.getInstanceIdentifier())) { + return connector; + } + } + throw new IllegalStateException("flow.json.gz has no connector " + connectorId); + } + + private static File flowFile(final NiFiInstance node) { + return new File(new File(node.getInstanceDirectory(), "conf"), "flow.json.gz"); + } + + private static VersionedDataflow read(final File flowFile) throws IOException { + try (InputStream fileIn = new FileInputStream(flowFile); + InputStream gzipIn = new GZIPInputStream(fileIn)) { + return OBJECT_MAPPER.readValue(gzipIn, VersionedDataflow.class); + } + } +} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/NiFiClientUtil.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/NiFiClientUtil.java index fc5cbc3b8a90..9aa6e3ba4091 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/NiFiClientUtil.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/NiFiClientUtil.java @@ -44,6 +44,7 @@ import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; import org.apache.nifi.web.api.dto.ConnectableDTO; import org.apache.nifi.web.api.dto.ConnectionDTO; +import org.apache.nifi.web.api.dto.ConnectorActionDTO; import org.apache.nifi.web.api.dto.ConnectorDTO; import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO; import org.apache.nifi.web.api.dto.ControllerServiceDTO; @@ -659,6 +660,24 @@ public void waitForConnectorState(final String connectorId, final ConnectorState } } + /** + * Returns the reason the given action is not allowed for the Connector, or null if the action is allowed or not listed. + */ + public String getConnectorActionReasonNotAllowed(final String connectorId, final String actionName) throws NiFiClientException, IOException { + final List actions = getConnectorClient().getConnector(connectorId).getComponent().getAvailableActions(); + if (actions == null) { + return null; + } + + for (final ConnectorActionDTO action : actions) { + if (actionName.equals(action.getName()) && !Boolean.TRUE.equals(action.getAllowed())) { + return action.getReasonNotAllowed(); + } + } + + return null; + } + public void waitForAssetRemoved(final String connectorId, final String assetId) throws NiFiClientException, IOException, InterruptedException { int iteration = 0; diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java new file mode 100644 index 000000000000..a5cf82e6eece --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java @@ -0,0 +1,98 @@ +/* + * 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.connectors; + +import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.components.connector.FlowEvolutionStatus; +import org.apache.nifi.tests.system.nar.NarUploadUtil; +import org.apache.nifi.toolkit.client.NiFiClientException; +import org.apache.nifi.web.api.entity.NarSummaryEntity; +import org.junit.jupiter.api.BeforeEach; + +import java.io.IOException; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Version-change test support. + */ +public abstract class AbstractChangeVersionDrainIT extends AbstractConnectorUpgradeDrainIT { + + @Override + protected boolean isAllowFactoryReuse() { + return true; + } + + @Override + protected boolean isDestroyEnvironmentAfterEachTest() { + return false; + } + + @BeforeEach + public void uploadDrainVersions() throws Exception { + uploadDrainNars(DRAIN_V1, DRAIN_V2); + } + + /** + * Deletes the uploaded NARs along with the flow, because the reused instance is shared with tests that expect no uploaded NARs. + */ + @Override + protected void destroyFlow() throws NiFiClientException, IOException, InterruptedException { + super.destroyFlow(); + + final NarUploadUtil narUploadUtil = new NarUploadUtil(getNifiClient()); + for (final NarSummaryEntity nar : getNifiClient().getControllerClient().getNarSummaries().getNarSummaries()) { + narUploadUtil.deleteNar(nar.getNarSummary()); + } + } + + @Override + protected String createOutgoingConnector(final Map properties) throws Exception { + return createDrainConnector(DRAIN_V1, properties); + } + + @Override + protected void triggerUpgrade(final String connectorId) throws Exception { + changeVersion(connectorId, DRAIN_V2); + } + + @Override + protected ExpectedBundle outgoingBundle() { + return new ExpectedBundle(DRAIN_BUNDLE_ARTIFACT, DRAIN_V1); + } + + @Override + protected ExpectedBundle incomingBundle() { + return new ExpectedBundle(DRAIN_BUNDLE_ARTIFACT, DRAIN_V2); + } + + protected void assertFlowEvolutionStatus(final String connectorId, final FlowEvolutionStatus expectedStatus) throws NiFiClientException, IOException { + assertEquals(expectedStatus.name(), getNifiClient().getConnectorClient().getConnector(connectorId).getComponent().getFlowEvolutionStatus()); + } + + protected void assertStoppedPending(final String connectorId, final String validationError) throws Exception { + getClientUtil().waitForConnectorState(connectorId, ConnectorState.STOPPED); + assertPending(connectorId); + if (validationError == null) { + return; + } + final String errors = getNifiClient().getConnectorClient().getConnector(connectorId).getComponent().getValidationErrors().toString(); + assertTrue(errors.contains(validationError), errors); + } +} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java new file mode 100644 index 000000000000..44b8b4bbd100 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java @@ -0,0 +1,406 @@ +/* + * 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.connectors; + +import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.VersionedConfigurationStep; +import org.apache.nifi.flow.VersionedConnector; +import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.flow.VersionedProcessor; +import org.apache.nifi.nar.NarState; +import org.apache.nifi.tests.system.AbstractNarSwapMigrationIT; +import org.apache.nifi.tests.system.FlowDefinitionFiles; +import org.apache.nifi.tests.system.NiFiInstance; +import org.apache.nifi.tests.system.nar.NarUploadUtil; +import org.apache.nifi.toolkit.client.ConnectorClient; +import org.apache.nifi.toolkit.client.NiFiClientException; +import org.apache.nifi.web.api.dto.BundleDTO; +import org.apache.nifi.web.api.dto.ConnectorDTO; +import org.apache.nifi.web.api.dto.NarSummaryDTO; +import org.apache.nifi.web.api.entity.ConnectionEntity; +import org.apache.nifi.web.api.entity.ConnectorEntity; +import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity; +import org.apache.nifi.web.api.entity.ProcessorEntity; +import org.junit.jupiter.api.BeforeEach; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Upgrade-drain scenarios that hold for every way a Connector can move to a new version. Each subclass supplies the + * trigger: a NAR swap followed by a restart, or a version change while the Connector is stopped. + */ +public abstract class AbstractConnectorUpgradeDrainIT extends AbstractNarSwapMigrationIT { + + private static final String GATE_FILE = "upgrade-drain-gate.txt"; + static final String PREPARATION_FAILED = "flow evolution preparation failed"; + static final String REMOVED_CONNECTION = "Removed Connection"; + static final String REMOVED_PROCESSOR_CHAIN = "Removed Processor Chain"; + static final String RELAY_PROCESSOR = "RelayFlowFile"; + static final String REMOVED_PROCESSOR = "RemovedFlowFile"; + static final String SWAPPED_PROCESSOR = "SwappedFlowFile"; + + static final String DRAIN_CONNECTOR_TYPE = "org.apache.nifi.connectors.tests.system.UpgradeDrainConnector"; + static final String DRAIN_BUNDLE_GROUP = "org.apache.nifi"; + static final String DRAIN_BUNDLE_ARTIFACT = "nifi-connector-upgrade-drain-nar"; + static final String DRAIN_V1 = "1.0.0"; + static final String DRAIN_V2 = "2.0.0"; + private static final String DRAIN_NARS_LOCATION = "target/nifi-connector-upgrade-drain-nars"; + private static final Map DRAIN_NAR_IDS = Map.of( + DRAIN_V1, "nifi-connector-upgrade-drain-v1-nar", + DRAIN_V2, "nifi-connector-upgrade-drain-v2-nar"); + + /** + * Makes the version 2 UpgradeDrainConnector misbehave. The Connector reads the named file from its node's working + * directory, and the file contents select the behavior. Faults that share a file replace each other. + */ + protected enum UpgradeDrainFault { + PREPARATION_RETURNS_NULL_FUTURE("upgrade-drain-preparation-result.txt", "NULL_FUTURE"), + PREPARATION_FAILS("upgrade-drain-preparation-result.txt", "FAILED_FUTURE"), + PREPARATION_UPDATES_PRE_UPGRADE_FLOW("upgrade-drain-preparation-result.txt", "UPDATE_PRE_UPGRADE_FLOW"), + ACTIVE_FLOW_RETURNS_NULL("upgrade-drain-active-flow.txt", "NULL"), + ACTIVE_FLOW_THROWS("upgrade-drain-active-flow.txt", "THROW"), + APPLY_FAILS("upgrade-drain-apply-fail.txt", ""); + + private final String fileName; + private final String contents; + + UpgradeDrainFault(final String fileName, final String contents) { + this.fileName = fileName; + this.contents = contents; + } + } + + /** + * Identifies a Connector bundle in assertions. A null version matches any version of the artifact. + */ + protected record ExpectedBundle(String artifact, String version) { + + String recordPrefix() { + return "org.apache.nifi:" + artifact + ":" + (version == null ? "" : version); + } + + void assertMatches(final Bundle bundle, final String description) { + assertNotNull(bundle, description); + assertTrue(bundle.getArtifact().contains(artifact), description + " " + bundle.getArtifact()); + if (version != null) { + assertEquals(version, bundle.getVersion(), description); + } + } + } + + /** + * Creates the Connector on its outgoing version and applies the given configuration. + */ + protected abstract String createOutgoingConnector(Map properties) throws Exception; + + /** + * Moves the stopped Connector to its incoming version, leaving it STOPPED with the upgrade pending. + */ + protected abstract void triggerUpgrade(String connectorId) throws Exception; + + protected abstract ExpectedBundle outgoingBundle(); + + protected abstract ExpectedBundle incomingBundle(); + + @BeforeEach + public void clearFaults() { + for (final UpgradeDrainFault fault : UpgradeDrainFault.values()) { + clearFault(fault); + } + } + + protected void injectFault(final UpgradeDrainFault fault) throws IOException { + for (int nodeIndex = 1; nodeIndex <= nodeCount(); nodeIndex++) { + injectFault(nodeIndex, fault); + } + } + + protected void injectFault(final int nodeIndex, final UpgradeDrainFault fault) throws IOException { + writeToNodeDirectory(nodeIndex, fault.fileName, fault.contents); + } + + protected void clearFault(final UpgradeDrainFault fault) { + deleteFromNodeDirectories(fault.fileName); + } + + protected String createOutgoingConnector(final String mode, final boolean removeConnection, final String comment) throws Exception { + return createOutgoingConnector(properties(mode, removeConnection, comment)); + } + + protected String queueStoppedUpgrade(final String mode, final boolean removeConnection, final String comment) throws Exception { + return queueAtLeastOneFlowFileAndStop(createOutgoingConnector(mode, removeConnection, comment)); + } + + protected String queueAtLeastOneFlowFileAndStop(final String connectorId) throws Exception { + holdFlowFiles(); + getClientUtil().startConnector(connectorId); + waitForConnectorMinQueueCount(connectorId, 1); + getClientUtil().stopConnector(connectorId); + return connectorId; + } + + protected void restartKeepingIncomingVersion() { + getNiFiInstance().stop(); + getNiFiInstance().start(true); + waitForCluster(); + } + + protected void uploadDrainNars(final String... versions) throws Exception { + final File narsLocation = new File(DRAIN_NARS_LOCATION); + if (!narsLocation.exists()) { + throw new IllegalStateException("NARs location does not exist at: " + narsLocation.getAbsolutePath()); + } + + final NarUploadUtil narUploadUtil = new NarUploadUtil(getNifiClient()); + for (final String version : versions) { + final NarSummaryDTO nar = narUploadUtil.uploadNar(narsLocation, DRAIN_NAR_IDS.get(version)); + waitFor(narUploadUtil.getWaitForNarStateSupplier(nar.getIdentifier(), NarState.INSTALLED)); + } + } + + protected String createDrainConnector(final String version, final Map properties) throws NiFiClientException, IOException, InterruptedException { + final ConnectorEntity connector = getClientUtil().createConnector(DRAIN_CONNECTOR_TYPE, DRAIN_BUNDLE_GROUP, DRAIN_BUNDLE_ARTIFACT, version); + getClientUtil().configureConnector(connector, "Upgrade", properties); + getClientUtil().applyConnectorUpdate(connector); + getClientUtil().waitForValidConnector(connector.getId()); + return connector.getId(); + } + + /** + * Sends the version change the way the UI does: a PUT carrying only the new bundle. + */ + protected ConnectorEntity changeVersion(final String connectorId, final String version) throws NiFiClientException, IOException { + final ConnectorClient connectorClient = getNifiClient().getConnectorClient(); + final ConnectorEntity current = connectorClient.getConnector(connectorId); + final ConnectorDTO component = new ConnectorDTO(); + component.setId(connectorId); + component.setBundle(new BundleDTO(DRAIN_BUNDLE_GROUP, DRAIN_BUNDLE_ARTIFACT, version)); + + final ConnectorEntity update = new ConnectorEntity(); + update.setId(connectorId); + update.setRevision(current.getRevision()); + update.setComponent(component); + return connectorClient.updateConnector(update); + } + + /** + * Stops the generator and lets the terminator drop queued FlowFiles on every node. + */ + protected void releaseFlowFiles() throws IOException { + for (int nodeIndex = 1; nodeIndex <= nodeCount(); nodeIndex++) { + releaseFlowFiles(nodeIndex); + } + } + + /** + * Stops the generator and lets the terminator drop queued FlowFiles on one node. + */ + protected void releaseFlowFiles(final int nodeIndex) throws IOException { + writeToNodeDirectory(nodeIndex, GATE_FILE, ""); + } + + /** + * Lets the generator run and makes the terminator hold every FlowFile on every node. + */ + protected void holdFlowFiles() { + deleteFromNodeDirectories(GATE_FILE); + } + + private void writeToNodeDirectory(final int nodeIndex, final String fileName, final String contents) throws IOException { + Files.writeString(new File(nodeDirectory(nodeIndex), fileName).toPath(), contents); + } + + private void deleteFromNodeDirectories(final String fileName) { + for (final File directory : instanceDirectories()) { + final File file = new File(directory, fileName); + if (file.exists()) { + assertTrue(file.delete(), file.getAbsolutePath()); + } + } + } + + protected void stopAndAssertNotPending(final String connectorId) throws IOException { + getNiFiInstance().stop(); + for (int nodeIndex = 1; nodeIndex <= nodeCount(); nodeIndex++) { + final VersionedConnector connector = FlowDefinitionFiles.readConnector(nodeInstance(nodeIndex), connectorId); + assertManagedFlowBundle(connector, incomingBundle()); + } + } + + protected void assertPersistedOutgoing(final String connectorId) throws IOException { + for (int nodeIndex = 1; nodeIndex <= nodeCount(); nodeIndex++) { + final VersionedConnector connector = FlowDefinitionFiles.readConnector(nodeInstance(nodeIndex), connectorId); + assertManagedFlowBundle(connector, outgoingBundle()); + } + } + + protected int nodeCount() { + return Math.max(1, getNumberOfNodes()); + } + + protected NiFiInstance nodeInstance(final int nodeIndex) { + return getNumberOfNodes() <= 1 ? getNiFiInstance() : getNiFiInstance().getNodeInstance(nodeIndex); + } + + protected File nodeDirectory(final int nodeIndex) { + return nodeInstance(nodeIndex).getInstanceDirectory(); + } + + protected void requestStart(final String connectorId) throws NiFiClientException, IOException { + final ConnectorEntity entity = getNifiClient().getConnectorClient().getConnector(connectorId); + entity.setDisconnectedNodeAcknowledged(true); + getNifiClient().getConnectorClient().startConnector(entity); + } + + protected static void assertLoadedBundle(final VersionedConnector connector, final ExpectedBundle expected) { + expected.assertMatches(connector.getBundle(), "loaded bundle"); + } + + protected static void assertManagedFlowBundle(final VersionedConnector connector, final ExpectedBundle expected) { + expected.assertMatches(connector.getManagedFlowBundle(), "managed flow bundle"); + } + + protected void assertPending(final String connectorId) { + final Exception failure = assertThrows(Exception.class, + () -> getClientUtil().applyConnectorUpdate(getNifiClient().getConnectorClient().getConnector(connectorId))); + assertTrue(failure.getMessage().contains("start the connector instead"), failure.getMessage()); + } + + protected void waitUntilDraining(final String connectorId) throws NiFiClientException, IOException, InterruptedException { + for (int iteration = 0; iteration < 600; iteration++) { + final ConnectorEntity entity = getNifiClient().getConnectorClient().getConnector(connectorId); + final String state = entity.getComponent().getState(); + if (ConnectorState.DRAINING.name().equals(state)) { + return; + } + if (ConnectorState.RUNNING.name().equals(state) || ConnectorState.STOPPED.name().equals(state) || ConnectorState.UPDATE_FAILED.name().equals(state)) { + throw new AssertionError("Expected DRAINING but the connector is " + state + ": " + entity.getComponent().getValidationErrors()); + } + Thread.sleep(100L); + } + final ConnectorEntity entity = getNifiClient().getConnectorClient().getConnector(connectorId); + throw new AssertionError("Connector did not reach DRAINING. State is " + entity.getComponent().getState()); + } + + protected String createConnector(final String type, final Map properties) throws NiFiClientException, IOException, InterruptedException { + final ConnectorEntity connector = getClientUtil().createConnector(type); + getClientUtil().configureConnector(connector, properties.containsKey("Evolution Mode") ? "Upgrade" : "Gate", properties); + getClientUtil().applyConnectorUpdate(connector); + getClientUtil().waitForValidConnector(connector.getId()); + return connector.getId(); + } + + protected Map properties(final String mode, final boolean removeConnection, final String comment) { + final Map properties = new LinkedHashMap<>(); + properties.put("Gate File Path", GATE_FILE); + properties.put("Evolution Mode", mode); + properties.put("Remove Connection", Boolean.toString(removeConnection)); + if (comment != null) { + properties.put("Comment", comment); + } + return properties; + } + + protected void assertConnectorState(final String connectorId, final ConnectorState state) throws NiFiClientException, IOException { + assertEquals(state.name(), getNifiClient().getConnectorClient().getConnector(connectorId).getComponent().getState()); + } + + protected ProcessorEntity findProcessor(final String connectorId, final String name) throws NiFiClientException, IOException { + final ProcessGroupFlowEntity flow = getNifiClient().getConnectorClient().getFlow(connectorId); + for (final ProcessorEntity processor : flow.getProcessGroupFlow().getFlow().getProcessors()) { + if (name.equals(processor.getComponent().getName())) { + return processor; + } + } + return null; + } + + protected VersionedProcessor findProcessor(final VersionedProcessGroup group, final String name) { + if (group == null || group.getProcessors() == null) { + return null; + } + for (final VersionedProcessor processor : group.getProcessors()) { + if (name.equals(processor.getName())) { + return processor; + } + } + return null; + } + + protected String configurationProperty(final List configurationSteps, final String propertyName) { + for (final VersionedConfigurationStep configurationStep : configurationSteps) { + if ("Upgrade".equals(configurationStep.getName()) && configurationStep.getProperties().containsKey(propertyName)) { + return configurationStep.getProperties().get(propertyName).getValue(); + } + } + + return null; + } + + protected int getConnectionQueuedCount(final String connectorId, final String connectionName) throws NiFiClientException, IOException { + final ConnectionEntity connection = findConnection(connectorId, connectionName); + if (connection == null || connection.getStatus() == null || connection.getStatus().getAggregateSnapshot() == null) { + return 0; + } + + return connection.getStatus().getAggregateSnapshot().getFlowFilesQueued(); + } + + protected void waitForConnectionMinQueueCount(final String connectorId, final String connectionName, final int minQueueSize) throws InterruptedException { + waitFor(() -> { + try { + return getConnectionQueuedCount(connectorId, connectionName) >= minQueueSize; + } catch (final Exception ignored) { + return false; + } + }); + } + + protected ConnectionEntity findConnection(final String connectorId, final String name) throws NiFiClientException, IOException { + return findConnection(getNifiClient().getConnectorClient(), connectorId, name); + } + + protected static ConnectionEntity findConnection(final ConnectorClient connectorClient, final String connectorId, final String name) throws NiFiClientException, IOException { + final ProcessGroupFlowEntity flow = connectorClient.getFlow(connectorId); + if (flow.getProcessGroupFlow().getFlow().getConnections() == null) { + return null; + } + for (final ConnectionEntity connection : flow.getProcessGroupFlow().getFlow().getConnections()) { + if (name.equals(connection.getComponent().getName())) { + return connection; + } + } + return null; + } + + protected void waitForCluster() { + if (getNumberOfNodes() > 1) { + waitForAllNodesConnected(); + } + } +} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java new file mode 100644 index 000000000000..5b0d1fc30acc --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java @@ -0,0 +1,56 @@ +/* + * 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.connectors; + +import java.io.IOException; +import java.util.Map; + +/** + * Upgrade-drain support whose trigger is a NAR swap and restart. + */ +public abstract class AbstractNarSwapUpgradeDrainIT extends AbstractConnectorUpgradeDrainIT { + + static final String V1_BUNDLE = "nifi-system-test-extensions-nar"; + static final String V2_BUNDLE = "nifi-alternate-config-extensions-nar"; + + @Override + protected String createOutgoingConnector(final Map properties) throws Exception { + return createConnector("UpgradeDrainConnector", properties); + } + + @Override + protected void triggerUpgrade(final String connectorId) throws IOException { + swapAndRestart(); + } + + @Override + protected ExpectedBundle outgoingBundle() { + return new ExpectedBundle(V1_BUNDLE, null); + } + + @Override + protected ExpectedBundle incomingBundle() { + return new ExpectedBundle(V2_BUNDLE, null); + } + + protected void swapAndRestart() throws IOException { + getNiFiInstance().stop(); + switchOutNars(); + getNiFiInstance().start(true); + waitForCluster(); + } +} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java new file mode 100644 index 000000000000..fb2196db7e2a --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java @@ -0,0 +1,250 @@ +/* + * 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.connectors; + +import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.components.connector.FlowEvolutionStatus; +import org.apache.nifi.tests.system.FlowDefinitionFiles; +import org.apache.nifi.tests.system.NiFiInstanceFactory; +import org.apache.nifi.toolkit.client.ConnectorClient; +import org.apache.nifi.toolkit.client.NiFiClientException; +import org.apache.nifi.web.api.entity.ConnectionEntity; +import org.apache.nifi.web.api.entity.ConnectorEntity; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Two-node version-change drain scenarios. The REST API merges every node's view of a Connector, so per-node assertions + * read each node directly without replication. + */ +public class ClusteredConnectorChangeVersionDrainIT extends AbstractChangeVersionDrainIT { + + @Override + public NiFiInstanceFactory getInstanceFactory() { + return createTwoNodeInstanceFactory(); + } + + @Test + @Timeout(300) + public void testBarrierWaitsForBothNodes() throws Exception { + final String connectorId = queueStoppedUpgrade("DRAIN", true, null); + triggerUpgrade(connectorId); + requestStart(connectorId); + waitForNodeConnectorState(1, connectorId, ConnectorState.DRAINING); + waitForNodeConnectorState(2, connectorId, ConnectorState.DRAINING); + + requestStart(connectorId); + assertNodeConnectorState(1, connectorId, ConnectorState.DRAINING); + assertNodeConnectorState(2, connectorId, ConnectorState.DRAINING); + + releaseFlowFiles(1); + waitForNode(1, connectorClient -> FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE.name().equals(connectorClient.getConnector(connectorId).getComponent().getFlowEvolutionStatus())); + // Node 1 has drained but stays at the drain barrier while node 2 still holds FlowFiles. + onNode(1, connectorClient -> { + final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (System.nanoTime() < deadline) { + final ConnectorEntity connector = connectorClient.getConnector(connectorId); + assertEquals(ConnectorState.DRAINING.name(), connector.getComponent().getState()); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE.name(), connector.getComponent().getFlowEvolutionStatus()); + Thread.sleep(100L); + } + + return null; + }); + assertNotNull(nodeConnection(1, connectorId)); + assertNodeConnectorState(2, connectorId, ConnectorState.DRAINING); + assertNotNull(nodeConnection(2, connectorId)); + assertNodeFlowEvolutionStatus(2, connectorId, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING); + + releaseFlowFiles(2); + waitForNodeConnectorState(1, connectorId, ConnectorState.RUNNING); + waitForNodeConnectorState(2, connectorId, ConnectorState.RUNNING); + assertNull(nodeConnection(1, connectorId)); + assertNull(nodeConnection(2, connectorId)); + assertNodeFlowEvolutionStatus(1, connectorId, FlowEvolutionStatus.INACTIVE); + assertNodeFlowEvolutionStatus(2, connectorId, FlowEvolutionStatus.INACTIVE); + } + + @Test + @Timeout(300) + public void testNodeLocalFailureKeepsBothStoppedAtDrainBarrier() throws Exception { + final String connectorId = createOutgoingConnector("NO_OP", true, null); + holdFlowFiles(); + getClientUtil().startConnector(connectorId); + waitForConnectorMinQueueCount(connectorId, 1); + // Release only node 1 so its generator stops while TerminateFlowFile, already running with the connector, empties that node. Node 2 keeps generating. + releaseFlowFiles(1); + waitForNode(1, connectorClient -> localQueuedCount(connectorClient, connectorId) == 0); + assertTrue(nodeLocalQueuedCount(2, connectorId) > 0); + getClientUtil().stopConnector(connectorId); + assertEquals(0, nodeLocalQueuedCount(1, connectorId)); + assertTrue(nodeLocalQueuedCount(2, connectorId) > 0); + + triggerUpgrade(connectorId); + + requestStart(connectorId); + waitForNodeConnectorState(2, connectorId, ConnectorState.STOPPED); + waitForNodeConnectorState(1, connectorId, ConnectorState.STOPPED); + assertNodeStoppedPendingWithOldFlow(1, connectorId); + assertNodeStoppedPendingWithOldFlow(2, connectorId); + assertNodeFlowEvolutionStatus(1, connectorId, FlowEvolutionStatus.FAILED); + assertNodeFlowEvolutionStatus(2, connectorId, FlowEvolutionStatus.FAILED); + final String nodeTwoErrors = onNode(2, connectorClient -> connectorClient.getConnector(connectorId).getComponent().getValidationErrors().toString()); + assertTrue(nodeTwoErrors.contains("does not contain a match for"), nodeTwoErrors); + } + + @Test + @Timeout(300) + public void testDisconnectedDrainingNodeBlocksDrainBarrierAndKeepsPendingFlowOnReconnect() throws Exception { + final String connectorId = queueStoppedUpgrade("DRAIN", true, null); + triggerUpgrade(connectorId); + requestStart(connectorId); + waitForNodeConnectorState(1, connectorId, ConnectorState.DRAINING); + waitForNodeConnectorState(2, connectorId, ConnectorState.DRAINING); + + disconnectNode(2); + releaseFlowFiles(); + waitForNodeConnectorState(1, connectorId, ConnectorState.STOPPED); + assertNodeStoppedPendingWithOldFlow(1, connectorId); + assertNodeFlowEvolutionStatus(1, connectorId, FlowEvolutionStatus.FAILED); + + reconnectNode(2); + waitForAllNodesConnected(); + waitForNodeConnectorState(1, connectorId, ConnectorState.STOPPED); + waitForNodeConnectorState(2, connectorId, ConnectorState.STOPPED); + assertNodeStoppedPendingWithOldFlow(1, connectorId); + assertNodeStoppedPendingWithOldFlow(2, connectorId); + assertNodeFlowEvolutionStatus(1, connectorId, FlowEvolutionStatus.FAILED); + assertNodeFlowEvolutionStatus(2, connectorId, FlowEvolutionStatus.FAILED); + + // Node 1 drained before its attempt failed at the barrier, but the upgraded flow was never applied, so a retry + // prepares and drains again. A preparation failure on node 1 therefore fails the retry. + injectFault(1, UpgradeDrainFault.PREPARATION_FAILS); + requestStart(connectorId); + waitForNode(1, connectorClient -> connectorClient.getConnector(connectorId).getComponent().getValidationErrors().toString().contains(PREPARATION_FAILED)); + waitForNodeConnectorState(1, connectorId, ConnectorState.STOPPED); + waitForNodeConnectorState(2, connectorId, ConnectorState.STOPPED); + assertNodeStoppedPendingWithOldFlow(1, connectorId); + assertNodeStoppedPendingWithOldFlow(2, connectorId); + + clearFault(UpgradeDrainFault.PREPARATION_FAILS); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + for (int nodeIndex = 1; nodeIndex <= 2; nodeIndex++) { + assertNodeConnectorState(nodeIndex, connectorId, ConnectorState.RUNNING); + assertNull(nodeConnection(nodeIndex, connectorId)); + assertNodeFlowEvolutionStatus(nodeIndex, connectorId, FlowEvolutionStatus.INACTIVE); + } + } + + @Test + @Timeout(240) + public void testApplyFailureRetriesApplyWithoutRepeatingEvolutionPreparation() throws Exception { + final String connectorId = queueStoppedUpgrade("NO_OP", false, "original"); + changeVersion(connectorId, DRAIN_V2); + getClientUtil().configureConnector(connectorId, "Upgrade", properties("NO_OP", false, "edited")); + injectFault(1, UpgradeDrainFault.APPLY_FAILS); + + requestStart(connectorId); + // The merged cluster state reports UPDATE_FAILED as soon as one node fails. A node that is still finishing its + // failed evolution treats a new start request as part of that evolution, so wait for every node to fail first. + waitForNodeConnectorState(1, connectorId, ConnectorState.UPDATE_FAILED); + waitForNodeConnectorState(2, connectorId, ConnectorState.UPDATE_FAILED); + assertManagedFlowBundle(FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId), outgoingBundle()); + + // Node 2 already applied the upgraded flow, so the retry only applies it on node 1. Flow evolution preparation + // already completed on both nodes, so the retry does not run it again. + clearFault(UpgradeDrainFault.APPLY_FAILS); + injectFault(2, UpgradeDrainFault.APPLY_FAILS); + injectFault(UpgradeDrainFault.PREPARATION_FAILS); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertNodeFlowEvolutionStatus(1, connectorId, FlowEvolutionStatus.INACTIVE); + assertNodeFlowEvolutionStatus(2, connectorId, FlowEvolutionStatus.INACTIVE); + assertEquals("edited", findProcessor(connectorId, "GenerateFlowFile").getComponent().getConfig().getComments()); + stopAndAssertNotPending(connectorId); + } + + private T onNode(final int nodeIndex, final NodeCall call) throws Exception { + switchClientToNode(nodeIndex); + try { + return call.call(getNifiClient().getConnectorClient(DO_NOT_REPLICATE)); + } finally { + setupClient(); + } + } + + private void waitForNode(final int nodeIndex, final NodeCall condition) throws InterruptedException { + switchClientToNode(nodeIndex); + try { + final ConnectorClient connectorClient = getNifiClient().getConnectorClient(DO_NOT_REPLICATE); + waitFor(() -> condition.call(connectorClient)); + } finally { + setupClient(); + } + } + + private void waitForNodeConnectorState(final int nodeIndex, final String connectorId, final ConnectorState expectedState) throws InterruptedException { + waitForNode(nodeIndex, connectorClient -> expectedState.name().equals(connectorClient.getConnector(connectorId).getComponent().getState())); + } + + private void assertNodeConnectorState(final int nodeIndex, final String connectorId, final ConnectorState expectedState) throws Exception { + assertEquals(expectedState.name(), onNode(nodeIndex, connectorClient -> connectorClient.getConnector(connectorId)).getComponent().getState()); + } + + private void assertNodeFlowEvolutionStatus(final int nodeIndex, final String connectorId, final FlowEvolutionStatus expectedStatus) throws Exception { + assertEquals(expectedStatus.name(), onNode(nodeIndex, connectorClient -> connectorClient.getConnector(connectorId)).getComponent().getFlowEvolutionStatus()); + } + + private ConnectionEntity nodeConnection(final int nodeIndex, final String connectorId) throws Exception { + return onNode(nodeIndex, connectorClient -> findConnection(connectorClient, connectorId, REMOVED_CONNECTION)); + } + + private int nodeLocalQueuedCount(final int nodeIndex, final String connectorId) throws Exception { + return onNode(nodeIndex, connectorClient -> localQueuedCount(connectorClient, connectorId)); + } + + private static int localQueuedCount(final ConnectorClient connectorClient, final String connectorId) throws NiFiClientException, IOException { + return connectorClient.getStatus(connectorId, true).getProcessGroupStatus().getAggregateSnapshot().getFlowFilesQueued(); + } + + private void assertNodeStoppedPendingWithOldFlow(final int nodeIndex, final String connectorId) throws Exception { + onNode(nodeIndex, connectorClient -> { + final ConnectorEntity connector = connectorClient.getConnector(connectorId); + assertEquals(ConnectorState.STOPPED.name(), connector.getComponent().getState()); + assertNotNull(findConnection(connectorClient, connectorId, REMOVED_CONNECTION)); + connector.setDisconnectedNodeAcknowledged(true); + final NiFiClientException failure = assertThrows(NiFiClientException.class, () -> connectorClient.applyUpdate(connector)); + assertTrue(failure.getMessage().contains("start the connector instead"), failure.getMessage()); + return null; + }); + } + + @FunctionalInterface + private interface NodeCall { + T call(ConnectorClient connectorClient) throws Exception; + } +} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorIT.java index d377b8663621..eb0631501417 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorIT.java @@ -24,6 +24,8 @@ import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO; import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO; import org.apache.nifi.web.api.entity.ConnectorEntity; +import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity; +import org.apache.nifi.web.api.entity.ProcessorEntity; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -201,9 +203,8 @@ public void testDeleteConnectorOnConnectWithDataQueued() throws NiFiClientExcept @Test public void testRunningConnectorSyncedOnReconnect() throws NiFiClientException, IOException, InterruptedException { // Create and start a connector - final ConnectorEntity connector = getClientUtil().createConnector("NopConnector"); + final ConnectorEntity connector = getClientUtil().createConnector("DataQueuingConnector"); assertNotNull(connector); - getClientUtil().configureConnector(connector, "Ignored Step", Map.of("Ignored Property", "Test Value")); getClientUtil().applyConnectorUpdate(connector); getClientUtil().startConnector(connector); logger.info("Created and started connector [{}]", connector.getId()); @@ -233,7 +234,8 @@ public void testRunningConnectorSyncedOnReconnect() throws NiFiClientException, waitFor(() -> { try { final ConnectorEntity rejoinedConnector = getNifiClient().getConnectorClient(DO_NOT_REPLICATE).getConnector(connector.getId()); - return "RUNNING".equals(rejoinedConnector.getComponent().getState()); + return "RUNNING".equals(rejoinedConnector.getComponent().getState()) + && "RUNNING".equals(managedProcessorState(connector.getId(), "GenerateFlowFile")); } catch (final Exception e) { return false; } @@ -241,8 +243,8 @@ public void testRunningConnectorSyncedOnReconnect() throws NiFiClientException, final ConnectorEntity finalNode2Connector = getNifiClient().getConnectorClient(DO_NOT_REPLICATE).getConnector(connector.getId()); assertEquals("RUNNING", finalNode2Connector.getComponent().getState()); - assertActiveConfigurationValue(finalNode2Connector, "Ignored Property", "Test Value"); - logger.info("Verified connector is RUNNING on Node 2 after rejoin with correct configuration"); + assertManagedProcessorState(connector.getId(), "GenerateFlowFile", "RUNNING"); + logger.info("Verified connector and managed processors are RUNNING on Node 2 after rejoin"); } @Test @@ -280,6 +282,21 @@ public void testNewConnectorSyncedOnReconnect() throws NiFiClientException, IOEx logger.info("Verified new connector exists on Node 2 after rejoin with correct configuration"); } + private void assertManagedProcessorState(final String connectorId, final String processorName, final String expectedState) + throws NiFiClientException, IOException { + assertEquals(expectedState, managedProcessorState(connectorId, processorName)); + } + + private String managedProcessorState(final String connectorId, final String processorName) throws NiFiClientException, IOException { + final ProcessGroupFlowEntity flow = getNifiClient().getConnectorClient(DO_NOT_REPLICATE).getFlow(connectorId); + for (final ProcessorEntity processor : flow.getProcessGroupFlow().getFlow().getProcessors()) { + if (processorName.equals(processor.getComponent().getName())) { + return processor.getComponent().getState(); + } + } + return null; + } + private void assertActiveConfigurationValue(final ConnectorEntity connector, final String propertyName, final String expectedValue) { final String actualValue = getConfigurationValue(connector.getComponent().getActiveConfiguration(), propertyName); assertEquals(expectedValue, actualValue, "Active configuration property '" + propertyName + "' did not match expected value"); diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java new file mode 100644 index 000000000000..6e4f30c9c400 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java @@ -0,0 +1,71 @@ +/* + * 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.connectors; + +import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.tests.system.NiFiInstanceFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Verifies clustered startup after a Connector NAR swap. The pre-upgrade flow queues FlowFiles on the connection + * from the processor the upgrade removes to the terminator that stays, so the connector stays draining until that + * connection is empty. The processor before the removed one is replaced. + */ +public class ClusteredConnectorUpgradeDrainIT extends AbstractNarSwapUpgradeDrainIT { + + @Override + public NiFiInstanceFactory getInstanceFactory() { + return createTwoNodeInstanceFactory(); + } + + @Test + @Timeout(240) + public void testRunningConnectorAutoResumes() throws Exception { + final Map properties = properties("DRAIN", true, null); + properties.put(REMOVED_PROCESSOR_CHAIN, "true"); + final String connectorId = createOutgoingConnector(properties); + holdFlowFiles(); + getClientUtil().startConnector(connectorId); + waitForConnectionMinQueueCount(connectorId, REMOVED_CONNECTION, 1); + getNiFiInstance().stop(); + switchOutNars(); + getNiFiInstance().start(true); + waitForCluster(); + + getClientUtil().waitForConnectorState(connectorId, ConnectorState.DRAINING); + assertNotNull(findProcessor(connectorId, RELAY_PROCESSOR)); + assertNotNull(findProcessor(connectorId, REMOVED_PROCESSOR)); + assertNotNull(findProcessor(connectorId, "TerminateFlowFile")); + assertTrue(getConnectionQueuedCount(connectorId, REMOVED_CONNECTION) > 0); + + releaseFlowFiles(); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertNull(findProcessor(connectorId, RELAY_PROCESSOR)); + assertNull(findProcessor(connectorId, REMOVED_PROCESSOR)); + assertNotNull(findProcessor(connectorId, SWAPPED_PROCESSOR)); + assertNotNull(findProcessor(connectorId, "TerminateFlowFile")); + assertNull(findConnection(connectorId, REMOVED_CONNECTION)); + stopAndAssertNotPending(connectorId); + } +} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java new file mode 100644 index 000000000000..c3ee2acd3243 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java @@ -0,0 +1,481 @@ +/* + * 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.connectors; + +import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.components.connector.FlowEvolutionStatus; +import org.apache.nifi.flow.VersionedConnector; +import org.apache.nifi.flow.VersionedConnectorState; +import org.apache.nifi.flow.VersionedConnectorValueReference; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.security.encryption.PropertyEncryptionEncoder; +import org.apache.nifi.tests.system.FlowDefinitionFiles; +import org.apache.nifi.toolkit.client.NiFiClientException; +import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO; +import org.apache.nifi.web.api.dto.StateEntryDTO; +import org.apache.nifi.web.api.entity.ComponentStateEntity; +import org.apache.nifi.web.api.entity.ConnectionEntity; +import org.apache.nifi.web.api.entity.ConnectorEntity; +import org.apache.nifi.web.api.entity.ParameterProviderEntity; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Single-node upgrade-drain scenarios for a version change. + */ +public class ConnectorChangeVersionDrainIT extends AbstractChangeVersionDrainIT { + + private static final String UPGRADE_SECRET = "Upgrade Secret"; + private static final String PROVIDER_NAME = "PropertiesParameterProvider"; + private static final String SECRET_NAME = "upgrade-secret"; + private static final String SECRET_FULLY_QUALIFIED_NAME = PROVIDER_NAME + ".Parameters." + SECRET_NAME; + private static final String GENERATOR = "GenerateFlowFile"; + private static final String CANCELLED_EVOLUTION = "Flow evolution was cancelled"; + private static final String REWIRED_ENDPOINT = "Rewired Endpoint"; + + @Test + @Timeout(360) + public void testPreUpgradeParameterSecretIsRefreshedAndCanBeRestored() throws Exception { + final SecretConnector secretConnector = createSecretConnector("original-secret"); + changeVersion(secretConnector.connectorId(), DRAIN_V2); + getClientUtil().updateParameterProviderProperties(secretConnector.parameterProvider(), Map.of("parameters", SECRET_NAME + "=rotated-secret")); + + getNiFiInstance().stop(); + assertSecretPersistedAsReference(FlowDefinitionFiles.readConnector(nodeInstance(1), secretConnector.connectorId())); + getNiFiInstance().start(true); + waitForCluster(); + + requestStart(secretConnector.connectorId()); + getClientUtil().waitForConnectorState(secretConnector.connectorId(), ConnectorState.RUNNING); + stopAndAssertNotPending(secretConnector.connectorId()); + } + + @Test + @Timeout(360) + public void testPendingUpgradeEditsThenStartsWithoutReEvolving() throws Exception { + final String connectorId = queueStoppedUpgrade("INHERITED_DRAIN", true, "original"); + final String connectionId = findConnection(connectorId, REMOVED_CONNECTION).getId(); + final int queued = getConnectorQueuedFlowFileCount(connectorId); + final long generated = generatorCount(connectorId); + assertQueueMatchesCount(connectorId); + triggerUpgrade(connectorId); + + assertConnectorState(connectorId, ConnectorState.STOPPED); + assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); + assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + assertPending(connectorId); + + getClientUtil().configureConnector(connectorId, "Upgrade", properties("DRAIN", true, "working-edit")); + assertPending(connectorId); + getNiFiInstance().stop(); + final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); + assertLoadedBundle(persisted, incomingBundle()); + assertManagedFlowBundle(persisted, outgoingBundle()); + assertNotNull(findProcessor(persisted.getManagedProcessGroup(), "TerminateFlowFile")); + getNiFiInstance().start(true); + waitForCluster(); + + assertEquals(generated, generatorCount(connectorId)); + assertQueueMatchesCount(connectorId); + + // Releasing FlowFiles stops the generator, so its count must not move while the pre-upgrade flow drains and evolves. + releaseFlowFiles(); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertNull(findConnection(connectorId, REMOVED_CONNECTION)); + assertEquals("working-edit", findProcessor(connectorId, GENERATOR).getComponent().getConfig().getComments()); + assertTrue(findProcessor(connectorId, GENERATOR).getComponent().getBundle().getArtifact().contains("nifi-system-test-extensions2")); + assertEquals(generated, generatorCount(connectorId)); + + getNiFiInstance().stop(); + final VersionedConnector evolved = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); + assertManagedFlowBundle(evolved, incomingBundle()); + assertEquals(VersionedConnectorState.RUNNING, evolved.getScheduledState()); + assertEquals("working-edit", configurationProperty(evolved.getActiveFlowConfiguration(), "Comment")); + assertEquals("working-edit", configurationProperty(evolved.getWorkingFlowConfiguration(), "Comment")); + assertEquals("working-edit", findProcessor(evolved.getManagedProcessGroup(), "GenerateFlowFile").getComments()); + assertTrue(findProcessor(evolved.getManagedProcessGroup(), "GenerateFlowFile").getBundle().getArtifact().contains("nifi-system-test-extensions2")); + getNiFiInstance().start(true); + waitForCluster(); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.INACTIVE); + + getClientUtil().stopConnector(connectorId); + getClientUtil().configureConnector(connectorId, "Upgrade", properties("DRAIN", true, "after-evolution")); + getClientUtil().applyConnectorUpdate(getNifiClient().getConnectorClient().getConnector(connectorId)); + getClientUtil().waitForValidConnector(connectorId); + assertEquals("after-evolution", findProcessor(connectorId, "GenerateFlowFile").getComponent().getConfig().getComments()); + } + + @Test + @Timeout(360) + public void testPendingUpgradeClearsWhenBundleMatchesManagedFlow() throws Exception { + final String connectorId = queueStoppedUpgrade("DRAIN", true, null); + final String connectionId = findConnection(connectorId, REMOVED_CONNECTION).getId(); + final int queued = getConnectorQueuedFlowFileCount(connectorId); + + changeVersion(connectorId, DRAIN_V2); + assertPending(connectorId); + changeVersion(connectorId, DRAIN_V1); + + assertConnectorState(connectorId, ConnectorState.STOPPED); + assertEquals(DRAIN_V1, getNifiClient().getConnectorClient().getConnector(connectorId).getComponent().getBundle().getVersion()); + assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); + assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + getClientUtil().applyConnectorUpdate(getNifiClient().getConnectorClient().getConnector(connectorId)); + getClientUtil().waitForValidConnector(connectorId); + + releaseFlowFiles(); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertNotNull(findConnection(connectorId, REMOVED_CONNECTION)); + + getNiFiInstance().stop(); + final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); + assertLoadedBundle(persisted, outgoingBundle()); + assertManagedFlowBundle(persisted, outgoingBundle()); + } + + @Test + @Timeout(240) + public void testRestartDuringDrainingComesBackPending() throws Exception { + final String connectorId = queueStoppedUpgrade("DRAIN", true, null); + triggerUpgrade(connectorId); + holdFlowFiles(); + assertTrue(getConnectorQueuedFlowFileCount(connectorId) > 0); + requestStart(connectorId); + waitUntilDraining(connectorId); + final int queued = getConnectorQueuedFlowFileCount(connectorId); + final long generated = generatorCount(connectorId); + + // An evolution in progress keeps the Connector's desired state RUNNING, so the restarted node resumes it. + getNiFiInstance().stop(); + assertEquals(VersionedConnectorState.RUNNING, FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId).getScheduledState()); + getNiFiInstance().start(true); + waitForCluster(); + + getClientUtil().cancelDrain(connectorId); + getClientUtil().waitForConnectorStopped(connectorId); + assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + assertEquals(generated, generatorCount(connectorId)); + assertQueueMatchesCount(connectorId); + assertNotNull(findConnection(connectorId, REMOVED_CONNECTION)); + assertPending(connectorId); + getNiFiInstance().stop(); + final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); + assertEquals(VersionedConnectorState.ENABLED, persisted.getScheduledState()); + assertLoadedBundle(persisted, incomingBundle()); + assertManagedFlowBundle(persisted, outgoingBundle()); + } + + @Test + @Timeout(240) + public void testUpdatingPreUpgradeFlowDuringPreparationFailsEvolution() throws Exception { + final String connectorId = queueStoppedUpgrade("NO_OP", false, null); + final String connectionId = findConnection(connectorId, REMOVED_CONNECTION).getId(); + final int queued = getConnectorQueuedFlowFileCount(connectorId); + final long generated = generatorCount(connectorId); + changeVersion(connectorId, DRAIN_V2); + injectFault(UpgradeDrainFault.PREPARATION_UPDATES_PRE_UPGRADE_FLOW); + requestStart(connectorId); + + assertStoppedPending(connectorId, "not an instance provided by the framework"); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.FAILED); + assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); + assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + assertEquals(generated, generatorCount(connectorId)); + + getNiFiInstance().stop(); + final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); + assertLoadedBundle(persisted, incomingBundle()); + assertManagedFlowBundle(persisted, outgoingBundle()); + } + + @Test + @Timeout(240) + public void testInvalidEvolutionResultLeavesUpgradePendingUntilValid() throws Exception { + final String connectorId = queueStoppedUpgrade("NO_OP", false, null); + final String connectionId = findConnection(connectorId, REMOVED_CONNECTION).getId(); + final int queued = getConnectorQueuedFlowFileCount(connectorId); + final long generated = generatorCount(connectorId); + assertQueueMatchesCount(connectorId); + changeVersion(connectorId, DRAIN_V2); + + final Map expectedErrors = new LinkedHashMap<>(); + expectedErrors.put(UpgradeDrainFault.PREPARATION_RETURNS_NULL_FUTURE, "must return a CompletableFuture"); + expectedErrors.put(UpgradeDrainFault.PREPARATION_FAILS, PREPARATION_FAILED); + expectedErrors.put(UpgradeDrainFault.ACTIVE_FLOW_RETURNS_NULL, "Upgraded flow was not returned"); + expectedErrors.put(UpgradeDrainFault.ACTIVE_FLOW_THROWS, "active flow failed"); + for (final Map.Entry expectedError : expectedErrors.entrySet()) { + clearFaults(); + injectFault(expectedError.getKey()); + + requestStart(connectorId); + assertStoppedPending(connectorId, expectedError.getValue()); + assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); + assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + assertEquals(generated, generatorCount(connectorId)); + assertPersistedOutgoing(connectorId); + } + + // The upgraded flow keeps the queued connection. FlowFiles are still held, so the generator keeps running and its + // count grows, but it must still equal the number of FlowFiles queued behind the terminator. + clearFaults(); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + getClientUtil().stopConnector(connectorId); + getClientUtil().waitForConnectorStopped(connectorId); + + assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); + assertQueueMatchesCount(connectorId); + assertTrue(generatorCount(connectorId) >= generated); + stopAndAssertNotPending(connectorId); + } + + @Test + @Timeout(240) + public void testMovingSourceOfQueuedConnectionFailsEvolutionUntilQueueIsEmpty() throws Exception { + final String connectorId = queueStoppedUpgrade("NO_OP", false, null); + final String connectionId = findConnection(connectorId, REMOVED_CONNECTION).getId(); + final int queued = getConnectorQueuedFlowFileCount(connectorId); + final long generated = generatorCount(connectorId); + changeVersion(connectorId, DRAIN_V2); + final Map properties = properties("NO_OP", false, null); + properties.put(REWIRED_ENDPOINT, "SOURCE"); + getClientUtil().configureConnector(connectorId, "Upgrade", properties); + + // Moving the source of a connection removes and recreates it, which would drop its queued FlowFiles. + requestStart(connectorId); + assertStoppedPending(connectorId, "changes the source of"); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.FAILED); + assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); + assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + assertEquals(generated, generatorCount(connectorId)); + assertPersistedOutgoing(connectorId); + + getClientUtil().purgeConnectorFlowFiles(connectorId); + getClientUtil().waitForConnectorStopped(connectorId); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertEquals(RELAY_PROCESSOR, findConnection(connectorId, REMOVED_CONNECTION).getComponent().getSource().getName()); + stopAndAssertNotPending(connectorId); + } + + @Test + @Timeout(240) + public void testMovingDestinationOfQueuedConnectionKeepsQueuedFlowFiles() throws Exception { + final String connectorId = queueStoppedUpgrade("NO_OP", false, null); + final String connectionId = findConnection(connectorId, REMOVED_CONNECTION).getId(); + final long generated = generatorCount(connectorId); + changeVersion(connectorId, DRAIN_V2); + final Map properties = properties("NO_OP", false, null); + properties.put(REWIRED_ENDPOINT, "DESTINATION"); + getClientUtil().configureConnector(connectorId, "Upgrade", properties); + + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + getClientUtil().stopConnector(connectorId); + getClientUtil().waitForConnectorStopped(connectorId); + + // A destination change updates the connection in place. FlowFiles are still held, so every FlowFile generated + // before and after the upgrade is still queued in the connector. + final ConnectionEntity connection = findConnection(connectorId, REMOVED_CONNECTION); + assertEquals(connectionId, connection.getId()); + assertEquals(RELAY_PROCESSOR, connection.getComponent().getDestination().getName()); + final long generatedAfterUpgrade = generatorCount(connectorId); + assertTrue(generatedAfterUpgrade >= generated); + assertEquals(generatedAfterUpgrade, getConnectorQueuedFlowFileCount(connectorId)); + stopAndAssertNotPending(connectorId); + } + + @Test + @Timeout(240) + public void testChangeVersionRejectedWhileDraining() throws Exception { + final String connectorId = queueStoppedUpgrade("DRAIN", true, null); + changeVersion(connectorId, DRAIN_V2); + holdFlowFiles(); + requestStart(connectorId); + waitUntilDraining(connectorId); + assertNotNull(getClientUtil().getConnectorActionReasonNotAllowed(connectorId, "CHANGE_VERSION")); + assertThrows(NiFiClientException.class, () -> changeVersion(connectorId, DRAIN_V1)); + assertConnectorState(connectorId, ConnectorState.DRAINING); + assertEquals(DRAIN_V2, getNifiClient().getConnectorClient().getConnector(connectorId).getComponent().getBundle().getVersion()); + + getClientUtil().cancelDrain(connectorId); + assertStoppedPending(connectorId, CANCELLED_EVOLUTION); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.FAILED); + assertNull(getClientUtil().getConnectorActionReasonNotAllowed(connectorId, "CHANGE_VERSION")); + } + + @Test + @Timeout(240) + public void testStopDuringEvolutionDrainFailsEvolution() throws Exception { + final String connectorId = queueStoppedUpgrade("DRAIN", true, null); + changeVersion(connectorId, DRAIN_V2); + holdFlowFiles(); + requestStart(connectorId); + waitUntilDraining(connectorId); + + getClientUtil().stopConnector(connectorId); + assertStoppedPending(connectorId, CANCELLED_EVOLUTION); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.FAILED); + assertNotNull(findConnection(connectorId, REMOVED_CONNECTION)); + assertPersistedOutgoing(connectorId); + } + + @Test + @Timeout(240) + public void testEndingTroubleshootingAfterFailedApplyCompletesUpgrade() throws Exception { + final String connectorId = createOutgoingConnector("NO_OP", false, null); + changeVersion(connectorId, DRAIN_V2); + injectFault(UpgradeDrainFault.APPLY_FAILS); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.UPDATE_FAILED); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE); + + clearFault(UpgradeDrainFault.APPLY_FAILS); + getClientUtil().enterTroubleshooting(connectorId); + getClientUtil().endTroubleshooting(connectorId); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.INACTIVE); + getClientUtil().applyConnectorUpdate(getNifiClient().getConnectorClient().getConnector(connectorId)); + getClientUtil().waitForValidConnector(connectorId); + stopAndAssertNotPending(connectorId); + } + + @Test + @Timeout(240) + public void testPendingUpgradeBlocksEndingTroubleshootingWithQueuedFlowFiles() throws Exception { + final String connectorId = queueStoppedUpgrade("NO_OP", false, null); + final int queued = getConnectorQueuedFlowFileCount(connectorId); + changeVersion(connectorId, DRAIN_V2); + getClientUtil().enterTroubleshooting(connectorId); + + final ConnectorEntity connector = getNifiClient().getConnectorClient().getConnector(connectorId); + final NiFiClientException failure = assertThrows(NiFiClientException.class, () -> getNifiClient().getConnectorClient() + .endTroubleshooting(connectorId, connector.getRevision().getClientId(), connector.getRevision().getVersion())); + assertTrue(failure.getMessage().contains(queued + " FlowFiles"), failure.getMessage()); + assertTrue(failure.getMessage().contains("upgrade is pending"), failure.getMessage()); + assertConnectorState(connectorId, ConnectorState.TROUBLESHOOTING); + assertPersistedOutgoing(connectorId); + + restartKeepingIncomingVersion(); + assertConnectorState(connectorId, ConnectorState.TROUBLESHOOTING); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING); + assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + } + + @Test + @Timeout(240) + public void testSecondUpgradeAfterCompletedUpgrade() throws Exception { + releaseFlowFiles(); + final String connectorId = createOutgoingConnector("NO_OP", false, null); + changeVersion(connectorId, DRAIN_V2); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + getClientUtil().stopConnector(connectorId); + getClientUtil().waitForConnectorStopped(connectorId); + + changeVersion(connectorId, DRAIN_V1); + assertPending(connectorId); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.INACTIVE); + + getNiFiInstance().stop(); + assertManagedFlowBundle(FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId), outgoingBundle()); + } + + /** + * While FlowFiles are held, the terminator keeps every generated FlowFile, so the generator's stored count equals the + * number of queued FlowFiles. Lost FlowFiles make the queue smaller; cleared state makes the count smaller. + */ + private void assertQueueMatchesCount(final String connectorId) throws NiFiClientException, IOException { + assertEquals(getConnectionQueuedCount(connectorId, REMOVED_CONNECTION), generatorCount(connectorId)); + } + + private long generatorCount(final String connectorId) throws NiFiClientException, IOException { + final String generatorId = findProcessor(connectorId, GENERATOR).getId(); + final ComponentStateEntity stateEntity = getNifiClient().getConnectorClient().getProcessorState(connectorId, generatorId); + for (final StateEntryDTO entry : stateEntity.getComponentState().getLocalState().getState()) { + if ("count".equals(entry.getKey())) { + return Long.parseLong(entry.getValue()); + } + } + + return 0L; + } + + private void assertSecretPersistedAsReference(final VersionedConnector connector) { + final VersionedParameter parameter = connector.getManagedParameterContext().getParameters().stream() + .filter(candidate -> UPGRADE_SECRET.equals(candidate.getName())) + .findFirst() + .orElseThrow(); + assertTrue(parameter.isSensitive()); + assertFalse(parameter.isProvided()); + assertTrue(PropertyEncryptionEncoder.isEncrypted(parameter.getValue())); + + final VersionedConnectorValueReference parameterReference = connector.getManagedParameterSecretReferences().get(UPGRADE_SECRET); + assertNotNull(parameterReference); + assertEquals(SECRET_FULLY_QUALIFIED_NAME, parameterReference.getFullyQualifiedSecretName()); + + final VersionedConnectorValueReference propertyReference = connector.getActiveFlowConfiguration().stream() + .filter(step -> "Upgrade".equals(step.getName())) + .map(step -> step.getProperties().get(UPGRADE_SECRET)) + .findFirst() + .orElseThrow(); + assertEquals(SECRET_FULLY_QUALIFIED_NAME, propertyReference.getFullyQualifiedSecretName()); + assertManagedFlowBundle(connector, outgoingBundle()); + } + + private SecretConnector createSecretConnector(final String secretValue) throws Exception { + final ParameterProviderEntity parameterProvider = getClientUtil().createParameterProvider(PROVIDER_NAME); + final ParameterProviderEntity configuredProvider = getClientUtil().updateParameterProviderProperties( + parameterProvider, Map.of("parameters", SECRET_NAME + "=" + secretValue)); + final ConnectorEntity connector = getClientUtil().createConnector( + DRAIN_CONNECTOR_TYPE, DRAIN_BUNDLE_GROUP, DRAIN_BUNDLE_ARTIFACT, DRAIN_V1); + + final Map propertyReferences = new HashMap<>(); + for (final Map.Entry property : properties("NO_OP", false, null).entrySet()) { + final ConnectorValueReferenceDTO reference = new ConnectorValueReferenceDTO(); + reference.setValueType("STRING_LITERAL"); + reference.setValue(property.getValue()); + propertyReferences.put(property.getKey(), reference); + } + propertyReferences.put(UPGRADE_SECRET, getClientUtil().createSecretValueReference( + configuredProvider.getId(), SECRET_NAME, SECRET_FULLY_QUALIFIED_NAME)); + + getClientUtil().configureConnectorWithReferences(connector, "Upgrade", propertyReferences); + getClientUtil().applyConnectorUpdate(connector); + getClientUtil().waitForValidConnector(connector.getId()); + return new SecretConnector(connector.getId(), configuredProvider); + } + + private record SecretConnector(String connectorId, ParameterProviderEntity parameterProvider) { + } +} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionIT.java index 44fc0853285b..0d745cd1a0d0 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionIT.java @@ -22,8 +22,11 @@ import org.apache.nifi.tests.system.nar.NarUploadUtil; import org.apache.nifi.toolkit.cli.impl.command.CommandOption; import org.apache.nifi.toolkit.cli.impl.command.nifi.connectors.ChangeVersionConnector; +import org.apache.nifi.toolkit.client.NiFiClientException; +import org.apache.nifi.web.api.dto.BundleDTO; import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO; +import org.apache.nifi.web.api.dto.ConnectorDTO; import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO; import org.apache.nifi.web.api.dto.NarSummaryDTO; import org.apache.nifi.web.api.dto.PropertyGroupConfigurationDTO; @@ -33,6 +36,7 @@ import org.junit.jupiter.api.Test; import java.io.File; +import java.io.IOException; import java.util.Map; import java.util.Properties; import java.util.Set; @@ -40,6 +44,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class ConnectorChangeVersionIT extends NiFiSystemIT { @@ -125,6 +130,12 @@ public void testChangeConnectorNarVersionPreservesManagedFlowAndOverlappingConfi assertEquals(VERSION_ONE, connector.getComponent().getBundle().getVersion()); assertEquals(managedProcessGroupId, connector.getComponent().getManagedProcessGroupId()); assertEquals(VERSION_ONE_FLOW_NAME, getManagedProcessGroupName(connector)); + final String connectorId = connector.getId(); + assertNotNull(getClientUtil().getConnectorActionReasonNotAllowed(connectorId, "CHANGE_VERSION")); + assertThrows(NiFiClientException.class, () -> updateConnectorVersion(connectorId, VERSION_TWO)); + connector = getNifiClient().getConnectorClient().getConnector(connector.getId()); + assertEquals(ConnectorState.TROUBLESHOOTING.name(), connector.getComponent().getState()); + assertEquals(VERSION_ONE, connector.getComponent().getBundle().getVersion()); final ProcessorEntity troubleshootingProcessor = getClientUtil().createProcessor("Sleep", managedProcessGroupId); assertTrue(containsProcessorId(connector.getId(), troubleshootingProcessor.getId())); @@ -167,6 +178,18 @@ private void changeConnectorVersion(final String currentVersion, final String ta new ChangeVersionConnector().doExecute(getNifiClient(), properties); } + private void updateConnectorVersion(final String connectorId, final String version) throws NiFiClientException, IOException { + final ConnectorEntity current = getNifiClient().getConnectorClient().getConnector(connectorId); + final ConnectorDTO component = new ConnectorDTO(); + component.setId(connectorId); + component.setBundle(new BundleDTO(BUNDLE_GROUP, BUNDLE_ARTIFACT, version)); + final ConnectorEntity update = new ConnectorEntity(); + update.setId(connectorId); + update.setRevision(current.getRevision()); + update.setComponent(component); + getNifiClient().getConnectorClient().updateConnector(update); + } + private String getManagedProcessGroupName(final ConnectorEntity connector) throws Exception { final ProcessGroupFlowEntity flowEntity = getNifiClient().getConnectorClient().getFlow(connector.getId()); return flowEntity.getProcessGroupFlow().getBreadcrumb().getBreadcrumb().getName(); diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java index 40b46eeacb0d..b4113a39c670 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java @@ -17,6 +17,7 @@ package org.apache.nifi.tests.system.connectors; +import org.apache.nifi.components.connector.ConnectorState; import org.apache.nifi.tests.system.NiFiSystemIT; import org.apache.nifi.toolkit.client.ConnectorClient; import org.apache.nifi.toolkit.client.NiFiClientException; @@ -108,6 +109,20 @@ public void testParameterContextInheritanceWithSensitiveAndAssetParameters() thr assertEquals(SENSITIVE_SECRET_VALUE, sensitiveContent, "Sensitive output file should contain the secret value"); assertEquals(ASSET_FILE_CONTENT, assetContent, "Asset output file should contain the asset file contents"); + + // A same-bundle restart resumes the Connector with its sensitive and asset parameters still resolved + getNiFiInstance().stop(); + assertTrue(sensitiveOutputFile.delete()); + assertTrue(assetOutputFile.delete()); + getNiFiInstance().start(); + if (getNumberOfNodes() > 1) { + waitForAllNodesConnected(); + } + + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + waitFor(() -> sensitiveOutputFile.exists() && assetOutputFile.exists()); + assertEquals(SENSITIVE_SECRET_VALUE, Files.readString(sensitiveOutputFile.toPath()).trim()); + assertEquals(ASSET_FILE_CONTENT, Files.readString(assetOutputFile.toPath()).trim()); } private ConnectorValueReferenceDTO createStringLiteralRef(final String value) { diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java new file mode 100644 index 000000000000..721411035bd0 --- /dev/null +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java @@ -0,0 +1,132 @@ +/* + * 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.connectors; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.util.NiFiProperties; +import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; +import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO; +import org.apache.nifi.web.api.dto.PropertyGroupConfigurationDTO; +import org.apache.nifi.web.api.entity.ConnectorEntity; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * A NAR-swap upgrade applies configuration supplied by the external provider. + */ +public class ConnectorUpgradeDrainProviderIT extends AbstractNarSwapUpgradeDrainIT { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String COMMENT = "Comment"; + private static final String LEGACY_NOTE = "Legacy Note"; + private static final String DRAIN_LABEL = "Drain Label"; + private static final String SUPPLIED_COMMENT = "supplied-by-provider"; + + private final Path providerState = createProviderState(); + + @Override + protected Map getNifiPropertiesOverrides() { + return Map.of(NiFiProperties.CONNECTOR_CONFIGURATION_PROVIDER_IMPLEMENTATION, "org.apache.nifi.connectors.tests.system.FileConnectorConfigurationProvider", NiFiProperties + .CONNECTOR_CONFIGURATION_PROVIDER_PROPERTIES_PREFIX + "state.directory", providerState.toAbsolutePath().toString()); + } + + @Test + @Timeout(240) + public void testProviderSuppliedConfigurationIsAppliedByUpgrade() throws Exception { + final Map initial = properties("DRAIN", true, "shared"); + initial.put(LEGACY_NOTE, "v1-only"); + final String connectorId = createConnector("UpgradeDrainConnector", initial); + + getNiFiInstance().stop(); + supplyComment(connectorId, SUPPLIED_COMMENT); + switchOutNars(); + getNiFiInstance().start(true); + waitForCluster(); + + assertConnectorState(connectorId, ConnectorState.STOPPED); + assertPending(connectorId); + final ConnectorEntity pending = getNifiClient().getConnectorClient().getConnector(connectorId); + assertEquals("shared", configurationValue(pending.getComponent().getActiveConfiguration(), COMMENT)); + assertEquals(SUPPLIED_COMMENT, configurationValue(pending.getComponent().getWorkingConfiguration(), COMMENT)); + assertNull(configurationValue(pending.getComponent().getActiveConfiguration(), LEGACY_NOTE)); + assertNull(configurationValue(pending.getComponent().getWorkingConfiguration(), LEGACY_NOTE)); + assertEquals("upgraded", configurationValue(pending.getComponent().getActiveConfiguration(), DRAIN_LABEL)); + assertEquals("upgraded", configurationValue(pending.getComponent().getWorkingConfiguration(), DRAIN_LABEL)); + + releaseFlowFiles(); + requestStart(connectorId); + getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); + assertEquals(SUPPLIED_COMMENT, findProcessor(connectorId, "GenerateFlowFile").getComponent().getConfig().getComments()); + } + + private void supplyComment(final String connectorId, final String comment) throws IOException { + final Path liveConfiguration = providerState.resolve(connectorId).resolve("live-config.json"); + final ObjectNode configuration = (ObjectNode) OBJECT_MAPPER.readTree(liveConfiguration.toFile()); + final JsonNode steps = configuration.get("workingFlowConfiguration"); + assertNotNull(steps, "Provider configuration has no working flow configuration"); + boolean updated = false; + for (final JsonNode step : steps) { + final ObjectNode properties = step.get("properties") instanceof ObjectNode objectNode ? objectNode : null; + final ObjectNode property = properties == null || !(properties.get(COMMENT) instanceof ObjectNode) ? null : (ObjectNode) properties.get(COMMENT); + if (property != null) { + property.put("value", comment); + updated = true; + } + } + if (!updated) { + throw new AssertionError("Provider configuration has no " + COMMENT + " property"); + } + OBJECT_MAPPER.writeValue(liveConfiguration.toFile(), configuration); + } + + private static String configurationValue(final ConnectorConfigurationDTO configuration, final String propertyName) { + if (configuration == null || configuration.getConfigurationStepConfigurations() == null) { + return null; + } + for (final ConfigurationStepConfigurationDTO step : configuration.getConfigurationStepConfigurations()) { + if (!"Upgrade".equals(step.getConfigurationStepName()) || step.getPropertyGroupConfigurations() == null) { + continue; + } + for (final PropertyGroupConfigurationDTO group : step.getPropertyGroupConfigurations()) { + if (group.getPropertyValues() != null && group.getPropertyValues().containsKey(propertyName)) { + return group.getPropertyValues().get(propertyName).getValue(); + } + } + } + return null; + } + + private static Path createProviderState() { + try { + return Files.createTempDirectory("file-connector-provider"); + } catch (final IOException e) { + throw new IllegalStateException("Unable to create the provider state directory", e); + } + } +} diff --git a/nifi-system-tests/pom.xml b/nifi-system-tests/pom.xml index e6c97cba6a45..c0789c67d921 100644 --- a/nifi-system-tests/pom.xml +++ b/nifi-system-tests/pom.xml @@ -27,11 +27,12 @@ nifi-system-test-authorizer-bundle nifi-system-test-component-metric-reporter-bundle + + nifi-system-test-nar-provider-bundles nifi-system-test-extensions-bundle nifi-system-test-extensions2-bundle nifi-system-test-flow-action-reporter-bundle nifi-alternate-config-extensions-bundle - nifi-system-test-nar-provider-bundles nifi-python-test-extensions-nar nifi-system-test-suite nifi-stateless-system-test-suite From a8faae0748f5d5afbb5345ed0b119f527bc5c0c5 Mon Sep 17 00:00:00 2001 From: Bob Paulin Date: Tue, 17 Nov 2026 16:07:09 -0600 Subject: [PATCH 2/5] NIFI-16477: Address review feedback on Connector flow evolution - Keep the managed flow and configurations in flow.json when restoring the pre-upgrade flow fails at startup; an unreachable Secrets Provider counts as unresolved secrets and leaves components stopped - Complete pending stop futures exceptionally when the Connector moves to a state other than STOPPING or STOPPED - Reject START of a pending Connector that is STOPPING, PURGING or in a user-requested drain, and refuse direct start() while an upgrade is pending - Always save RUNNING when an evolution begins so a restart during the drain resumes the upgrade - Replace restore overloads and booleans with ResumeComponentState - Restore with FlowMappingOptions.forPersistedFlow, matching capture - Move flow evolution state and steps into ConnectorFlowEvolution - Make ConnectorClusterUnavailableException an IOException, move the pre-upgrade stop retry into the node, and document FlowEvolutionStatus - Add isSourceChanged helper and restore its synchronizer test - Add unit tests and a capture/restore round-trip test - Reduce system test restarts to two by reading flow.json.gz while NiFi runs, merging restart tests, and folding ConnectorUpgradeDrainProviderIT into ClusteredConnectorUpgradeDrainIT --- .../main/asciidoc/administration-guide.adoc | 2 +- .../src/main/asciidoc/developer-guide.adoc | 2 +- ...tandardVersionedComponentSynchronizer.java | 20 +- .../nifi/groups/StandardProcessGroup.java | 16 +- ...ardVersionedComponentSynchronizerTest.java | 18 + .../TestVersionedComponentFlowMapper.java | 19 - .../ConnectorClusterUnavailableException.java | 4 +- .../components/connector/ConnectorNode.java | 3 +- .../connector/FlowEvolutionStatus.java | 11 + .../connector/FrameworkFlowContext.java | 13 +- .../org/apache/nifi/groups/ProcessGroup.java | 13 +- .../nifi/groups/ResumeComponentState.java | 36 + .../connector/ConnectorFlowEvolution.java | 703 ++++++++++++++++++ .../connector/MigrationFlowContext.java | 8 +- .../connector/ParameterSecretReferences.java | 24 +- .../connector/StandardConnectorNode.java | 687 +++-------------- .../StandardConnectorRepository.java | 6 +- .../StandardConnectorStateTransition.java | 33 + .../connector/StandardFlowContext.java | 16 +- .../connector/FlowEvolutionHookConnector.java | 7 +- .../connector/StandardConnectorNodeIT.java | 121 +++ .../connector/TestStandardConnectorNode.java | 322 ++++++-- .../TestStandardConnectorRepository.java | 86 ++- .../TestStandardConnectorStateTransition.java | 27 + .../connector/TestStandardFlowContext.java | 3 +- .../service/mock/MockProcessGroup.java | 8 +- .../nifi/web/StandardNiFiServiceFacade.java | 9 +- .../tests/system/FlowDefinitionFiles.java | 3 +- .../AbstractConnectorUpgradeDrainIT.java | 50 +- ...lusteredConnectorChangeVersionDrainIT.java | 5 +- .../ClusteredConnectorUpgradeDrainIT.java | 169 ++++- .../ConnectorChangeVersionDrainIT.java | 234 +++--- .../ConnectorParameterContextIT.java | 15 - .../ConnectorUpgradeDrainProviderIT.java | 132 ---- 34 files changed, 1776 insertions(+), 1049 deletions(-) create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ResumeComponentState.java create mode 100644 nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java delete mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java diff --git a/nifi-docs/src/main/asciidoc/administration-guide.adoc b/nifi-docs/src/main/asciidoc/administration-guide.adoc index 7d16a699a07c..ad5fc98bf29b 100644 --- a/nifi-docs/src/main/asciidoc/administration-guide.adoc +++ b/nifi-docs/src/main/asciidoc/administration-guide.adoc @@ -3928,7 +3928,7 @@ These properties configure how NiFi manages Connectors. For what flow evolution |==== |*Property*|*Description* -|`nifi.connector.flow.evolution.timeout`|How long a Connector may spend draining its outgoing flow in `prepareForFlowEvolution`. Waiting for other cluster nodes to finish their drain is not limited by this timeout. Accepts any NiFi time duration value such as `30 mins`. The default value is `30 mins`. A timeout leaves the Connector stopped and still pending. +|`nifi.connector.flow.evolution.timeout`|How long a Connector may spend draining its outgoing flow in `prepareForFlowEvolution`. Each cluster node applies this timeout to its own drain. A node that finishes first waits for the others, and that wait ends as soon as any node fails, times out, or disconnects. Accepts any NiFi time duration value such as `30 mins`. The default value is `30 mins`. A timeout leaves the Connector stopped and still pending. |==== [[secrets_manager_properties]] diff --git a/nifi-docs/src/main/asciidoc/developer-guide.adoc b/nifi-docs/src/main/asciidoc/developer-guide.adoc index cda826c753d3..4ba4081653b8 100644 --- a/nifi-docs/src/main/asciidoc/developer-guide.adoc +++ b/nifi-docs/src/main/asciidoc/developer-guide.adoc @@ -2748,7 +2748,7 @@ Each node prepares on its own. Every node has already finished the hook, so the In a cluster, each node drains its own Connector. No node applies the upgraded flow until every node that still has the outgoing flow has drained it, so the Connector reports `DRAINING` while the nodes wait for one another. A node that has already applied the upgraded flow has nothing to drain and does not hold back the others. A node that disconnects after applying the upgraded flow does not block the others either: the connected nodes start. `nifi.connector.flow.evolution.timeout` limits only the local drain in `prepareForFlowEvolution`. See <> in the Administration Guide. -If evolution fails before the upgraded flow is applied, including while a node waits for the others to drain, the Connector remains stopped and still pending, and the next START runs the hook again. Stopping the Connector while it drains cancels the attempt. The failure is not saved, so after a restart the Connector comes back in the state that was last saved. +If evolution fails before the upgraded flow is applied, including while a node waits for the others to drain, the Connector remains stopped and still pending, and the next START runs the hook again. Stopping the Connector while it drains cancels the attempt. The START that begins an evolution is saved, so a restart while the Connector drains resumes the upgrade. The failure is not saved, because shutting down also interrupts the drain and must not prevent the upgrade from resuming. After a restart the Connector comes back in the state that was last saved. A failure while applying the upgraded flow leaves the Connector `UPDATE_FAILED`. The failure is not saved, so the Connector must be corrected and started again. On a node where `prepareForUpdate` or `applyUpdate` failed, the Connector is still pending and the next START retries both without the hook. On a node where the upgraded flow was applied, the Connector is no longer pending and the next START runs the new flow. diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java index d9535ce97fe0..76a99cccc1df 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizer.java @@ -823,14 +823,9 @@ private void removeMissingConnections(final ProcessGroup group, final VersionedP for (final VersionedConnection proposedConnection : proposed.getConnections()) { final Connection existingConnection = connectionsByVersionedId.get(proposedConnection.getIdentifier()); - if (existingConnection != null) { - final String proposedSourceId = proposedConnection.getSource().getId(); - final String existingSourceId = existingConnection.getSource().getVersionedComponentId().orElse(null); - - if (existingSourceId != null && !Objects.equals(proposedSourceId, existingSourceId)) { - connectionsRemovedDueToChangingSourceId.add(proposedConnection.getIdentifier()); - connectionsRemoved.add(proposedConnection.getIdentifier()); - } + if (existingConnection != null && isSourceChanged(existingConnection, proposedConnection)) { + connectionsRemovedDueToChangingSourceId.add(proposedConnection.getIdentifier()); + connectionsRemoved.add(proposedConnection.getIdentifier()); } } @@ -845,6 +840,11 @@ private void removeMissingConnections(final ProcessGroup group, final VersionedP } } + private static boolean isSourceChanged(final Connection existing, final VersionedConnection proposed) { + final String existingSourceId = existing.getSource().getVersionedComponentId().orElse(null); + return existingSourceId != null && !Objects.equals(proposed.getSource().getId(), existingSourceId); + } + private void synchronizeConnections(final ProcessGroup group, final VersionedProcessGroup proposed, final Map connectionsByVersionedId) { // Add and update Connections for (final VersionedConnection proposedConnection : proposed.getConnections()) { @@ -4128,9 +4128,7 @@ private void verifyCanRemoveMissingComponents(final ProcessGroup processGroup, f + "does not contain a match for " + connection + " and the connection currently has data in the queue."); } - final String existingSourceId = connection.getSource().getVersionedComponentId().orElse(null); - final String proposedSourceId = proposedConnection.getSource().getId(); - if (existingSourceId != null && !Objects.equals(proposedSourceId, existingSourceId)) { + if (isSourceChanged(connection, proposedConnection)) { throw new IllegalStateException(processGroup + " cannot be updated to the proposed flow because the proposed flow " + "changes the source of " + connection + " and the connection currently has data in the queue."); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java index 4ad55f6a5c6d..2e7d3f59a9e3 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/groups/StandardProcessGroup.java @@ -4027,12 +4027,7 @@ public void updateFlow(final VersionedExternalFlow proposedSnapshot, final Strin } @Override - public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedSnapshot) { - restoreFlowPreservingIdentifiers(proposedSnapshot, autoResumeState); - } - - @Override - public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedSnapshot, final boolean resumeComponentState) { + public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedSnapshot, final ResumeComponentState resumeComponentState) { // Use the Instance Identifier captured in the persisted flow as the runtime identifier for every component. This is // required so that Connection identifiers (and therefore FlowFile queue identifiers) match what was in use before // the flow was persisted. Without this, queued FlowFiles in the FlowFile Repository cannot be re-associated with @@ -4040,10 +4035,11 @@ public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow propose final ComponentIdGenerator idGenerator = (proposedId, instanceId, destinationGroupId) -> instanceId; final VersionedComponentStateLookup stateLookup = VersionedComponentStateLookup.IDENTITY_LOOKUP; - // resumeComponentState=false restores the flow structure (so queued FlowFiles can be re-associated with their - // Connections) without resuming any component to its previously running or enabled state. When true, restore each - // component to the running/enabled state captured in the persisted flow. - final ComponentScheduler componentScheduler = resumeComponentState + // LEAVE_STOPPED restores the flow structure (so queued FlowFiles can be re-associated with their Connections) without + // resuming any component to its previously running or enabled state. RESUME_AS_PERSISTED restores each component + // to the running/enabled state captured in the persisted flow, unless auto-resume is disabled. + final boolean resumeStates = resumeComponentState == ResumeComponentState.RESUME_AS_PERSISTED && autoResumeState; + final ComponentScheduler componentScheduler = resumeStates ? new DefaultComponentScheduler(controllerServiceProvider, stateLookup) : new NonStartingComponentScheduler(controllerServiceProvider, stateLookup); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizerTest.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizerTest.java index b9ae7efa2b81..04dd9cb8e400 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizerTest.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/flow/synchronization/StandardVersionedComponentSynchronizerTest.java @@ -1152,6 +1152,24 @@ public void testRemoveInputPortFailsIfOutgoingConnectionNotEmpty() throws FlowSy assertThrows(TimeoutException.class, () -> synchronizer.synchronize(inputPort, null, group, synchronizationOptions)); } + @Test + public void testVerifyCanSynchronizeRejectsSourceChangeWhileQueueHasData() { + when(processorA.getVersionedComponentId()).thenReturn(Optional.of("processor-a")); + when(connectionAB.getVersionedComponentId()).thenReturn(Optional.of("connection-ab")); + + final VersionedConnection proposedConnection = createMinimalVersionedConnection(processorB, processorB); + proposedConnection.setIdentifier("connection-ab"); + proposedConnection.getSource().setId("processor-b"); + final VersionedProcessGroup proposedGroup = new VersionedProcessGroup(); + proposedGroup.setConnections(Set.of(proposedConnection)); + + synchronizer.verifyCanSynchronize(group, proposedGroup, true); + + queuesWithData.add(connectionAB.getIdentifier()); + final IllegalStateException exception = assertThrows(IllegalStateException.class, () -> synchronizer.verifyCanSynchronize(group, proposedGroup, true)); + assertTrue(exception.getMessage().contains("changes the source of")); + } + @Test public void testAddsControllerService() throws FlowSynchronizationException, InterruptedException, TimeoutException { final VersionedControllerService versionedService = createMinimalVersionedControllerService(); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java index 0e84c6a388c3..5916ef43cd33 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java @@ -214,25 +214,6 @@ public void testControllerServicesMapsToInstanceId() { testControllerServicesMapsToProperId(false); } - @Test - public void testPersistedFlowMappingUsesInstanceIdForControllerServiceReferences() { - final VersionedComponentFlowMapper mapper = VersionedComponentFlowMapper.forPersistedFlow( - mock(ExtensionManager.class), new RecordingPropertyEncryptionProvider(), VersionedComponentStateLookup.IDENTITY_LOOKUP); - - final ControllerServiceNode mockServiceNode = mock(ControllerServiceNode.class); - when(mockServiceNode.getIdentifier()).thenReturn("1234"); - when(mockServiceNode.getVersionedComponentId()).thenReturn(Optional.of("versioned")); - - final ControllerServiceProvider serviceProvider = mock(ControllerServiceProvider.class); - when(serviceProvider.getControllerServiceNode("1234")).thenReturn(mockServiceNode); - final Map properties = new HashMap<>(); - properties.put("Service A", "1234"); - - final ProcessorNode procNode = createProcessorNode(properties); - final VersionedProcessor versionedProcessor = mapper.mapProcessor(procNode, serviceProvider, Collections.emptySet(), Collections.emptyMap()); - assertEquals("1234", versionedProcessor.getProperties().get("Service A")); - } - private void testControllerServicesMapsToProperId(final boolean useVersionedId) { final ExtensionManager extensionManager = mock(ExtensionManager.class); final FlowMappingOptions mappingOptions = new FlowMappingOptions.Builder() diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java index bedca7e6c383..66943f5e2524 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorClusterUnavailableException.java @@ -17,10 +17,12 @@ package org.apache.nifi.components.connector; +import java.io.IOException; + /** * Thrown when a clustered Connector request cannot be completed because no node is connected yet. */ -public class ConnectorClusterUnavailableException extends RuntimeException { +public class ConnectorClusterUnavailableException extends IOException { public ConnectorClusterUnavailableException(final String message) { super(message); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java index e4314d28769b..e80254d71e45 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java @@ -351,9 +351,10 @@ default FlowEvolutionStatus getReportedFlowEvolutionStatus() { * Moves a pending upgrade from STOPPED or UPDATE_FAILED to DRAINING and creates the evolution context. When an earlier * attempt failed after every node had drained, this attempt resumes after the hook without running it again. * + * @param scheduler lifecycle scheduler used to keep stopping the outgoing flow when a failed attempt cannot stop it right away * @throws IllegalStateException if no evolution is pending or the Connector is not STOPPED or UPDATE_FAILED */ - void prepareFlowEvolution(); + void prepareFlowEvolution(FlowEngine scheduler); /** * Runs preflight, the Connector evolution hook, and the local evolve-drain phase on the provided executor. The executor diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java index 5bd919041544..ce93735f45ea 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FlowEvolutionStatus.java @@ -22,6 +22,13 @@ /** * Reports local progress through the evolve-drain phase of a pending Connector flow evolution. Applying the upgraded flow * after the evolve-drain phase is tracked through {@link ConnectorState}, as for a configuration update. + * + *

+ * A node reports {@link #INACTIVE} until an upgrade is pending, and {@link #EVOLVE_DRAIN_PENDING} from then on, even before + * the first START. When the local drain finishes, the status becomes {@link #EVOLVE_DRAIN_COMPLETE} and stays there while the + * upgraded flow is applied. Once the upgraded flow is applied and its snapshot captured, the status returns to {@link #INACTIVE}. + * There is no separate completed value, because {@link #INACTIVE} means that nothing is pending. + *

*/ public enum FlowEvolutionStatus { /** @@ -39,6 +46,10 @@ public enum FlowEvolutionStatus { */ EVOLVE_DRAIN_COMPLETE, + /** + * The current evolution attempt failed or was cancelled on this node. It is reported instead of the drain status until + * the next START prepares a new attempt, which then reports the drain status again. + */ FAILED; /** diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java index e0b8be362d98..08418cc6eb95 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/FrameworkFlowContext.java @@ -24,6 +24,7 @@ import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.logging.ComponentLog; public interface FrameworkFlowContext extends FlowContext { @@ -47,19 +48,11 @@ public interface FrameworkFlowContext extends FlowContext { /** * Restores a persisted authoritative flow into the managed process group, keeping component identifiers. - * Components resume according to the Process Group's auto-resume setting. * @param persistedFlow the flow to restore * @param parameterContext the parameter context that belonged to that flow, or null + * @param resumeComponentState whether components resume the scheduled state captured in the flow */ - void restorePersistedFlow(VersionedProcessGroup persistedFlow, VersionedParameterContext parameterContext); - - /** - * Restores a persisted authoritative flow into the managed process group, keeping component identifiers. - * @param persistedFlow the flow to restore - * @param parameterContext the parameter context that belonged to that flow, or null - * @param resumeComponentState whether components should resume the running or enabled state captured in the snapshot - */ - void restorePersistedFlow(VersionedProcessGroup persistedFlow, VersionedParameterContext parameterContext, boolean resumeComponentState); + void restorePersistedFlow(VersionedProcessGroup persistedFlow, VersionedParameterContext parameterContext, ResumeComponentState resumeComponentState); default void reload(final Bundle bundle, final ComponentLog connectorLog) { reload(bundle, connectorLog, getConfigurationContext()); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java index 9c3c5f3e0c62..e7d349a4528d 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ProcessGroup.java @@ -973,18 +973,9 @@ default CompletableFuture stopComponents() { * in the FlowFile Repository can be re-associated with their Connections after a restart). * * @param proposedSnapshot the proposed flow whose Instance Identifiers should be used as runtime identifiers + * @param resumeComponentState whether components resume the scheduled state captured in the snapshot */ - void restoreFlowPreservingIdentifiers(VersionedExternalFlow proposedSnapshot); - - /** - * Restores a previously persisted flow while controlling whether components resume their captured scheduled state. - * When {@code resumeComponentState} is false, the flow structure is restored so queued FlowFiles can reattach, but - * no component is started or enabled. - * - * @param proposedSnapshot the proposed flow whose Instance Identifiers should be used as runtime identifiers - * @param resumeComponentState whether components should resume the running or enabled state captured in the snapshot - */ - void restoreFlowPreservingIdentifiers(VersionedExternalFlow proposedSnapshot, boolean resumeComponentState); + void restoreFlowPreservingIdentifiers(VersionedExternalFlow proposedSnapshot, ResumeComponentState resumeComponentState); /** * Updates the Process Group to match the proposed flow diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ResumeComponentState.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ResumeComponentState.java new file mode 100644 index 000000000000..40c50c6d6f6b --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/groups/ResumeComponentState.java @@ -0,0 +1,36 @@ +/* + * 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.groups; + +/** + * Specifies whether the components of a restored flow resume the scheduled state captured in that flow. + */ +public enum ResumeComponentState { + + /** + * Components resume the running or enabled state captured in the flow, subject to the + * {@code nifi.flowcontroller.autoResumeState} setting. + */ + RESUME_AS_PERSISTED, + + /** + * The flow structure is restored so queued FlowFiles can be re-associated with their Connections, but no component is + * started or enabled. + */ + LEAVE_STOPPED +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java new file mode 100644 index 000000000000..4f7f7f12a5fe --- /dev/null +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java @@ -0,0 +1,703 @@ +/* + * 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.components.ValidationResult; +import org.apache.nifi.engine.FlowEngine; +import org.apache.nifi.flow.Bundle; +import org.apache.nifi.flow.VersionedExternalFlow; +import org.apache.nifi.flow.VersionedParameterContext; +import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.logging.ComponentLog; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.UnaryOperator; + +/** + * The flow evolution state of one Connector: the authoritative snapshot that records the outgoing flow, the progress through + * the evolve-drain phase, and the current evolution attempt. The evolution lock guards every change to the snapshot and the + * attempt, and every Connector state transition that an evolution makes. The progress and the snapshot may be read without it. + */ +final class ConnectorFlowEvolution { + private static final Logger logger = LoggerFactory.getLogger(ConnectorFlowEvolution.class); + + /** + * The parts of the Connector that a flow evolution reads or calls. + */ + interface EvolvingConnector { + boolean isExtensionMissing(); + + /** + * @return the bundle of the loaded Connector, or null when it is not known + */ + Bundle getLoadedBundle(); + + FrameworkFlowContext getActiveFlowContext(); + + ComponentLog getComponentLog(); + + ParameterSecretReferences.Resolution resolveParameterSecrets(VersionedParameterContext parameterContext, Map parameterSecretReferences); + + void setUnresolvedParameterSecretReferences(Map unresolvedReferences); + + /** + * @return a validation result for each managed component whose extension is missing + */ + List validateManagedFlowComponents(); + + CompletableFuture invokeFlowEvolutionHook(FlowEvolutionContext context) throws FlowUpdateException; + + /** + * @return the flow that the upgraded Connector builds from its working configuration + */ + VersionedExternalFlow getUpgradedFlow() throws Exception; + + ConnectorFlowSnapshot captureSnapshot(); + } + + private final EvolvingConnector connector; + private final ConnectorStateTransition stateTransition; + private final Object lock = new Object(); + private final AtomicReference progress = new AtomicReference<>(FlowEvolutionProgress.NONE); + private volatile ConnectorFlowSnapshot authoritativeSnapshot; + // Written only while holding the lock + private volatile FlowEvolutionAttempt latestAttempt; + + ConnectorFlowEvolution(final EvolvingConnector connector, final ConnectorStateTransition stateTransition) { + this.connector = Objects.requireNonNull(connector, "Evolving Connector is required"); + this.stateTransition = Objects.requireNonNull(stateTransition, "State Transition is required"); + } + + boolean isPending() { + synchronized (lock) { + if (connector.isExtensionMissing()) { + return false; + } + + final ConnectorFlowSnapshot snapshot = authoritativeSnapshot; + final Bundle snapshotBundle = snapshot == null ? null : snapshot.bundle(); + return snapshotBundle != null && !sameBundle(snapshotBundle, connector.getLoadedBundle()); + } + } + + FlowEvolutionStatus getReportedStatus() { + return progress.get().reportedStatus(); + } + + boolean isDrainComplete() { + return progress.get().isDrainComplete(); + } + + boolean isApplyingEvolvedFlow() { + return getReportedStatus() == FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE; + } + + boolean hasFailed() { + return progress.get().hasFailed(); + } + + /** + * @return the explanation of the current failure, or null when the evolution has not failed + */ + String getFailureExplanation() { + return progress.get().failureExplanation(); + } + + ConnectorFlowSnapshot getSnapshot() { + return authoritativeSnapshot; + } + + private VersionedProcessGroup getSnapshotFlow() { + final ConnectorFlowSnapshot snapshot = authoritativeSnapshot; + return snapshot == null ? null : snapshot.flow(); + } + + /** + * Moves a pending upgrade from STOPPED or UPDATE_FAILED to DRAINING and opens a new attempt. + * + * @param scheduler lifecycle scheduler used to keep stopping the outgoing flow when the attempt fails and cannot stop it right away + */ + void prepare(final FlowEngine scheduler) { + Objects.requireNonNull(scheduler, "Scheduler is required"); + synchronized (lock) { + if (!isPending()) { + throw new IllegalStateException("Cannot prepare flow evolution for " + connector + " because no evolution is pending"); + } + // Hook progress outlives an attempt only once every node has drained, so the outgoing flow is no longer needed. + final boolean drainCompletedInEarlierAttempt = isDrainComplete(); + if (!stateTransition.trySetCurrentState(ConnectorState.STOPPED, ConnectorState.DRAINING) + && !stateTransition.trySetCurrentState(ConnectorState.UPDATE_FAILED, ConnectorState.DRAINING)) { + throw new IllegalStateException("Cannot prepare flow evolution for " + connector + " from state " + stateTransition.getCurrentState()); + } + + progress.set(new FlowEvolutionProgress(drainCompletedInEarlierAttempt + ? FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE + : FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, null)); + final Bundle postUpgradeBundle = connector.getLoadedBundle(); + final ConnectorFlowSnapshot outgoingSnapshot = authoritativeSnapshot; + final Bundle preUpgradeBundle = outgoingSnapshot == null || outgoingSnapshot.bundle() == null ? postUpgradeBundle : outgoingSnapshot.bundle(); + final PreUpgradeFlowContext preUpgradeFlowContext = new PreUpgradeFlowContext(connector.getActiveFlowContext(), preUpgradeBundle); + final StandardFlowEvolutionContext context = new StandardFlowEvolutionContext(preUpgradeFlowContext, postUpgradeBundle); + latestAttempt = new FlowEvolutionAttempt(context, drainCompletedInEarlierAttempt, scheduler); + // Only a start request begins an evolution, so the connector is desired RUNNING while it drains and once the + // upgraded flow is applied. A node that joins while this connector is draining inherits the flow mapped from the + // desired state, so it also starts and enters the same evolution. + stateTransition.setDesiredState(ConnectorState.RUNNING); + } + } + + boolean isInProgress() { + synchronized (lock) { + // Desired state cannot say this. stop() sets the desired state to STOPPED before it aborts the evolution. + // The drain status cannot say this either, because a pending evolution reports EVOLVE_DRAIN_PENDING before its attempt + // begins, while a user-requested drain may also be running. + final StandardFlowEvolutionContext context = currentContext(); + return stateTransition.getCurrentState() == ConnectorState.DRAINING + && context != null + && !context.isFailed() + && !hasFailed(); + } + } + + /** + * Cancels the evolution in progress, if there is one. + * + * @param whileInProgress runs while holding the evolution lock, only when an evolution is in progress and before it is cancelled + * @return whether an evolution was in progress + */ + boolean cancelInProgress(final Runnable whileInProgress) { + synchronized (lock) { + if (!isInProgress()) { + return false; + } + + whileInProgress.run(); + } + + // Recorded before cancelling, because the coordinator wakes on the cancellation and must see the failure to stop the Connector + publishFailure("Flow evolution was cancelled", null); + closeCurrentAttempt(); + return true; + } + + /** + * Runs preflight, the Connector evolution hook, and the local evolve-drain phase on the provided executor. + * + * @return the future for the local evolve-drain phase of the prepared attempt + */ + Future evolve(final ExecutorService executor) throws FlowUpdateException { + Objects.requireNonNull(executor, "Executor Service is required"); + + synchronized (lock) { + final StandardFlowEvolutionContext context = currentContext(); + verifyContext(context); + final FlowEvolutionAttempt attempt = latestAttempt; + if (attempt.evolveFuture != null) { + return attempt.evolveFuture; + } + + attempt.evolveFuture = executor.submit(() -> { + runEvolveDrainPhase(context); + return null; + }); + return attempt.evolveFuture; + } + } + + private void runEvolveDrainPhase(final StandardFlowEvolutionContext context) throws FlowUpdateException { + runPreflight(context); + if (isDrainComplete()) { + return; + } + + verifyContext(context); + final CompletableFuture connectorFuture; + try { + connectorFuture = Objects.requireNonNull(connector.invokeFlowEvolutionHook(context), "Connector prepareForFlowEvolution must return a CompletableFuture"); + } catch (final FlowUpdateException e) { + fail(context, e.getMessage(), e); + throw e; + } + + try { + synchronized (lock) { + verifyContext(context); + latestAttempt.prepareFuture = connectorFuture; + } + } catch (final FlowUpdateException e) { + connectorFuture.cancel(true); + throw e; + } + + try { + connectorFuture.get(); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new FlowUpdateException("Interrupted while waiting for flow evolution hook for " + connector, e); + } catch (final CancellationException e) { + throw new FlowUpdateException("Flow evolution hook was cancelled for " + connector, e); + } catch (final ExecutionException e) { + final Throwable cause = e.getCause() == null ? e : e.getCause(); + fail(context, cause.getMessage(), cause); + throw new FlowUpdateException("Flow evolution hook failed for " + connector, cause); + } + + completeEvolveDrainPhase(context); + } + + private void runPreflight(final StandardFlowEvolutionContext context) throws FlowUpdateException { + verifyContext(context); + if (!isDrainComplete()) { + refreshPreUpgradeParameterSecrets(context); + } + + final List ghostResults = connector.validateManagedFlowComponents(); + if (!ghostResults.isEmpty()) { + final String explanation = ghostResults.getFirst().getExplanation(); + fail(context, explanation, null); + throw new FlowUpdateException(explanation); + } + + verifyContext(context); + } + + private void refreshPreUpgradeParameterSecrets(final StandardFlowEvolutionContext context) throws FlowUpdateException { + final ConnectorFlowSnapshot snapshot = authoritativeSnapshot; + if (snapshot == null || snapshot.parameterContext() == null) { + verifyContext(context); + connector.setUnresolvedParameterSecretReferences(Map.of()); + return; + } + + final ParameterSecretReferences.Resolution resolution = connector.resolveParameterSecrets(snapshot.parameterContext(), snapshot.parameterSecretReferences()); + if (!resolution.unresolvedReferences().isEmpty()) { + final Map.Entry unresolved = resolution.unresolvedReferences().entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .findFirst() + .orElseThrow(); + final SecretReference reference = unresolved.getValue(); + final String secretName = reference.getFullyQualifiedName() == null ? reference.getSecretName() : reference.getFullyQualifiedName(); + final String explanation = "Flow evolution cannot start: secret [%s] used by parameter [%s] could not be resolved. " + .formatted(secretName, unresolved.getKey()) + + "Restore the secret in its provider, then start the Connector to resume the upgrade."; + verifyContext(context); + connector.setUnresolvedParameterSecretReferences(Map.copyOf(resolution.unresolvedReferences())); + fail(context, explanation, null); + throw new FlowUpdateException(explanation); + } + + verifyContext(context); + connector.setUnresolvedParameterSecretReferences(Map.of()); + if (!resolution.parameterValues().isEmpty()) { + connector.getActiveFlowContext().getParameterContext().updateParameters(resolution.parameterValues()); + } + } + + private void completeEvolveDrainPhase(final StandardFlowEvolutionContext context) throws FlowUpdateException { + // The hook may start processors so queues can empty. Those processors must be stopped before the upgraded + // flow is verified, so no FlowFile reaches a connection the upgraded flow removes after it has been checked. + verifyContext(context); + if (!stopPreUpgradeFlow()) { + fail(context, "Failed to stop the pre-upgrade flow", null); + throw new FlowUpdateException("Failed to stop the pre-upgrade flow for " + connector); + } + + verifyUpgradedFlow(context); + + synchronized (lock) { + verifyContext(context); + progress.updateAndGet(current -> current.withDrainStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE)); + } + } + + /** + * Fails the evolution if the upgraded flow cannot replace the active flow, for example because it removes a + * connection that still holds FlowFiles. + */ + private void verifyUpgradedFlow(final StandardFlowEvolutionContext context) throws FlowUpdateException { + verifyContext(context); + final VersionedExternalFlow proposedFlow; + try { + proposedFlow = connector.getUpgradedFlow(); + } catch (final Exception failure) { + fail(context, failure.getMessage(), failure); + throw new FlowUpdateException("Failed to determine the upgraded flow for " + connector, failure); + } + if (proposedFlow == null || proposedFlow.getFlowContents() == null) { + fail(context, "Upgraded flow was not returned", null); + throw new FlowUpdateException("Upgraded flow was not returned for " + connector); + } + + verifyContext(context); + try { + connector.getActiveFlowContext().verifyUpdateFlow(proposedFlow); + } catch (final FlowUpdateException e) { + fail(context, e.getMessage(), e); + throw e; + } + } + + private void verifyContext(final StandardFlowEvolutionContext context) throws FlowUpdateException { + if (currentContext() != context || context == null || context.isFailed() || hasFailed() || stateTransition.getCurrentState() != ConnectorState.DRAINING) { + throw new FlowUpdateException("Flow evolution was cancelled for " + connector); + } + } + + /** + * @return the context of the current or most recent attempt, or null when no attempt has begun while the evolution is pending + */ + private StandardFlowEvolutionContext currentContext() { + final FlowEvolutionAttempt attempt = latestAttempt; + return attempt == null ? null : attempt.context; + } + + /** + * {@link Connector#applyUpdate} must be safe to run again on a flow it has already partly updated, because a start + * after a failed apply resumes after the hook and applies again. + */ + void beginEvolvedFlowUpdate() throws FlowUpdateException { + // Checked again after the drain barrier because an attempt that resumes after the hook skips the evolve-drain phase, and the + // persisted flow is replaced once the upgraded flow is applied. + verifyUpgradedFlow(currentContext()); + + synchronized (lock) { + if (!isInProgress() || !isDrainComplete()) { + throw new FlowUpdateException("Cannot apply the upgraded flow for " + connector + " because the evolve-drain phase is not complete"); + } + + // Leaving DRAINING closes the evolution attempt, and prepareForUpdate follows as for any configuration update. + // The status stays EVOLVE_DRAIN_COMPLETE until the upgraded flow is applied so a peer still waiting on the drain + // barrier passes it. The desired state stays RUNNING, because only a start request begins an evolution. + stateTransition.setCurrentState(ConnectorState.PREPARING_FOR_UPDATE); + } + } + + /** + * Marks this attempt failed and cancels its hook after releasing the evolution lock. The hook future is copied + * under the lock so a newer attempt is not cancelled. This does not cancel the evolve-drain task, because it runs + * on that task and cancelling it would interrupt the task before it stops the pre-upgrade flow. + * + * @param expectedContext the context of the attempt to close + * @return false when the context is already closed or has been replaced + */ + private boolean closeAttempt(final StandardFlowEvolutionContext expectedContext) { + final CompletableFuture prepareFuture; + synchronized (lock) { + final FlowEvolutionAttempt attempt = latestAttempt; + if (attempt == null || attempt.context.isFailed() || attempt.context != expectedContext) { + return false; + } + + attempt.context.fail(); + prepareFuture = attempt.prepareFuture; + } + + cancel(prepareFuture); + return true; + } + + /** + * Marks the current attempt failed and cancels its hook and evolve-drain task. The futures are copied under the + * evolution lock so a newer attempt started after this close is not cancelled. + */ + private void closeCurrentAttempt() { + final CompletableFuture prepareFuture; + final Future evolveDrainTask; + synchronized (lock) { + final FlowEvolutionAttempt attempt = latestAttempt; + if (attempt == null || attempt.context.isFailed()) { + return; + } + + attempt.context.fail(); + prepareFuture = attempt.prepareFuture; + evolveDrainTask = attempt.evolveFuture; + } + + cancel(evolveDrainTask); + cancel(prepareFuture); + } + + private static void cancel(final Future future) { + if (future != null) { + future.cancel(true); + } + } + + private void fail(final StandardFlowEvolutionContext context, final String explanation, final Throwable cause) { + if (!closeAttempt(context)) { + return; + } + + finishFailure(explanation, cause); + } + + /** + * Fails the current attempt, or finishes a failure that was already recorded, and stops the outgoing flow. + */ + void fail(final String explanation, final Throwable cause) { + closeCurrentAttempt(); + finishFailure(explanation, cause); + } + + private void finishFailure(final String explanation, final Throwable cause) { + if (!isDrainComplete() && !stopPreUpgradeFlow()) { + publishFailure(explanation, cause); + synchronized (lock) { + stateTransition.setDesiredState(ConnectorState.STOPPED); + stateTransition.setCurrentState(ConnectorState.STOPPING); + } + schedulePreUpgradeStopRetry(); + return; + } + + publishFailure(explanation, cause); + synchronized (lock) { + stateTransition.setDesiredState(ConnectorState.STOPPED); + stateTransition.setCurrentState(ConnectorState.STOPPED); + // A peer may not have drained yet, so the next attempt drains again. An attempt that started after this + // node's drain had already completed keeps that progress, because the drain barrier may already have passed + // and the upgraded flow may have been partly applied. + final FlowEvolutionAttempt attempt = latestAttempt; + if (attempt == null || !attempt.drainCompletedInEarlierAttempt) { + progress.updateAndGet(current -> current.replaceDrainStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING)); + } + } + } + + private void publishFailure(final String explanation, final Throwable cause) { + final String concreteExplanation = explanation == null || explanation.isBlank() + ? cause == null ? "Unknown flow evolution failure" : cause.getClass().getSimpleName() + : explanation; + final FlowEvolutionProgress previous = progress.getAndUpdate(current -> current.withFailureIfAbsent(concreteExplanation)); + if (!previous.hasFailed()) { + connector.getComponentLog().error("Flow evolution failed: {}", concreteExplanation, cause); + } + } + + /** + * Keeps stopping the pre-upgrade flow after {@link #finishFailure} left the connector STOPPING, using the scheduler of + * the failed attempt. Only one retry is scheduled per attempt, although a failure may be finished more than once. + */ + private void schedulePreUpgradeStopRetry() { + final FlowEngine scheduler; + synchronized (lock) { + final FlowEvolutionAttempt attempt = latestAttempt; + if (attempt == null || attempt.preUpgradeStopRetryScheduled) { + return; + } + + attempt.preUpgradeStopRetryScheduled = true; + scheduler = attempt.scheduler; + } + + scheduler.schedule(() -> retryPreUpgradeStop(scheduler, 0), 0, TimeUnit.SECONDS); + } + + /** + * Completes pending stop futures when the stop succeeds. The Connector is not started again, because the upgrade + * is still pending and only the Connector Repository may start it. + */ + private void retryPreUpgradeStop(final FlowEngine scheduler, final int attempt) { + if (stateTransition.getCurrentState() != ConnectorState.STOPPING) { + return; + } + + if (stopPreUpgradeFlow()) { + synchronized (lock) { + if (stateTransition.getCurrentState() != ConnectorState.STOPPING) { + return; + } + stateTransition.setCurrentState(ConnectorState.STOPPED); + } + logger.info("Successfully stopped the pre-upgrade flow for {} after a failed evolution", connector); + return; + } + + final long delaySeconds = Math.min(60L, 1L << Math.min(attempt, 5)); + logger.warn("Failed to stop the pre-upgrade flow for {}. Will try again in {} seconds", connector, delaySeconds); + scheduler.schedule(() -> retryPreUpgradeStop(scheduler, attempt + 1), delaySeconds, TimeUnit.SECONDS); + } + + /** + * @return whether the pre-upgrade flow stopped + */ + private boolean stopPreUpgradeFlow() { + try { + final CompletableFuture stopped = connector.getActiveFlowContext().getRootGroup().getLifecycle().stop(); + if (stopped != null) { + stopped.get(1, TimeUnit.MINUTES); + } + return true; + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Interrupted while stopping the pre-upgrade flow for {}", connector, e); + return false; + } catch (final Exception e) { + logger.warn("Failed to stop the pre-upgrade flow for {}", connector, e); + return false; + } + } + + /** + * Captures the live flow outside the evolution lock, because capturing resolves secrets, then installs it under the lock + * after checking again that it may be installed. + */ + void captureSnapshot() { + verifyCanCaptureSnapshot(); + final ConnectorFlowSnapshot snapshot = connector.captureSnapshot(); + + synchronized (lock) { + verifyCanCaptureSnapshot(); + installSnapshot(snapshot); + } + } + + /** + * Captures the live flow when there is no snapshot, so that a later upgrade has a pre-upgrade flow to evolve. + */ + void ensureSnapshot() { + if (getSnapshotFlow() != null || connector.isExtensionMissing()) { + return; + } + + verifyCanCaptureSnapshot(); + final ConnectorFlowSnapshot snapshot = connector.captureSnapshot(); + + synchronized (lock) { + // Another thread may have installed a snapshot, such as the pre-upgrade flow, while the live flow was being captured + if (getSnapshotFlow() != null) { + return; + } + + verifyCanCaptureSnapshot(); + installSnapshot(snapshot); + } + } + + private void verifyCanCaptureSnapshot() { + // Applying the upgraded flow after the evolve-drain phase records the new bundle, which is what ends the pending evolution. + if (isPending() && !isDrainComplete()) { + throw new IllegalStateException("Cannot capture an authoritative snapshot for " + connector + " while flow evolution is pending"); + } + } + + /** + * Installs the snapshot computed from the current one while holding the evolution lock. + */ + void updateSnapshot(final UnaryOperator update) { + synchronized (lock) { + installSnapshot(update.apply(authoritativeSnapshot)); + } + } + + /** + * Installs the snapshot and brings the drain status in line with whether an evolution is now pending. This is the only + * writer of the snapshot. It must also be called, with the current snapshot, whenever the loaded bundle or whether the + * extension is missing changes. + */ + void installSnapshot(final ConnectorFlowSnapshot snapshot) { + synchronized (lock) { + authoritativeSnapshot = snapshot; + + // Once the snapshot records the loaded bundle no evolution is pending, so no attempt is open and neither its drain progress + // nor its failure applies. + if (!isPending()) { + progress.set(FlowEvolutionProgress.NONE); + latestAttempt = null; + return; + } + + // A node that still has the outgoing flow reports it as pending even before its own attempt begins, so a peer + // does not apply the upgraded flow while this node may still need to drain. + progress.updateAndGet(current -> current.replaceDrainStatus(FlowEvolutionStatus.INACTIVE, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING)); + } + } + + private static boolean sameBundle(final Bundle bundle, final Bundle other) { + return other != null + && Objects.equals(bundle.getGroup(), other.getGroup()) + && Objects.equals(bundle.getArtifact(), other.getArtifact()) + && Objects.equals(bundle.getVersion(), other.getVersion()); + } + + /** + * Progress through a pending flow evolution. The drain status is kept when the evolution fails, so a retry knows whether + * this node has already drained the outgoing flow. + * + * @param drainStatus {@link FlowEvolutionStatus#INACTIVE} when no evolution is pending, otherwise this node's evolve-drain progress + * @param failureExplanation why the evolution failed, or null when it has not failed + */ + private record FlowEvolutionProgress(FlowEvolutionStatus drainStatus, String failureExplanation) { + private static final FlowEvolutionProgress NONE = new FlowEvolutionProgress(FlowEvolutionStatus.INACTIVE, null); + + FlowEvolutionStatus reportedStatus() { + return hasFailed() ? FlowEvolutionStatus.FAILED : drainStatus; + } + + boolean isDrainComplete() { + return drainStatus == FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE; + } + + boolean hasFailed() { + return failureExplanation != null; + } + + FlowEvolutionProgress withDrainStatus(final FlowEvolutionStatus status) { + return new FlowEvolutionProgress(status, failureExplanation); + } + + FlowEvolutionProgress replaceDrainStatus(final FlowEvolutionStatus expected, final FlowEvolutionStatus replacement) { + return drainStatus == expected ? withDrainStatus(replacement) : this; + } + + FlowEvolutionProgress withFailureIfAbsent(final String explanation) { + return hasFailed() ? this : new FlowEvolutionProgress(drainStatus, explanation); + } + } + + /** + * One attempt at a pending flow evolution. The futures are each set at most once per attempt, and are read and written + * only while holding the evolution lock, so closing the attempt cancels this attempt's work and never a newer attempt's. + */ + private static final class FlowEvolutionAttempt { + private final StandardFlowEvolutionContext context; + private final boolean drainCompletedInEarlierAttempt; + private final FlowEngine scheduler; + private CompletableFuture prepareFuture; + private Future evolveFuture; + private boolean preUpgradeStopRetryScheduled; + + private FlowEvolutionAttempt(final StandardFlowEvolutionContext context, final boolean drainCompletedInEarlierAttempt, final FlowEngine scheduler) { + this.context = context; + this.drainCompletedInEarlierAttempt = drainCompletedInEarlierAttempt; + this.scheduler = scheduler; + } + } +} diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java index 400d6417316f..583242ac7b95 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/MigrationFlowContext.java @@ -25,6 +25,7 @@ import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import java.util.Objects; @@ -105,13 +106,8 @@ public void updateFlow(final VersionedExternalFlow versionedExternalFlow, final } @Override - public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext) { + public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext, final ResumeComponentState resumeComponentState) { throw new IllegalStateException("restorePersistedFlow() cannot be called from MigratableConnector.migrateConfiguration() or migrateState();" + " the migration context exposes a read-only view of the managed flow so that the framework remains the sole owner of installing the managed Process Group."); } - - @Override - public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext, final boolean resumeComponentState) { - restorePersistedFlow(persistedFlow, parameterContext); - } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java index 97b06175a165..57f58ced3b53 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java @@ -32,6 +32,8 @@ import org.apache.nifi.security.encryption.SensitivePropertyCodec; import org.apache.nifi.security.encryption.SensitivePropertyContext; import org.apache.nifi.security.encryption.SensitivePropertyContextFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; @@ -47,6 +49,7 @@ * current value of the secret from the {@link SecretsManager} instead of its persisted value. */ final class ParameterSecretReferences { + private static final Logger logger = LoggerFactory.getLogger(ParameterSecretReferences.class); private ParameterSecretReferences() { } @@ -130,9 +133,7 @@ static Resolution resolve(final VersionedParameterContext parameterContext, fina final VersionedParameterContext resolved = copyContext(parameterContext); final Map references = parameterSecretReferences == null ? Map.of() : parameterSecretReferences; final Set distinctReferences = new HashSet<>(references.values()); - final Map secrets = distinctReferences.isEmpty() - ? Map.of() - : secretsManager.getSecrets(distinctReferences, false); + final Map secrets = getSecrets(distinctReferences, secretsManager); final Map unresolved = new HashMap<>(); final Set undecryptable = new HashSet<>(); final List resolvedValues = new ArrayList<>(); @@ -178,6 +179,23 @@ static Resolution resolve(final VersionedParameterContext parameterContext, fina return new Resolution(resolved, resolvedValues, unresolved, undecryptable); } + /** + * A Secrets Provider that cannot be reached leaves every reference unresolved, so a restore installs the flow with its + * components stopped instead of failing. + */ + private static Map getSecrets(final Set references, final SecretsManager secretsManager) { + if (references.isEmpty()) { + return Map.of(); + } + + try { + return secretsManager.getSecrets(references, false); + } catch (final RuntimeException e) { + logger.warn("Failed to retrieve {} Secret References from the Secrets Manager; treating them as unresolved", references.size(), e); + return Map.of(); + } + } + private static VersionedParameterContext copyContext(final VersionedParameterContext source) { final VersionedParameterContext copy = new VersionedParameterContext(); copy.setIdentifier(source.getIdentifier()); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java index 1b739e1864ba..a624cdf38577 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java @@ -60,6 +60,7 @@ import org.apache.nifi.flow.VersionedProcessor; import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.groups.RemoteProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.logging.GroupedComponent; import org.apache.nifi.migration.StandardConnectorPropertyConfiguration; @@ -88,9 +89,7 @@ import java.util.OptionalLong; import java.util.Set; import java.util.UUID; -import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -121,11 +120,7 @@ public class StandardConnectorNode implements ConnectorNode, GroupedComponent { private final FlowContextFactory flowContextFactory; private final ConnectorFlowSnapshotMapper snapshotMapper; private volatile FrameworkFlowContext activeFlowContext; - private final AtomicReference flowEvolutionProgress = new AtomicReference<>(FlowEvolutionProgress.NONE); - private volatile ConnectorFlowSnapshot authoritativeFlowSnapshot; - private final Object flowEvolutionLock = new Object(); - // Written only while holding flowEvolutionLock - private volatile FlowEvolutionAttempt latestFlowEvolutionAttempt; + private final ConnectorFlowEvolution flowEvolution; private final AtomicReference validationState = new AtomicReference<>(new ValidationState(ValidationStatus.VALIDATING, Collections.emptyList())); private final ConnectorValidationTrigger validationTrigger; @@ -173,6 +168,7 @@ public StandardConnectorNode(final String identifier, final FlowManager flowMana final Bundle activeFlowBundle = new Bundle(bundleCoordinate.getGroup(), bundleCoordinate.getId(), bundleCoordinate.getVersion()); this.activeFlowContext = flowContextFactory.createActiveFlowContext(identifier, connectorDetails.getComponentLog(), activeFlowBundle); + this.flowEvolution = new ConnectorFlowEvolution(new EvolvingConnectorAdapter(), stateTransition); rebuildLoggingAttributes(); } @@ -313,7 +309,7 @@ public void prepareForUpdate() throws FlowUpdateException { } // An evolution is applied with the connector desired RUNNING, because only a start request begins an evolution. final ConnectorState desiredState = getDesiredState(); - final boolean evolving = desiredState == ConnectorState.RUNNING && isApplyingEvolvedFlow(); + final boolean evolving = desiredState == ConnectorState.RUNNING && flowEvolution.isApplyingEvolvedFlow(); if (desiredState != ConnectorState.UPDATING && !evolving) { throw new IllegalStateException("Cannot prepare update for " + this + " because its desired state is currently " + desiredState + "; it must be UPDATING."); @@ -744,7 +740,7 @@ private void applyUpdate(final FrameworkFlowContext contextToInherit) throws Flo } // Read before the snapshot is captured, because capturing it ends the evolution. - final boolean evolving = isApplyingEvolvedFlow(); + final boolean evolving = flowEvolution.isApplyingEvolvedFlow(); try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(extensionManager, getConnector().getClass(), getIdentifier())) { getConnector().applyUpdate(contextToInherit, activeFlowContext); @@ -815,7 +811,7 @@ private void releaseWorkingFlowContext(final WorkingFlowContextState workingCont @Override public void abortUpdate(final Throwable cause) { - if (isFlowEvolutionInProgress() || hasFlowEvolutionFailed()) { + if (flowEvolution.isInProgress() || flowEvolution.hasFailed()) { failFlowEvolution(cause == null ? null : cause.getMessage(), cause); return; } @@ -1007,6 +1003,14 @@ public Future start(final FlowEngine scheduler) { } private void start(final FlowEngine scheduler, final CompletableFuture startCompleteFuture) { + // Starting here would run the upgraded Connector's code against the pre-upgrade flow. The desired state is left + // unchanged, so a refused start is not saved as RUNNING. + if (isPendingFlowEvolution()) { + startCompleteFuture.completeExceptionally(new IllegalStateException("Cannot start " + this + + " directly because an upgrade is pending; start it through the Connector Repository so the upgrade is applied first")); + return; + } + try { stateTransition.setDesiredState(ConnectorState.RUNNING); activeFlowContext.getConfigurationContext().resolvePropertyValues(); @@ -1063,7 +1067,7 @@ public Future stop(final FlowEngine scheduler) { final CompletableFuture stopCompleteFuture = new CompletableFuture<>(); stateTransition.setDesiredState(ConnectorState.STOPPED); - if (prepareFlowEvolutionStop(stopCompleteFuture)) { + if (flowEvolution.cancelInProgress(() -> stateTransition.addPendingStopFuture(stopCompleteFuture))) { return stopCompleteFuture; } @@ -1097,19 +1101,6 @@ public Future stop(final FlowEngine scheduler) { return stopCompleteFuture; } - private boolean prepareFlowEvolutionStop(final CompletableFuture stopCompleteFuture) { - synchronized (flowEvolutionLock) { - if (!isFlowEvolutionInProgress()) { - return false; - } - - stateTransition.addPendingStopFuture(stopCompleteFuture); - } - - abortFlowEvolution(); - return true; - } - private void stopManagedProcessGroup(final FlowEngine scheduler) { if (getCurrentState() != ConnectorState.STOPPING) { return; @@ -1176,16 +1167,7 @@ public Future drainFlowFiles() { @Override public void cancelDrainFlowFiles() { - final boolean flowEvolutionActive; - synchronized (flowEvolutionLock) { - flowEvolutionActive = isFlowEvolutionInProgress(); - if (flowEvolutionActive) { - stateTransition.setDesiredState(ConnectorState.STOPPED); - } - } - - if (flowEvolutionActive) { - abortFlowEvolution(); + if (flowEvolution.cancelInProgress(() -> stateTransition.setDesiredState(ConnectorState.STOPPED))) { return; } @@ -1199,12 +1181,6 @@ public void cancelDrainFlowFiles() { logger.info("Cancelled draining of FlowFiles for {}", this); } - private void abortFlowEvolution() { - // Recorded before cancelling, because the coordinator wakes on the cancellation and must see the failure to stop the Connector - publishFlowEvolutionFailure("Flow evolution was cancelled", null); - closeCurrentFlowEvolution(); - } - @Override public void verifyCancelDrainFlowFiles() throws IllegalStateException { final ConnectorState state = getCurrentState(); @@ -1276,7 +1252,14 @@ private void requireStopped(final String action, final ConnectorState newState) private void stopComponent(final FlowEngine scheduler, final CompletableFuture stopCompleteFuture) { componentLifecycleLock.lock(); try { - if (getCurrentState() != ConnectorState.STOPPING) { + final ConnectorState currentState = getCurrentState(); + if (currentState == ConnectorState.STOPPED) { + stopCompleteFuture.complete(null); + return; + } + + if (currentState != ConnectorState.STOPPING) { + stopCompleteFuture.completeExceptionally(new IllegalStateException("Stop of " + this + " did not complete because its state changed to " + currentState)); return; } @@ -1407,9 +1390,20 @@ public void verifyCanStart() { throw new IllegalStateException("Cannot start " + this + " because its extension is missing."); } if (managedFlowRestoreFailed) { - throw new IllegalStateException("Cannot start " + this + " because its managed flow was not installed while it was ghosted; " + throw new IllegalStateException("Cannot start " + this + " because its persisted managed flow could not be restored; " + "restart NiFi so queued FlowFiles rejoin the restored connections before starting"); } + + // A start that would begin a new evolution needs the Connector stopped. A start that joins an evolution already draining is allowed. + if (isPendingFlowEvolution()) { + final ConnectorState currentState = getCurrentState(); + final boolean userRequestedDrain = currentState == ConnectorState.DRAINING && !flowEvolution.isInProgress(); + if (currentState == ConnectorState.STOPPING || currentState == ConnectorState.PURGING || userRequestedDrain) { + throw new IllegalStateException("Cannot start " + this + " because an upgrade is pending and its state is currently " + currentState + + "; it must be stopped before the upgrade can begin"); + } + } + final ValidationState state = performValidation(); final boolean blockingFailure = state.getValidationErrors().stream().anyMatch(StandardConnectorNode::isBlockingValidationFailure); if (blockingFailure) { @@ -1597,7 +1591,7 @@ public void endTroubleshooting() throws FlowUpdateException { // A pending upgrade installs this flow directly. prepareForFlowEvolution is not called: the queues were // required to be empty, and the loaded bundle is captured so the evolution is no longer pending. initializationContext.updateFlow(activeFlowContext, flowToApply, BundleCompatibility.RESOLVE_BUNDLE); - installAuthoritativeSnapshot(createAuthoritativeSnapshot()); + flowEvolution.installSnapshot(createAuthoritativeSnapshot()); stateTransition.setDesiredState(ConnectorState.STOPPED); stateTransition.setCurrentState(ConnectorState.STOPPED); @@ -1644,7 +1638,7 @@ public void replaceConnector(final Connector replacement, final BundleCoordinate // The snapshot keeps the outgoing flow, Parameter Context and managed-flow bundle across version changes, so a // change to a different version leaves the flow evolution pending and a change back to the snapshot bundle clears it. - final ConnectorFlowSnapshot outgoingSnapshot = authoritativeFlowSnapshot; + final ConnectorFlowSnapshot outgoingSnapshot = flowEvolution.getSnapshot(); final boolean replacementMissing = replacement instanceof GhostConnector; final boolean restoreSnapshotFlow = extensionMissing && !replacementMissing && outgoingSnapshot != null && outgoingSnapshot.flow() != null; @@ -1677,7 +1671,7 @@ public void replaceConnector(final Connector replacement, final BundleCoordinate if (restoreSnapshotFlow) { // A missing Connector leaves the managed group empty, so the persisted flow is restored to reattach its queues restorePersistedFlow(outgoingSnapshot.flow(), outgoingSnapshot.parameterContext(), - outgoingSnapshot.parameterSecretReferences(), true); + outgoingSnapshot.parameterSecretReferences(), ResumeComponentState.RESUME_AS_PERSISTED); } activeFlowContext.reload(bundle, replacementLog, replacementActiveConfiguration); @@ -1689,13 +1683,10 @@ public void replaceConnector(final Connector replacement, final BundleCoordinate initializationContext = replacementInitializationContext; // The loaded bundle and whether the extension is missing have changed, so the snapshot is installed again even when it is kept. - synchronized (flowEvolutionLock) { - final ConnectorFlowSnapshot replacementSnapshot = outgoingSnapshot == null || replacementMissing - ? authoritativeFlowSnapshot - : new ConnectorFlowSnapshot(outgoingSnapshot.flow(), outgoingSnapshot.parameterContext(), outgoingSnapshot.parameterSecretReferences(), - outgoingSnapshot.bundle(), replacementActiveConfiguration.toConnectorConfiguration()); - installAuthoritativeSnapshot(replacementSnapshot); - } + flowEvolution.updateSnapshot(currentSnapshot -> outgoingSnapshot == null || replacementMissing + ? currentSnapshot + : new ConnectorFlowSnapshot(outgoingSnapshot.flow(), outgoingSnapshot.parameterContext(), outgoingSnapshot.parameterSecretReferences(), + outgoingSnapshot.bundle(), replacementActiveConfiguration.toConnectorConfiguration())); } catch (final Throwable failure) { if (workingContextModified) { releaseWorkingFlowContext(workingContextState); @@ -1777,42 +1768,21 @@ public boolean isExtensionMissing() { @Override public boolean isPendingFlowEvolution() { - synchronized (flowEvolutionLock) { - if (extensionMissing) { - return false; - } - - final ConnectorFlowSnapshot snapshot = authoritativeFlowSnapshot; - final Bundle snapshotBundle = snapshot == null ? null : snapshot.bundle(); - return snapshotBundle != null && !sameBundle(snapshotBundle, bundleCoordinate); - } + return flowEvolution.isPending(); } @Override public FlowEvolutionStatus getReportedFlowEvolutionStatus() { - return flowEvolutionProgress.get().reportedStatus(); - } - - private boolean isEvolveDrainComplete() { - return flowEvolutionProgress.get().isDrainComplete(); - } - - private boolean isApplyingEvolvedFlow() { - return getReportedFlowEvolutionStatus() == FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE; + return flowEvolution.getReportedStatus(); } boolean hasFlowEvolutionFailed() { - return flowEvolutionProgress.get().hasFailed(); - } - - private VersionedProcessGroup getAuthoritativeManagedProcessGroup() { - final ConnectorFlowSnapshot snapshot = authoritativeFlowSnapshot; - return snapshot == null ? null : snapshot.flow(); + return flowEvolution.hasFailed(); } @Override public ConnectorFlowSnapshot getAuthoritativeFlowSnapshot() { - return authoritativeFlowSnapshot; + return flowEvolution.getSnapshot(); } @Override @@ -1837,8 +1807,15 @@ public boolean restorePendingFlowEvolution(final VersionedConnector persisted, f if (!extensionMissing && !sameManagedBundle(managedFlowBundle) && persistedManagedGroup != null) { // Skip inheritConfiguration. Its applyUpdate would replace the pre-upgrade group with the new bundle's - // flow. The restored group keeps the previous bundle, so the next start evolves it. - restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, true); + // flow. The restored group keeps the previous bundle, so the next start evolves it. A failed restore still loads + // the configuration and adopts the persisted snapshot, so the next flow save keeps the pre-upgrade flow. + try { + restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, ResumeComponentState.RESUME_AS_PERSISTED); + } catch (final Exception e) { + logger.error("{} failed to restore the persisted pre-upgrade managed flow; the Connector cannot start until NiFi is restarted and the flow is restored", this, e); + markManagedFlowRestoreFailed(); + } + loadConfigurationsWithoutRebuildingFlow(activeConfiguration, workingConfiguration); adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); return true; @@ -1864,7 +1841,7 @@ public void restorePersistedManagedFlow(final VersionedConnector persisted) { // Install the persisted flow while ghosted so queues exist before the FlowFile repository recovers. // Components stay stopped: a ghost cannot start, and resuming would run them under a missing extension. try { - restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, false); + restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, ResumeComponentState.LEAVE_STOPPED); } catch (final Exception e) { logger.error("{} failed to restore the persisted managed flow while ghosted; " + "queued FlowFiles may not rejoin until NiFi restarts after the Connector becomes loadable again", this, e); @@ -1887,7 +1864,7 @@ public void restoreTroubleshootingManagedFlow(final VersionedConnector persisted if (sameManagedBundle(managedFlowBundle) && persistedManagedGroup != null) { try { - restorePersistedFlow(persistedManagedGroup, null, Map.of(), true); + restorePersistedFlow(persistedManagedGroup, null, Map.of(), ResumeComponentState.RESUME_AS_PERSISTED); adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); } catch (final Exception e) { logger.error("{} failed to restore the managed flow while restoring Troubleshooting", this, e); @@ -1898,30 +1875,14 @@ public void restoreTroubleshootingManagedFlow(final VersionedConnector persisted @Override public void ensureAuthoritativeFlowSnapshot() { - if (getAuthoritativeManagedProcessGroup() != null || extensionMissing) { - return; - } - - // Without a snapshot, a later NAR upgrade has no pre-upgrade flow to evolve. - verifyCanCaptureAuthoritativeSnapshot(); - final ConnectorFlowSnapshot snapshot = createAuthoritativeSnapshot(); - - synchronized (flowEvolutionLock) { - // Another thread may have installed a snapshot, such as the pre-upgrade flow, while the live flow was being captured - if (getAuthoritativeManagedProcessGroup() != null) { - return; - } - - verifyCanCaptureAuthoritativeSnapshot(); - installAuthoritativeSnapshot(snapshot); - } + flowEvolution.ensureSnapshot(); } private void restoreTroubleshootingFlow(final VersionedProcessGroup persistedManagedGroup, final VersionedParameterContext parameterContext, final Map parameterSecretReferences) throws FlowUpdateException { logger.info("{} was persisted in Troubleshooting mode; restoring Managed Process Group from persisted snapshot", this); try { - restorePersistedFlow(persistedManagedGroup, parameterContext, parameterSecretReferences, false); + restorePersistedFlow(persistedManagedGroup, parameterContext, parameterSecretReferences, ResumeComponentState.LEAVE_STOPPED); } catch (final Exception e) { logger.error("{} failed to restore the managed flow while restoring Troubleshooting", this, e); throw new FlowUpdateException("Failed to restore Managed Process Group from persisted flow: " + e.getMessage(), e); @@ -1962,22 +1923,20 @@ void resolvePersistedBundles(final VersionedProcessGroup group) { void adoptAuthoritativeSnapshot(final VersionedProcessGroup flow, final VersionedParameterContext parameterContext, final Map parameterSecretReferences, final Bundle managedFlowBundle) { - installAuthoritativeSnapshot(new ConnectorFlowSnapshot(flow, parameterContext, parameterSecretReferences, managedFlowBundle, + flowEvolution.installSnapshot(new ConnectorFlowSnapshot(flow, parameterContext, parameterSecretReferences, managedFlowBundle, activeFlowContext.getConfigurationContext().toConnectorConfiguration())); } void restorePersistedFlow(final VersionedProcessGroup flow, final VersionedParameterContext parameterContext, - final Map parameterSecretReferences, final boolean resumeComponents) { + final Map parameterSecretReferences, final ResumeComponentState requestedResumeState) { final ParameterSecretReferences.Resolution resolution = resolvePersistedParameterSecrets(parameterContext, parameterSecretReferences); if (!resolution.undecryptableParameters().isEmpty()) { logger.warn("{} could not decrypt the persisted values of sensitive parameters {}; components are left stopped", this, resolution.undecryptableParameters()); } - if (resumeComponents && unresolvedParameterSecretReferences.isEmpty() && resolution.undecryptableParameters().isEmpty()) { - activeFlowContext.restorePersistedFlow(flow, resolution.parameterContext()); - } else { - activeFlowContext.restorePersistedFlow(flow, resolution.parameterContext(), false); - } + final boolean parametersResolved = unresolvedParameterSecretReferences.isEmpty() && resolution.undecryptableParameters().isEmpty(); + final ResumeComponentState resumeState = parametersResolved ? requestedResumeState : ResumeComponentState.LEAVE_STOPPED; + activeFlowContext.restorePersistedFlow(flow, resolution.parameterContext(), resumeState); } private ParameterSecretReferences.Resolution resolvePersistedParameterSecrets(final VersionedParameterContext parameterContext, @@ -1988,381 +1947,22 @@ private ParameterSecretReferences.Resolution resolvePersistedParameterSecrets(fi } @Override - public void prepareFlowEvolution() { - synchronized (flowEvolutionLock) { - if (!isPendingFlowEvolution()) { - throw new IllegalStateException("Cannot prepare flow evolution for " + this + " because no evolution is pending"); - } - // Hook progress outlives an attempt only once every node has drained, so the outgoing flow is no longer needed. - final boolean drainCompletedInEarlierAttempt = isEvolveDrainComplete(); - if (!stateTransition.trySetCurrentState(ConnectorState.STOPPED, ConnectorState.DRAINING) - && !stateTransition.trySetCurrentState(ConnectorState.UPDATE_FAILED, ConnectorState.DRAINING)) { - throw new IllegalStateException("Cannot prepare flow evolution for " + this + " from state " + getCurrentState()); - } - - flowEvolutionProgress.set(new FlowEvolutionProgress(drainCompletedInEarlierAttempt - ? FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE - : FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, null)); - final Bundle postUpgradeBundle = loadedBundle(); - final ConnectorFlowSnapshot outgoingSnapshot = authoritativeFlowSnapshot; - final Bundle preUpgradeBundle = outgoingSnapshot == null || outgoingSnapshot.bundle() == null ? postUpgradeBundle : outgoingSnapshot.bundle(); - final StandardFlowEvolutionContext context = new StandardFlowEvolutionContext(new PreUpgradeFlowContext(activeFlowContext, preUpgradeBundle), postUpgradeBundle); - latestFlowEvolutionAttempt = new FlowEvolutionAttempt(context, drainCompletedInEarlierAttempt); - // Only a start request begins an evolution, so the connector is desired RUNNING while it drains and once the - // upgraded flow is applied. A node that joins while this connector is draining inherits the flow mapped from the - // desired state, so it also starts and enters the same evolution. - stateTransition.setDesiredState(ConnectorState.RUNNING); - } - } - - private boolean isFlowEvolutionInProgress() { - synchronized (flowEvolutionLock) { - // Desired state cannot say this. stop() sets the desired state to STOPPED before it aborts the evolution. - // The drain status cannot say this either, because a pending evolution reports EVOLVE_DRAIN_PENDING before its attempt - // begins, while a user-requested drain may also be running. - final StandardFlowEvolutionContext context = currentFlowEvolutionContext(); - return getCurrentState() == ConnectorState.DRAINING - && context != null - && !context.isFailed() - && !hasFlowEvolutionFailed(); - } - } - - private void runFlowEvolutionPreflight(final StandardFlowEvolutionContext context) throws FlowUpdateException { - verifyFlowEvolutionContext(context); - if (!isEvolveDrainComplete()) { - refreshPreUpgradeParameterSecrets(context); - } - - final List ghostResults = new ArrayList<>(); - validateManagedFlowComponents(ghostResults); - if (!ghostResults.isEmpty()) { - final String explanation = ghostResults.getFirst().getExplanation(); - failFlowEvolution(context, explanation, null); - throw new FlowUpdateException(explanation); - } - - verifyFlowEvolutionContext(context); - } - - private void refreshPreUpgradeParameterSecrets(final StandardFlowEvolutionContext context) throws FlowUpdateException { - final ConnectorFlowSnapshot snapshot = authoritativeFlowSnapshot; - if (snapshot == null || snapshot.parameterContext() == null) { - verifyFlowEvolutionContext(context); - unresolvedParameterSecretReferences = Map.of(); - return; - } - - final ParameterSecretReferences.Resolution resolution = snapshotMapper.resolve( - snapshot.parameterContext(), snapshot.parameterSecretReferences(), initializationContext.getSecretsManager()); - if (!resolution.unresolvedReferences().isEmpty()) { - final Map.Entry unresolved = resolution.unresolvedReferences().entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .findFirst() - .orElseThrow(); - final SecretReference reference = unresolved.getValue(); - final String secretName = reference.getFullyQualifiedName() == null ? reference.getSecretName() : reference.getFullyQualifiedName(); - final String explanation = "Flow evolution cannot start: secret [%s] used by parameter [%s] could not be resolved. " - .formatted(secretName, unresolved.getKey()) - + "Restore the secret in its provider, then start the Connector to resume the upgrade."; - verifyFlowEvolutionContext(context); - unresolvedParameterSecretReferences = Map.copyOf(resolution.unresolvedReferences()); - failFlowEvolution(context, explanation, null); - throw new FlowUpdateException(explanation); - } - - verifyFlowEvolutionContext(context); - unresolvedParameterSecretReferences = Map.of(); - if (!resolution.parameterValues().isEmpty()) { - activeFlowContext.getParameterContext().updateParameters(resolution.parameterValues()); - } + public void prepareFlowEvolution(final FlowEngine scheduler) { + flowEvolution.prepare(scheduler); } @Override public Future evolveFlow(final ExecutorService executor) throws FlowUpdateException { - Objects.requireNonNull(executor, "Executor Service is required"); - - synchronized (flowEvolutionLock) { - final StandardFlowEvolutionContext context = currentFlowEvolutionContext(); - verifyFlowEvolutionContext(context); - final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; - if (attempt.evolveFuture != null) { - return attempt.evolveFuture; - } - - attempt.evolveFuture = executor.submit(() -> { - runEvolveDrainPhase(context); - return null; - }); - return attempt.evolveFuture; - } - } - - private void runEvolveDrainPhase(final StandardFlowEvolutionContext context) throws FlowUpdateException { - runFlowEvolutionPreflight(context); - if (isEvolveDrainComplete()) { - return; - } - - verifyFlowEvolutionContext(context); - final CompletableFuture connectorFuture; - try { - connectorFuture = invokeFlowEvolutionHook(context); - } catch (final FlowUpdateException e) { - failFlowEvolution(context, e.getMessage(), e); - throw e; - } - - try { - synchronized (flowEvolutionLock) { - verifyFlowEvolutionContext(context); - latestFlowEvolutionAttempt.prepareFuture = connectorFuture; - } - } catch (final FlowUpdateException e) { - connectorFuture.cancel(true); - throw e; - } - - try { - connectorFuture.get(); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - throw new FlowUpdateException("Interrupted while waiting for flow evolution hook for " + this, e); - } catch (final CancellationException e) { - throw new FlowUpdateException("Flow evolution hook was cancelled for " + this, e); - } catch (final ExecutionException e) { - final Throwable cause = e.getCause() == null ? e : e.getCause(); - failFlowEvolution(context, cause.getMessage(), cause); - throw new FlowUpdateException("Flow evolution hook failed for " + this, cause); - } - - completeEvolveDrainPhase(context); - } - - private void completeEvolveDrainPhase(final StandardFlowEvolutionContext context) throws FlowUpdateException { - // The hook may start processors so queues can empty. Those processors must be stopped before the upgraded - // flow is verified, so no FlowFile reaches a connection the upgraded flow removes after it has been checked. - verifyFlowEvolutionContext(context); - if (!stopPreUpgradeFlow()) { - failFlowEvolution(context, "Failed to stop the pre-upgrade flow", null); - throw new FlowUpdateException("Failed to stop the pre-upgrade flow for " + this); - } - - verifyUpgradedFlow(context); - - synchronized (flowEvolutionLock) { - verifyFlowEvolutionContext(context); - flowEvolutionProgress.updateAndGet(progress -> progress.withDrainStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE)); - } - } - - /** - * Fails the evolution if the upgraded flow cannot replace the active flow, for example because it removes a - * connection that still holds FlowFiles. - */ - private void verifyUpgradedFlow(final StandardFlowEvolutionContext context) throws FlowUpdateException { - verifyFlowEvolutionContext(context); - final VersionedExternalFlow proposedFlow; - try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(getConnector().getClass().getClassLoader())) { - proposedFlow = getConnector().getActiveFlow(getWorkingFlowContext()); - } catch (final Exception failure) { - failFlowEvolution(context, failure.getMessage(), failure); - throw new FlowUpdateException("Failed to determine the upgraded flow for " + this, failure); - } - if (proposedFlow == null || proposedFlow.getFlowContents() == null) { - failFlowEvolution(context, "Upgraded flow was not returned", null); - throw new FlowUpdateException("Upgraded flow was not returned for " + this); - } - - verifyFlowEvolutionContext(context); - try { - activeFlowContext.verifyUpdateFlow(proposedFlow); - } catch (final FlowUpdateException e) { - failFlowEvolution(context, e.getMessage(), e); - throw e; - } - } - - private void verifyFlowEvolutionContext(final StandardFlowEvolutionContext context) throws FlowUpdateException { - if (currentFlowEvolutionContext() != context || context == null || context.isFailed() || hasFlowEvolutionFailed() || getCurrentState() != ConnectorState.DRAINING) { - throw new FlowUpdateException("Flow evolution was cancelled for " + this); - } + return flowEvolution.evolve(executor); } - /** - * @return the context of the current or most recent attempt, or null when no attempt has begun while the evolution is pending - */ - private StandardFlowEvolutionContext currentFlowEvolutionContext() { - final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; - return attempt == null ? null : attempt.context; - } - - private CompletableFuture invokeFlowEvolutionHook(final FlowEvolutionContext evolutionContext) throws FlowUpdateException { - try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(getConnector().getClass().getClassLoader())) { - return Objects.requireNonNull( - getConnector().prepareForFlowEvolution(evolutionContext), - "Connector prepareForFlowEvolution must return a CompletableFuture"); - } - } - - /** - * {@link Connector#applyUpdate} must be safe to run again on a flow it has already partly updated, because a start - * after a failed apply resumes after the hook and applies again. - */ @Override public void beginEvolvedFlowUpdate() throws FlowUpdateException { - // Checked again after the drain barrier because an attempt that resumes after the hook skips the evolve-drain phase, and the - // persisted flow is replaced once the upgraded flow is applied. - verifyUpgradedFlow(currentFlowEvolutionContext()); - - synchronized (flowEvolutionLock) { - if (!isFlowEvolutionInProgress() || !isEvolveDrainComplete()) { - throw new FlowUpdateException("Cannot apply the upgraded flow for " + this + " because the evolve-drain phase is not complete"); - } - - // Leaving DRAINING closes the evolution attempt, and prepareForUpdate follows as for any configuration update. - // The status stays EVOLVE_DRAIN_COMPLETE until the upgraded flow is applied so a peer still waiting on the drain - // barrier passes it. The desired state stays RUNNING, because only a start request begins an evolution. - stateTransition.setCurrentState(ConnectorState.PREPARING_FOR_UPDATE); - } - } - - /** - * Marks this evolution failed and cancels its hook after releasing the evolution lock. The hook future is copied - * under the lock so a newer evolution is not cancelled. This does not cancel the evolve-drain task, because it runs - * on that task and cancelling it would interrupt the task before it stops the pre-upgrade flow. - * - * @param expectedContext the evolution to close - * @return false when the context is already closed or has been replaced - */ - private boolean closeFlowEvolutionContext(final StandardFlowEvolutionContext expectedContext) { - final CompletableFuture prepareFuture; - synchronized (flowEvolutionLock) { - final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; - if (attempt == null || attempt.context.isFailed() || attempt.context != expectedContext) { - return false; - } - - attempt.context.fail(); - prepareFuture = attempt.prepareFuture; - } - - cancel(prepareFuture); - return true; - } - - /** - * Marks the current evolution failed and cancels its hook and evolve-drain task. The futures are copied under the - * evolution lock so a newer evolution started after this close is not cancelled. - */ - private void closeCurrentFlowEvolution() { - final CompletableFuture prepareFuture; - final Future evolveDrainTask; - synchronized (flowEvolutionLock) { - final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; - if (attempt == null || attempt.context.isFailed()) { - return; - } - - attempt.context.fail(); - prepareFuture = attempt.prepareFuture; - evolveDrainTask = attempt.evolveFuture; - } - - cancel(evolveDrainTask); - cancel(prepareFuture); - } - - private void cancel(final Future future) { - if (future != null) { - future.cancel(true); - } - } - - private void failFlowEvolution(final StandardFlowEvolutionContext context, final String explanation, final Throwable cause) { - if (!closeFlowEvolutionContext(context)) { - return; - } - - finishFlowEvolutionFailure(explanation, cause); + flowEvolution.beginEvolvedFlowUpdate(); } void failFlowEvolution(final String explanation, final Throwable cause) { - closeCurrentFlowEvolution(); - finishFlowEvolutionFailure(explanation, cause); - } - - /** - * Retries stopping the pre-upgrade flow after {@link #finishFlowEvolutionFailure} left the connector STOPPING. - * Completes pending stop futures and honors a desired RUNNING state when the stop succeeds. - */ - void retryPreUpgradeStop(final FlowEngine scheduler) { - if (getCurrentState() != ConnectorState.STOPPING) { - return; - } - - scheduler.schedule(() -> retryPreUpgradeStop(scheduler, 0), 0, TimeUnit.SECONDS); - } - - private void retryPreUpgradeStop(final FlowEngine scheduler, final int attempt) { - if (getCurrentState() != ConnectorState.STOPPING) { - return; - } - - if (stopPreUpgradeFlow()) { - synchronized (flowEvolutionLock) { - if (getCurrentState() != ConnectorState.STOPPING) { - return; - } - stateTransition.setCurrentState(ConnectorState.STOPPED); - } - logger.info("Successfully stopped the pre-upgrade flow for {} after a failed evolution", this); - - final ConnectorState desiredState = getDesiredState(); - if (desiredState == ConnectorState.RUNNING) { - logger.info("{} was requested to be RUNNING while stopping the pre-upgrade flow so will attempt to start again", this); - start(scheduler, new CompletableFuture<>()); - } - return; - } - - final long delaySeconds = Math.min(60L, 1L << Math.min(attempt, 5)); - logger.warn("Failed to stop the pre-upgrade flow for {}. Will try again in {} seconds", this, delaySeconds); - scheduler.schedule(() -> retryPreUpgradeStop(scheduler, attempt + 1), delaySeconds, TimeUnit.SECONDS); - } - - private void finishFlowEvolutionFailure(final String explanation, final Throwable cause) { - if (!isEvolveDrainComplete() && !stopPreUpgradeFlow()) { - publishFlowEvolutionFailure(explanation, cause); - synchronized (flowEvolutionLock) { - stateTransition.setDesiredState(ConnectorState.STOPPED); - stateTransition.setCurrentState(ConnectorState.STOPPING); - } - return; - } - - publishFlowEvolutionFailure(explanation, cause); - synchronized (flowEvolutionLock) { - stateTransition.setDesiredState(ConnectorState.STOPPED); - stateTransition.setCurrentState(ConnectorState.STOPPED); - // A peer may not have drained yet, so the next attempt drains again. An attempt that started after this - // node's drain had already completed keeps that progress, because the drain barrier may already have passed - // and the upgraded flow may have been partly applied. - final FlowEvolutionAttempt attempt = latestFlowEvolutionAttempt; - if (attempt == null || !attempt.drainCompletedInEarlierAttempt) { - flowEvolutionProgress.updateAndGet(progress -> progress.replaceDrainStatus(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING)); - } - } - } - - private void publishFlowEvolutionFailure(final String explanation, final Throwable cause) { - final String concreteExplanation = explanation == null || explanation.isBlank() - ? cause == null ? "Unknown flow evolution failure" : cause.getClass().getSimpleName() - : explanation; - final FlowEvolutionProgress previous = flowEvolutionProgress.getAndUpdate(progress -> progress.withFailureIfAbsent(concreteExplanation)); - if (!previous.hasFailed()) { - getComponentLog().error("Flow evolution failed: {}", concreteExplanation, cause); - } + flowEvolution.fail(explanation, cause); } private static boolean isBlockingValidationFailure(final ValidationResult result) { @@ -2381,68 +1981,8 @@ private static ValidationResult createFlowEvolutionFailure(final String explanat .build(); } - /** - * @return whether the pre-upgrade flow stopped - */ - private boolean stopPreUpgradeFlow() { - try { - final CompletableFuture stopped = activeFlowContext.getRootGroup().getLifecycle().stop(); - if (stopped != null) { - stopped.get(1, TimeUnit.MINUTES); - } - return true; - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - logger.warn("Interrupted while stopping the pre-upgrade flow for {}", this, e); - return false; - } catch (final Exception e) { - logger.warn("Failed to stop the pre-upgrade flow for {}", this, e); - return false; - } - } - - /** - * Captures the live flow outside the evolution lock, because capturing resolves secrets, then installs it under the lock - * after checking again that it may be installed. - */ void captureAuthoritativeSnapshot() { - verifyCanCaptureAuthoritativeSnapshot(); - final ConnectorFlowSnapshot snapshot = createAuthoritativeSnapshot(); - - synchronized (flowEvolutionLock) { - verifyCanCaptureAuthoritativeSnapshot(); - installAuthoritativeSnapshot(snapshot); - } - } - - private void verifyCanCaptureAuthoritativeSnapshot() { - // Applying the upgraded flow after the evolve-drain phase records the new bundle, which is what ends the pending evolution. - if (isPendingFlowEvolution() && !isEvolveDrainComplete()) { - throw new IllegalStateException("Cannot capture an authoritative snapshot for " + this + " while flow evolution is pending"); - } - } - - /** - * Installs the snapshot and brings the drain status in line with whether an evolution is now pending. This is the only - * writer of the snapshot. It must also be called, with the current snapshot, whenever the loaded bundle or whether the - * extension is missing changes. - */ - private void installAuthoritativeSnapshot(final ConnectorFlowSnapshot snapshot) { - synchronized (flowEvolutionLock) { - authoritativeFlowSnapshot = snapshot; - - // Once the snapshot records the loaded bundle no evolution is pending, so no attempt is open and neither its drain progress - // nor its failure applies. - if (!isPendingFlowEvolution()) { - flowEvolutionProgress.set(FlowEvolutionProgress.NONE); - latestFlowEvolutionAttempt = null; - return; - } - - // A node that still has the outgoing flow reports it as pending even before its own attempt begins, so a peer - // does not apply the upgraded flow while this node may still need to drain. - flowEvolutionProgress.updateAndGet(progress -> progress.replaceDrainStatus(FlowEvolutionStatus.INACTIVE, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING)); - } + flowEvolution.captureSnapshot(); } private ConnectorFlowSnapshot createAuthoritativeSnapshot() { @@ -3402,7 +2942,7 @@ private ConnectorAction createStartAction(final boolean stopped, final boolean t reason = "Connector's extension is missing"; } else if (managedFlowRestoreFailed) { allowed = false; - reason = "Cannot start " + this + " because its managed flow was not installed while it was ghosted; " + reason = "Cannot start " + this + " because its persisted managed flow could not be restored; " + "restart NiFi so queued FlowFiles rejoin the restored connections before starting"; } else { final Collection validationResults = getValidationErrors(); @@ -3643,7 +3183,7 @@ public ValidationStatus getValidationStatus() { @Override public ValidationState getValidationState() { final ValidationState current = validationState.get(); - final String failureExplanation = flowEvolutionProgress.get().failureExplanation(); + final String failureExplanation = flowEvolution.getFailureExplanation(); if (failureExplanation == null) { return current; } @@ -3909,54 +3449,67 @@ private List fetchAllowableValues(final String stepName, final S return allowableValues; } - /** - * Progress through a pending flow evolution. The drain status is kept when the evolution fails, so a retry knows whether - * this node has already drained the outgoing flow. - * - * @param drainStatus {@link FlowEvolutionStatus#INACTIVE} when no evolution is pending, otherwise this node's evolve-drain progress - * @param failureExplanation why the evolution failed, or null when it has not failed - */ - private record FlowEvolutionProgress(FlowEvolutionStatus drainStatus, String failureExplanation) { - private static final FlowEvolutionProgress NONE = new FlowEvolutionProgress(FlowEvolutionStatus.INACTIVE, null); + private final class EvolvingConnectorAdapter implements ConnectorFlowEvolution.EvolvingConnector { + @Override + public boolean isExtensionMissing() { + return extensionMissing; + } - FlowEvolutionStatus reportedStatus() { - return hasFailed() ? FlowEvolutionStatus.FAILED : drainStatus; + @Override + public Bundle getLoadedBundle() { + return bundleCoordinate == null ? null : loadedBundle(); } - boolean isDrainComplete() { - return drainStatus == FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE; + @Override + public FrameworkFlowContext getActiveFlowContext() { + return activeFlowContext; } - boolean hasFailed() { - return failureExplanation != null; + @Override + public ComponentLog getComponentLog() { + return StandardConnectorNode.this.getComponentLog(); } - FlowEvolutionProgress withDrainStatus(final FlowEvolutionStatus status) { - return new FlowEvolutionProgress(status, failureExplanation); + @Override + public ParameterSecretReferences.Resolution resolveParameterSecrets(final VersionedParameterContext parameterContext, + final Map parameterSecretReferences) { + return snapshotMapper.resolve(parameterContext, parameterSecretReferences, initializationContext.getSecretsManager()); } - FlowEvolutionProgress replaceDrainStatus(final FlowEvolutionStatus expected, final FlowEvolutionStatus replacement) { - return drainStatus == expected ? withDrainStatus(replacement) : this; + @Override + public void setUnresolvedParameterSecretReferences(final Map unresolvedReferences) { + unresolvedParameterSecretReferences = unresolvedReferences; } - FlowEvolutionProgress withFailureIfAbsent(final String explanation) { - return hasFailed() ? this : new FlowEvolutionProgress(drainStatus, explanation); + @Override + public List validateManagedFlowComponents() { + final List results = new ArrayList<>(); + StandardConnectorNode.this.validateManagedFlowComponents(results); + return results; } - } - /** - * One attempt at a pending flow evolution. The futures are each set at most once per attempt, and are read and written - * only while holding the evolution lock, so closing the attempt cancels this attempt's work and never a newer attempt's. - */ - private static final class FlowEvolutionAttempt { - private final StandardFlowEvolutionContext context; - private final boolean drainCompletedInEarlierAttempt; - private CompletableFuture prepareFuture; - private Future evolveFuture; + @Override + public CompletableFuture invokeFlowEvolutionHook(final FlowEvolutionContext context) throws FlowUpdateException { + try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(getConnector().getClass().getClassLoader())) { + return getConnector().prepareForFlowEvolution(context); + } + } - private FlowEvolutionAttempt(final StandardFlowEvolutionContext context, final boolean drainCompletedInEarlierAttempt) { - this.context = context; - this.drainCompletedInEarlierAttempt = drainCompletedInEarlierAttempt; + @Override + public VersionedExternalFlow getUpgradedFlow() throws Exception { + try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(getConnector().getClass().getClassLoader())) { + return getConnector().getActiveFlow(getWorkingFlowContext()); + } + } + + @Override + public ConnectorFlowSnapshot captureSnapshot() { + return createAuthoritativeSnapshot(); + } + + @Override + public String toString() { + return StandardConnectorNode.this.toString(); } } 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 09c247621f4f..10f33507cd5d 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 @@ -637,8 +637,9 @@ public Future startConnector(final ConnectorNode connector, final Connecto } try { - connector.prepareFlowEvolution(); + connector.prepareFlowEvolution(lifecycleExecutor); } catch (final Throwable failure) { + logger.error("Failed to prepare flow evolution for {}", connector, failure); evolutionFuture.completeExceptionally(failure); evolveThenStartFuturesByConnectorId.remove(connectorId, evolutionFuture); if (failure instanceof final Error error) { @@ -754,9 +755,6 @@ private void handleFlowEvolutionFailure(final ConnectorNode connector, final Com try { // While DRAINING this fails the evolution. Once preparation for the upgraded flow has begun it leaves UPDATE_FAILED. connector.abortUpdate(failure); - if (connector.getCurrentState() == ConnectorState.STOPPING && connector instanceof final StandardConnectorNode standardConnector) { - standardConnector.retryPreUpgradeStop(lifecycleExecutor); - } } catch (final Throwable cleanupFailure) { failure.addSuppressed(cleanupFailure); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorStateTransition.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorStateTransition.java index 3e45c73bc3d7..402249b5c2a7 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorStateTransition.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorStateTransition.java @@ -57,6 +57,7 @@ public void setDesiredState(final ConnectorState desiredState) { @Override public boolean trySetCurrentState(final ConnectorState expectedState, final ConnectorState newState) { final List> futuresToComplete; + final List> abandonedStopFutures; synchronized (this) { final boolean changed = currentState.compareAndSet(expectedState, newState); if (!changed) { @@ -64,10 +65,12 @@ public boolean trySetCurrentState(final ConnectorState expectedState, final Conn } futuresToComplete = removePendingFutures(newState); + abandonedStopFutures = removeAbandonedStopFutures(newState); } logger.info("Transitioned current state for {} from {} to {}", componentDescription, expectedState, newState); completeFutures(futuresToComplete, newState); + failStopFutures(abandonedStopFutures, newState); return true; } @@ -75,13 +78,16 @@ public boolean trySetCurrentState(final ConnectorState expectedState, final Conn public void setCurrentState(final ConnectorState newState) { final ConnectorState oldState; final List> futuresToComplete; + final List> abandonedStopFutures; synchronized (this) { oldState = currentState.getAndSet(newState); futuresToComplete = removePendingFutures(newState); + abandonedStopFutures = removeAbandonedStopFutures(newState); } logger.info("Transitioned current state for {} from {} to {}", componentDescription, oldState, newState); completeFutures(futuresToComplete, newState); + failStopFutures(abandonedStopFutures, newState); } @Override @@ -120,6 +126,33 @@ private List> removePendingFutures(final ConnectorState return List.of(); } + /** + * A stop is pending only while the Connector is stopping or is about to stop. Any other state, such as + * UPDATE_FAILED after a failed update, means the stop that registered the future will never complete it. + */ + private List> removeAbandonedStopFutures(final ConnectorState newState) { + if (newState == ConnectorState.STOPPING || newState == ConnectorState.STOPPED || pendingStopFutures.isEmpty()) { + return List.of(); + } + + final List> abandonedFutures = new ArrayList<>(pendingStopFutures); + pendingStopFutures.clear(); + return abandonedFutures; + } + + private void failStopFutures(final List> futures, final ConnectorState newState) { + if (futures.isEmpty()) { + return; + } + + final IllegalStateException failure = new IllegalStateException("Stop of " + componentDescription + " did not complete because its state changed to " + newState); + for (final CompletableFuture future : futures) { + future.completeExceptionally(failure); + } + + logger.info("Failed {} pending stop futures for {} on transition to {}", futures.size(), componentDescription, newState); + } + private void completeFutures(final List> futures, final ConnectorState newState) { for (final CompletableFuture future : futures) { future.complete(null); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java index 15f0c93f56b9..c03a1940fc68 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardFlowContext.java @@ -26,6 +26,7 @@ import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.parameter.ParameterContext; @@ -116,21 +117,10 @@ public void updateFlow(final VersionedExternalFlow versionedExternalFlow, final /** * Restores a persisted flow into the managed process group, keeping component identifiers so queued FlowFiles * reattach. When {@code parameterContext} is non-null its values are applied to the managed parameter context. - * Components resume according to the Process Group's auto-resume setting. + * {@code resumeComponentState} determines whether components resume as persisted or are left stopped. */ @Override - public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext) { - final VersionedExternalFlow externalFlow = toExternalFlow(persistedFlow, parameterContext); - managedProcessGroup.restoreFlowPreservingIdentifiers(externalFlow); - finishRestorePersistedFlow(externalFlow, parameterContext); - } - - /** - * Restores a persisted flow into the managed process group, keeping component identifiers so queued FlowFiles - * reattach. When {@code resumeComponentState} is false, components are left stopped. - */ - @Override - public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext, final boolean resumeComponentState) { + public void restorePersistedFlow(final VersionedProcessGroup persistedFlow, final VersionedParameterContext parameterContext, final ResumeComponentState resumeComponentState) { final VersionedExternalFlow externalFlow = toExternalFlow(persistedFlow, parameterContext); managedProcessGroup.restoreFlowPreservingIdentifiers(externalFlow, resumeComponentState); finishRestorePersistedFlow(externalFlow, parameterContext); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java index 29769019b36d..a63765d0a7c3 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/FlowEvolutionHookConnector.java @@ -31,7 +31,7 @@ /** * Connector that counts its flow evolution hook, update preparation, apply and start calls. The hook can return a future - * that never completes, and start can fail a given number of times. + * that never completes, and apply and start can each fail a given number of times. */ public class FlowEvolutionHookConnector extends AbstractConnector { @@ -42,6 +42,7 @@ public class FlowEvolutionHookConnector extends AbstractConnector { volatile int applyCalls; volatile boolean leaveFutureIncomplete; volatile CompletableFuture evolutionFuture; + volatile int remainingApplyFailures; volatile int remainingStartFailures; final AtomicInteger startCalls = new AtomicInteger(); final CountDownLatch hookEntered = new CountDownLatch(1); @@ -72,6 +73,10 @@ public List getConfigurationSteps() { @Override public void applyUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException { applyCalls++; + if (remainingApplyFailures > 0) { + remainingApplyFailures--; + throw new FlowUpdateException("Intentional apply failure"); + } } @Override diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java index de59c2ce6048..8ea4c6b2dc51 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/StandardConnectorNodeIT.java @@ -17,6 +17,8 @@ package org.apache.nifi.components.connector; +import org.apache.nifi.asset.Asset; +import org.apache.nifi.asset.AssetManager; import org.apache.nifi.bundle.Bundle; import org.apache.nifi.components.DescribedValue; import org.apache.nifi.components.connector.processors.CreateDummyFlowFile; @@ -69,7 +71,13 @@ import org.apache.nifi.controller.service.ControllerServiceState; import org.apache.nifi.controller.service.StandardControllerServiceProvider; import org.apache.nifi.engine.FlowEngine; +import org.apache.nifi.flow.VersionedAsset; +import org.apache.nifi.flow.VersionedComponent; +import org.apache.nifi.flow.VersionedParameter; +import org.apache.nifi.flow.VersionedProcessGroup; +import org.apache.nifi.flow.VersionedProcessor; import org.apache.nifi.groups.ProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.mock.MockNodeTypeProvider; import org.apache.nifi.nar.ExtensionDiscoveringManager; import org.apache.nifi.nar.StandardExtensionDiscoveringManager; @@ -80,6 +88,11 @@ import org.apache.nifi.processor.Relationship; import org.apache.nifi.provenance.ProvenanceRepository; import org.apache.nifi.python.PythonBridge; +import org.apache.nifi.registry.flow.diff.FlowComparatorVersionedStrategy; +import org.apache.nifi.registry.flow.diff.FlowDifference; +import org.apache.nifi.registry.flow.diff.StandardComparableDataFlow; +import org.apache.nifi.registry.flow.diff.StandardFlowComparator; +import org.apache.nifi.registry.flow.diff.StaticDifferenceDescriptor; import org.apache.nifi.reporting.BulletinRepository; import org.apache.nifi.scheduling.SchedulingStrategy; import org.apache.nifi.security.encryption.InternalPassThroughPropertyEncryptionProvider; @@ -104,6 +117,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.Function; import java.util.function.IntSupplier; import java.util.function.Predicate; @@ -111,7 +125,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -129,9 +145,11 @@ public class StandardConnectorNodeIT { private FlowEngine componentLifecycleThreadPool; private ConnectorRepository connectorRepository; private ControllerServiceProvider controllerServiceProvider; + private AssetManager connectorAssetManager; @BeforeEach public void setup() { + connectorAssetManager = mock(AssetManager.class); connectorRepository = new StandardConnectorRepository(); final SecretsManager secretsManager = new ParameterProviderSecretsManager(); @@ -175,6 +193,10 @@ public void setup() { when(flowController.getValidationTrigger()).thenReturn(mock(ValidationTrigger.class)); when(flowController.getConnectorValidationTrigger()).thenReturn(mock(ConnectorValidationTrigger.class)); when(flowController.getPropertyEncryptionProvider()).thenReturn(new InternalPassThroughPropertyEncryptionProvider()); + when(flowController.getConnectorAssetManager()).thenReturn(connectorAssetManager); + final AssetManager assetManager = mock(AssetManager.class); + when(assetManager.createMissingAsset(nullable(String.class), anyString())).thenAnswer(invocation -> mockAsset(invocation.getArgument(1))); + when(flowController.getAssetManager()).thenReturn(assetManager); doAnswer(invocation -> { return createConnection(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2), invocation.getArgument(3), invocation.getArgument(4)); @@ -408,6 +430,105 @@ public void testControllerServices() throws FlowUpdateException { assertInstanceOf(CounterService.class, serviceNodes.iterator().next().getControllerServiceImplementation()); } + /** + * Captures a managed flow in which a processor references both a managed Controller Service and an asset parameter of the + * managed Parameter Context, then rebuilds the flow from a different configuration that removes the service and both + * references and changes processor properties and connections, and drops the asset. Restoring the captured flow over the + * rebuilt one brings back the service with its original identifier, both references, and the asset, so capturing again + * yields the captured flow. + */ + @Test + public void testRestoringCapturedFlowOverRebuiltFlowReturnsCapturedFlow() throws FlowUpdateException { + final StandardConnectorNode connectorNode = (StandardConnectorNode) initializeDynamicFlowConnector(); + configure(connectorNode, createConnectorConfiguration("Restored", 2, false, true)); + + final Asset asset = mockAsset("asset-1"); + when(connectorAssetManager.getAsset("asset-1")).thenReturn(Optional.of(asset)); + final ProcessGroup managedGroup = connectorNode.getActiveFlowContext().getManagedProcessGroup(); + final ParameterContext parameterContext = managedGroup.getParameterContext(); + parameterContext.setParameters(Map.of("Asset Parameter", new Parameter.Builder().name("Asset Parameter").referencedAssets(List.of(asset)).build())); + final String assetParameterReference = "#{Asset Parameter}"; + findCreateDummyFlowFile(managedGroup).setProperties(Map.of("Text", assetParameterReference)); + + connectorNode.captureAuthoritativeSnapshot(); + final ConnectorFlowSnapshot captured = connectorNode.getAuthoritativeFlowSnapshot(); + final String counterServiceId = managedGroup.getControllerServices(true).iterator().next().getIdentifier(); + + configure(connectorNode, createConnectorConfiguration("Rebuilt", 3, true, false)); + parameterContext.setParameters(Map.of("Asset Parameter", new Parameter.Builder().name("Asset Parameter").build())); + assertTrue(managedGroup.getControllerServices(true).isEmpty()); + assertNull(getRawPropertyValue(findCreateDummyFlowFile(managedGroup), "Counter Service")); + assertNotEquals(assetParameterReference, getRawPropertyValue(findCreateDummyFlowFile(managedGroup), "Text")); + connectorNode.captureAuthoritativeSnapshot(); + assertFalse(compareFlows(captured.flow(), connectorNode.getAuthoritativeFlowSnapshot().flow()).isEmpty()); + + connectorNode.restorePersistedFlow(captured.flow(), captured.parameterContext(), captured.parameterSecretReferences(), ResumeComponentState.LEAVE_STOPPED); + connectorNode.captureAuthoritativeSnapshot(); + final ConnectorFlowSnapshot restored = connectorNode.getAuthoritativeFlowSnapshot(); + + assertEquals(Set.of(), compareFlows(captured.flow(), restored.flow())); + + final Set restoredServices = managedGroup.getControllerServices(true); + assertEquals(1, restoredServices.size()); + assertEquals(counterServiceId, restoredServices.iterator().next().getIdentifier()); + final ProcessorNode restoredProcessor = findCreateDummyFlowFile(managedGroup); + assertEquals(counterServiceId, getRawPropertyValue(restoredProcessor, "Counter Service")); + assertEquals(assetParameterReference, getRawPropertyValue(restoredProcessor, "Text")); + assertEquals(counterServiceId, findProcessor(restored.flow(), CreateDummyFlowFile.class.getName()).getProperties().get("Counter Service")); + + final VersionedParameter assetParameter = restored.parameterContext().getParameters().stream() + .filter(parameter -> "Asset Parameter".equals(parameter.getName())) + .findFirst() + .orElseThrow(); + assertEquals(List.of("asset-1"), assetParameter.getReferencedAssets().stream().map(VersionedAsset::getIdentifier).toList()); + assertEquals(List.of(asset), parameterContext.getParameter("Asset Parameter").orElseThrow().getReferencedAssets()); + } + + private static Set compareFlows(final VersionedProcessGroup expected, final VersionedProcessGroup actual) { + final StandardFlowComparator comparator = new StandardFlowComparator( + new StandardComparableDataFlow("Expected Flow", expected), + new StandardComparableDataFlow("Actual Flow", actual), + new StaticDifferenceDescriptor(), Function.identity(), VersionedComponent::getInstanceIdentifier, FlowComparatorVersionedStrategy.DEEP); + return comparator.compare().getDifferences(); + } + + private static ProcessorNode findCreateDummyFlowFile(final ProcessGroup managedGroup) { + return managedGroup.findAllProcessors().stream() + .filter(candidate -> CreateDummyFlowFile.class.getName().equals(candidate.getCanonicalClassName())) + .findFirst() + .orElseThrow(); + } + + private static String getRawPropertyValue(final ProcessorNode processor, final String propertyName) { + return processor.getRawPropertyValue(processor.getPropertyDescriptor(propertyName)); + } + + private static Asset mockAsset(final String identifier) { + final Asset asset = mock(Asset.class); + when(asset.getIdentifier()).thenReturn(identifier); + when(asset.getName()).thenReturn(identifier + ".txt"); + when(asset.getFile()).thenReturn(new File("target", identifier + ".txt")); + when(asset.getDigest()).thenReturn(Optional.empty()); + return asset; + } + + private static VersionedProcessor findProcessor(final VersionedProcessGroup group, final String type) { + for (final VersionedProcessor processor : group.getProcessors()) { + if (type.equals(processor.getType())) { + return processor; + } + } + + for (final VersionedProcessGroup childGroup : group.getProcessGroups()) { + final VersionedProcessor processor = findProcessor(childGroup, type); + if (processor != null) { + return processor; + } + } + + return null; + } + @Test public void testStopConnectorWhileManagedServiceBlocksInOnEnabled() throws Exception { final ConnectorNode connectorNode = initializeControllerServiceEnablingConnector(ControllerServiceEnablingConnector.BLOCKING_ENABLING); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java index 6409d2856064..f729383ece7d 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java @@ -54,6 +54,7 @@ import org.apache.nifi.groups.FlowFileConcurrency; import org.apache.nifi.groups.FlowFileOutboundPolicy; import org.apache.nifi.groups.ProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.migration.ConnectorPropertyConfiguration; import org.apache.nifi.nar.ExtensionManager; @@ -247,6 +248,25 @@ public void testStopFromRunningState() throws Exception { assertFalse(stopFuture.isCancelled()); } + @Test + public void testStopDuringUpdateFailsWhenUpdateAbortsFirst() throws Exception { + final StandardConnectorNode connectorNode = createConnectorNode(); + connectorNode.transitionStateForUpdating(); + final FlowEngine deferringScheduler = mock(FlowEngine.class); + + final Future stopFuture = connectorNode.stop(deferringScheduler); + final ArgumentCaptor stopTask = ArgumentCaptor.forClass(Runnable.class); + verify(deferringScheduler).schedule(stopTask.capture(), eq(0L), eq(TimeUnit.SECONDS)); + + // The update fails after the stop moved the Connector to STOPPING but before the scheduled stop runs + connectorNode.abortUpdate(new FlowUpdateException("Update failed")); + stopTask.getValue().run(); + + final ExecutionException failure = assertThrows(ExecutionException.class, () -> stopFuture.get(5, TimeUnit.SECONDS)); + assertTrue(failure.getCause().getMessage().contains("UPDATE_FAILED"), failure.getCause().getMessage()); + assertEquals(ConnectorState.UPDATE_FAILED, connectorNode.getCurrentState()); + } + @Test public void testRestartRefreshesSecretBeforeStartingConnector() throws Exception { final SecretReference secretReference = new SecretReference("provider-id", "Provider", "password", "Provider.group.password"); @@ -996,6 +1016,8 @@ public void testReplaceConnectorWithGhostMarksExtensionMissing() throws FlowUpda assertSame(ghostConnector, connectorNode.getConnector()); assertTrue(connectorNode.isExtensionMissing()); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertEquals(FlowEvolutionStatus.INACTIVE, connectorNode.getReportedFlowEvolutionStatus()); assertEquals("(Missing) TrackingConnector", connectorNode.getComponentType()); final ConnectorAction startWhileGhosted = findAction(connectorNode, "START"); @@ -1009,6 +1031,7 @@ public void testReplaceConnectorWithGhostMarksExtensionMissing() throws FlowUpda connectorNode.performValidation(); assertFalse(connectorNode.isExtensionMissing()); + assertTrue(connectorNode.isPendingFlowEvolution()); assertTrue(connectorNode.isManagedFlowRestoreFailed()); final ConnectorAction start = findAction(connectorNode, "START"); assertFalse(start.isAllowed()); @@ -2177,20 +2200,138 @@ public void testInheritingConfigurationKeepsTransitivelyGatedRequiredPropertyIrr @Test - public void testEvolveFlowReturnsSameTaskWhileHookIsPending() throws Exception { + public void testFlowEvolutionLifecycle() throws Exception { final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + final StandardConnectorNode connectorNode = createConnectorNode(connector); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertEquals(FlowEvolutionStatus.INACTIVE, connectorNode.getReportedFlowEvolutionStatus()); + assertThrows(IllegalStateException.class, () -> connectorNode.prepareFlowEvolution(scheduler)); + + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); + assertThrows(FlowUpdateException.class, connectorNode::beginEvolvedFlowUpdate); + connector.leaveFutureIncomplete = true; + connectorNode.prepareFlowEvolution(scheduler); + assertEquals(ConnectorState.DRAINING, connectorNode.getCurrentState()); + assertEquals(ConnectorState.RUNNING, connectorNode.getDesiredState()); + assertThrows(FlowUpdateException.class, connectorNode::beginEvolvedFlowUpdate); + assertEquals(ConnectorState.DRAINING, connectorNode.getCurrentState()); + + final Future failedEvolution = connectorNode.evolveFlow(flowEvolutionExecutor); + assertTrue(connector.evolutionFuturePublished.await(5, TimeUnit.SECONDS)); + assertSame(failedEvolution, connectorNode.evolveFlow(flowEvolutionExecutor)); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); + + connector.evolutionFuture.completeExceptionally(new IllegalStateException("queue still holds data")); + final ExecutionException hookFailure = assertThrows(ExecutionException.class, () -> failedEvolution.get(5, TimeUnit.SECONDS)); + assertInstanceOf(FlowUpdateException.class, hookFailure.getCause()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertTrue(connectorNode.getValidationErrors().stream() + .anyMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()) && "queue still holds data".equals(result.getExplanation()))); + + connector.leaveFutureIncomplete = false; + connectorNode.prepareFlowEvolution(scheduler); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); + connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS); + assertEquals(2, connector.hookCalls); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE, connectorNode.getReportedFlowEvolutionStatus()); + assertTrue(connectorNode.isPendingFlowEvolution()); + + connectorNode.beginEvolvedFlowUpdate(); + assertEquals(ConnectorState.PREPARING_FOR_UPDATE, connectorNode.getCurrentState()); + connectorNode.prepareForUpdate(); + connectorNode.applyUpdate(); + + assertEquals(ConnectorState.UPDATED, connectorNode.getCurrentState()); + assertEquals(ConnectorState.RUNNING, connectorNode.getDesiredState()); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertEquals(FlowEvolutionStatus.INACTIVE, connectorNode.getReportedFlowEvolutionStatus()); + assertEquals("1.0.0", connectorNode.getAuthoritativeFlowSnapshot().bundle().getVersion()); + assertEquals(1, connector.applyCalls); + } + + @Test + public void testFlowEvolutionAfterFailedApplyResumesAfterHook() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + connector.remainingApplyFailures = 1; final StandardConnectorNode connectorNode = createConnectorNode(connector); connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + connectorNode.prepareFlowEvolution(scheduler); + connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS); + connectorNode.beginEvolvedFlowUpdate(); + connectorNode.prepareForUpdate(); + assertThrows(FlowUpdateException.class, connectorNode::applyUpdate); + assertEquals(ConnectorState.UPDATE_FAILED, connectorNode.getCurrentState()); + assertTrue(connectorNode.isPendingFlowEvolution()); + + connectorNode.prepareFlowEvolution(scheduler); + assertEquals(ConnectorState.DRAINING, connectorNode.getCurrentState()); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE, connectorNode.getReportedFlowEvolutionStatus()); + connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS); - connectorNode.prepareFlowEvolution(); + // An attempt that resumed after the hook keeps the drain progress when it fails, because the upgraded flow may have been partly applied + connectorNode.failFlowEvolution("upgraded flow could not be applied", null); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + connectorNode.prepareFlowEvolution(scheduler); + assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_COMPLETE, connectorNode.getReportedFlowEvolutionStatus()); + + connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS); + connectorNode.beginEvolvedFlowUpdate(); + connectorNode.prepareForUpdate(); + connectorNode.applyUpdate(); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertEquals(1, connector.hookCalls); + assertEquals(2, connector.applyCalls); + } + + @Test + public void testStopCancelsFlowEvolutionInProgress() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + connector.leaveFutureIncomplete = true; + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + connectorNode.prepareFlowEvolution(scheduler); final Future evolution = connectorNode.evolveFlow(flowEvolutionExecutor); assertTrue(connector.evolutionFuturePublished.await(5, TimeUnit.SECONDS)); - assertSame(evolution, connectorNode.evolveFlow(flowEvolutionExecutor)); - assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); - // The hook stays blocked, so the task has to be interrupted before the executor is closed. - evolution.cancel(true); + final Future stopFuture = connectorNode.stop(scheduler); + assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + assertThrows(CancellationException.class, () -> evolution.get(5, TimeUnit.SECONDS)); + assertThrows(CancellationException.class, () -> connector.evolutionFuture.get(5, TimeUnit.SECONDS)); + assertFalse(stopFuture.isDone()); + + // The Connector Repository fails the cancelled evolution, which stops the pre-upgrade flow and completes the stop + connectorNode.abortUpdate(new FlowUpdateException("Flow evolution was cancelled")); + stopFuture.get(5, TimeUnit.SECONDS); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertEvolutionContextClosed(connector.context); + } + + @Test + public void testEnsureAuthoritativeFlowSnapshot() throws Exception { + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); + assertNull(connectorNode.getAuthoritativeFlowSnapshot()); + + connectorNode.ensureAuthoritativeFlowSnapshot(); + final ConnectorFlowSnapshot captured = connectorNode.getAuthoritativeFlowSnapshot(); + assertEquals("1.0.0", captured.bundle().getVersion()); + assertFalse(connectorNode.isPendingFlowEvolution()); + connectorNode.ensureAuthoritativeFlowSnapshot(); + assertSame(captured, connectorNode.getAuthoritativeFlowSnapshot()); + + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + final ConnectorFlowSnapshot outgoing = connectorNode.getAuthoritativeFlowSnapshot(); + connectorNode.ensureAuthoritativeFlowSnapshot(); + assertSame(outgoing, connectorNode.getAuthoritativeFlowSnapshot()); + assertThrows(IllegalStateException.class, connectorNode::captureAuthoritativeSnapshot); + assertTrue(connectorNode.isPendingFlowEvolution()); } @Test @@ -2200,7 +2341,7 @@ public void testAbortUpdateInterruptsBlockedFlowEvolutionHook() throws Exception final StandardConnectorNode connectorNode = createConnectorNode(connector); connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); final Future evolution = connectorNode.evolveFlow(flowEvolutionExecutor); assertTrue(connector.hookEntered.await(5, TimeUnit.SECONDS)); assertTrue(connector.evolutionFuturePublished.await(5, TimeUnit.SECONDS)); @@ -2220,7 +2361,7 @@ public void testBeginEvolvedFlowUpdateWithQueuedFlowFilesInRemovedConnection() t final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); final StandardConnectorNode connectorNode = createConnectorNode(connector); connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS); assertEquals(outgoingSnapshotBundle().getVersion(), connector.preUpgradeBundle.getVersion()); @@ -2236,28 +2377,17 @@ public void testBeginEvolvedFlowUpdateWithQueuedFlowFilesInRemovedConnection() t assertEquals(0, connector.applyCalls); } - @Test - public void testBeginEvolvedFlowUpdateRequiresCompletedEvolveDrain() throws Exception { - final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); - connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); - assertThrows(FlowUpdateException.class, connectorNode::beginEvolvedFlowUpdate); - - connectorNode.prepareFlowEvolution(); - assertThrows(FlowUpdateException.class, connectorNode::beginEvolvedFlowUpdate); - assertEquals(ConnectorState.DRAINING, connectorNode.getCurrentState()); - } - @Test public void testStaleEvolutionTaskReleasedDuringNextEvolution() throws Exception { final GatedActiveFlowConnector connector = new GatedActiveFlowConnector(); final StandardConnectorNode connectorNode = createConnectorNode(connector); connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); final Future evolution = connectorNode.evolveFlow(flowEvolutionExecutor); assertTrue(connector.reachedActiveFlow.await(5, TimeUnit.SECONDS)); connectorNode.abortUpdate(new FlowUpdateException("cancel")); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); connector.releaseActiveFlow.countDown(); assertThrows(CancellationException.class, () -> evolution.get(5, TimeUnit.SECONDS)); @@ -2302,7 +2432,7 @@ public void testRevalidationAndRetryAfterFlowEvolutionFailure() throws Exception .count()); connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); assertTrue(connectorNode.getValidationErrors().stream() @@ -2312,48 +2442,37 @@ public void testRevalidationAndRetryAfterFlowEvolutionFailure() throws Exception } @Test - public void testFlowEvolutionFailureWhenPreUpgradeFlowDoesNotStop() throws Exception { - final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); + public void testPreUpgradeStopRetryCompletesStopWithoutStarting() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); final ProcessGroupLifecycle lifecycle = connectorNode.getActiveFlowContext().getRootGroup().getLifecycle(); when(lifecycle.stop()) + .thenReturn(CompletableFuture.failedFuture(new TimeoutException("still running"))) .thenReturn(CompletableFuture.failedFuture(new TimeoutException("still running"))) .thenReturn(CompletableFuture.completedFuture(null)); + final FlowEngine deferringScheduler = mock(FlowEngine.class); + connectorNode.prepareFlowEvolution(deferringScheduler); + // The evolve-drain task and the Connector Repository's abort can each finish the same failure + connectorNode.failFlowEvolution("hook started processors that would not stop", null); connectorNode.failFlowEvolution("hook started processors that would not stop", null); - assertEquals(ConnectorState.STOPPING, connectorNode.getCurrentState()); assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); - assertTrue(connectorNode.getValidationErrors().stream() - .anyMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()))); - connectorNode.retryPreUpgradeStop(scheduler); + final Future stopFuture = connectorNode.stop(scheduler); + final Future startFuture = connectorNode.start(scheduler); + assertThrows(ExecutionException.class, () -> startFuture.get(5, TimeUnit.SECONDS)); - final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (connectorNode.getCurrentState() != ConnectorState.STOPPED && System.nanoTime() < deadline) { - Thread.sleep(50); - } + final ArgumentCaptor retryTask = ArgumentCaptor.forClass(Runnable.class); + verify(deferringScheduler).schedule(retryTask.capture(), eq(0L), eq(TimeUnit.SECONDS)); + retryTask.getValue().run(); + stopFuture.get(5, TimeUnit.SECONDS); assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); - assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); - } - - @Test - public void testStartWhilePreUpgradeFlowIsStopping() throws Exception { - final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); - final ProcessGroupLifecycle lifecycle = connectorNode.getActiveFlowContext().getRootGroup().getLifecycle(); - when(lifecycle.stop()) - .thenReturn(CompletableFuture.failedFuture(new TimeoutException("still running"))) - .thenReturn(CompletableFuture.completedFuture(null)); - - connectorNode.failFlowEvolution("hook started processors that would not stop", null); - assertEquals(ConnectorState.STOPPING, connectorNode.getCurrentState()); - - final Future startFuture = connectorNode.start(scheduler); - connectorNode.retryPreUpgradeStop(scheduler); - startFuture.get(5, TimeUnit.SECONDS); - - assertEquals(ConnectorState.RUNNING, connectorNode.getCurrentState()); + assertTrue(connectorNode.isPendingFlowEvolution()); + assertEquals(0, connector.startCalls.get()); } @Test @@ -2367,7 +2486,7 @@ public void testEvolveFlowRejectsMissingManagedComponents() throws Exception { final StandardConnectorNode connectorNode = createConnectorNode(connector); connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); final ExecutionException processorFailure = assertThrows(ExecutionException.class, () -> connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS)); assertTrue(processorFailure.getCause().getMessage().contains("MissingProcessor"), processorFailure.getCause().getMessage()); @@ -2390,7 +2509,7 @@ public void testFlowEvolutionWithMissingSecretThenRestoredSecret() throws Except persistedParameterContext("Source Database Password"), Map.of("Source Database Password", secretReference), outgoingSnapshotBundle()); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); final ExecutionException failure = assertThrows(ExecutionException.class, () -> connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS)); assertTrue(failure.getCause().getMessage().contains("Provider.group.password"), failure.getCause().getMessage()); @@ -2401,7 +2520,7 @@ public void testFlowEvolutionWithMissingSecretThenRestoredSecret() throws Except final Secret restoredSecret = mock(Secret.class); when(restoredSecret.getValue()).thenReturn("current-password"); currentSecret.set(restoredSecret); - connectorNode.prepareFlowEvolution(); + connectorNode.prepareFlowEvolution(scheduler); assertEquals(FlowEvolutionStatus.EVOLVE_DRAIN_PENDING, connectorNode.getReportedFlowEvolutionStatus()); assertTrue(connectorNode.getValidationErrors().stream() .noneMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()))); @@ -2414,16 +2533,105 @@ public void testFlowEvolutionWithMissingSecretThenRestoredSecret() throws Except } @Test - public void testRestorePersistedFlowKeepsComponentsStoppedWhenSecretMissing() throws Exception { + public void testRestorePersistedFlowKeepsComponentsStoppedWhenSecretUnavailable() throws Exception { final SecretReference secretReference = new SecretReference("provider-id", "Provider", "password", "Provider.group.password"); when(secretsManager.getSecrets(anySet(), eq(false))).thenReturn(Map.of()); final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector(), secretsManager); clearInvocations(managedProcessGroup); connectorNode.restorePersistedFlow(flowGroup("pre-upgrade"), - persistedParameterContext("Source Database Password"), Map.of("Source Database Password", secretReference), true); + persistedParameterContext("Source Database Password"), Map.of("Source Database Password", secretReference), ResumeComponentState.RESUME_AS_PERSISTED); + verify(managedProcessGroup).restoreFlowPreservingIdentifiers(any(VersionedExternalFlow.class), eq(ResumeComponentState.LEAVE_STOPPED)); + + // A Secrets Provider that cannot be reached is treated the same as a missing secret + when(secretsManager.getSecrets(anySet(), eq(false))).thenThrow(new IllegalStateException("Secrets Provider unavailable")); + clearInvocations(managedProcessGroup); + final VersionedConnector persisted = new VersionedConnector(); + persisted.setManagedProcessGroup(flowGroup("pre-upgrade")); + persisted.setManagedParameterContext(persistedParameterContext("Source Database Password")); + persisted.setManagedParameterSecretReferences(Map.of("Source Database Password", versionedSecretReference(secretReference))); + persisted.setManagedFlowBundle(outgoingSnapshotBundle()); - verify(managedProcessGroup).restoreFlowPreservingIdentifiers(any(VersionedExternalFlow.class), eq(false)); + assertTrue(connectorNode.restorePendingFlowEvolution(persisted, List.of(), List.of())); + verify(managedProcessGroup).restoreFlowPreservingIdentifiers(any(VersionedExternalFlow.class), eq(ResumeComponentState.LEAVE_STOPPED)); + assertFalse(connectorNode.isManagedFlowRestoreFailed()); + assertTrue(connectorNode.isPendingFlowEvolution()); + } + + @Test + public void testVerifyCanStartRequiresStoppedConnectorWhenUpgradePending() throws Exception { + final StandardConnectorStateTransition stateTransition = new StandardConnectorStateTransition("TestConnectorNode"); + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector(), stateTransition); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + assertTrue(connectorNode.isPendingFlowEvolution()); + connectorNode.verifyCanStart(); + + for (final ConnectorState state : List.of(ConnectorState.STOPPING, ConnectorState.PURGING, ConnectorState.DRAINING)) { + stateTransition.setCurrentState(state); + final IllegalStateException failure = assertThrows(IllegalStateException.class, connectorNode::verifyCanStart); + assertTrue(failure.getMessage().contains("upgrade is pending"), failure.getMessage()); + } + + // A start that joins an evolution already draining is allowed + stateTransition.setCurrentState(ConnectorState.STOPPED); + connectorNode.prepareFlowEvolution(scheduler); + assertEquals(ConnectorState.DRAINING, connectorNode.getCurrentState()); + connectorNode.verifyCanStart(); + } + + @Test + public void testStartRefusedWhileUpgradePending() throws Exception { + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + final StandardConnectorNode connectorNode = createConnectorNode(connector); + connectorNode.adoptAuthoritativeSnapshot(flowGroup("pre-upgrade"), null, Map.of(), outgoingSnapshotBundle()); + + final Future startFuture = connectorNode.start(scheduler); + + final ExecutionException failure = assertThrows(ExecutionException.class, () -> startFuture.get(5, TimeUnit.SECONDS)); + assertTrue(failure.getCause().getMessage().contains("upgrade is pending"), failure.getCause().getMessage()); + assertEquals(ConnectorState.STOPPED, connectorNode.getDesiredState()); + assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); + assertEquals(0, connector.startCalls.get()); + } + + @Test + public void testRestorePendingFlowEvolutionAdoptsSnapshotWhenRestoreFails() throws Exception { + final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); + doThrow(new IllegalStateException("Restore failed")).when(managedProcessGroup) + .restoreFlowPreservingIdentifiers(any(VersionedExternalFlow.class), eq(ResumeComponentState.RESUME_AS_PERSISTED)); + final VersionedProcessGroup persistedGroup = flowGroup("pre-upgrade"); + final VersionedConnector persisted = new VersionedConnector(); + persisted.setManagedProcessGroup(persistedGroup); + persisted.setManagedFlowBundle(outgoingSnapshotBundle()); + final VersionedConnectorValueReference greeting = new VersionedConnectorValueReference(); + greeting.setValueType("STRING_LITERAL"); + greeting.setValue("Welcome"); + final VersionedConfigurationStep activeStep = new VersionedConfigurationStep(); + activeStep.setName("settings"); + activeStep.setProperties(Map.of("Greeting", greeting)); + + assertTrue(connectorNode.restorePendingFlowEvolution(persisted, List.of(activeStep), List.of(activeStep))); + + assertTrue(connectorNode.isManagedFlowRestoreFailed()); + assertTrue(connectorNode.isPendingFlowEvolution()); + final IllegalStateException startFailure = assertThrows(IllegalStateException.class, connectorNode::verifyCanStart); + assertTrue(startFailure.getMessage().contains("could not be restored"), startFailure.getMessage()); + + final ConnectorFlowSnapshot snapshot = connectorNode.getAuthoritativeFlowSnapshot(); + assertSame(persistedGroup, snapshot.flow()); + assertEquals(outgoingSnapshotBundle(), snapshot.bundle()); + final ConnectorValueReference activeGreeting = snapshot.activeConfiguration().getNamedStepConfiguration("settings").configuration().getPropertyValue("Greeting"); + assertEquals(new StringLiteralValue("Welcome"), activeGreeting); + } + + private static VersionedConnectorValueReference versionedSecretReference(final SecretReference secretReference) { + final VersionedConnectorValueReference reference = new VersionedConnectorValueReference(); + reference.setValueType("SECRET_REFERENCE"); + reference.setProviderId(secretReference.getProviderId()); + reference.setProviderName(secretReference.getProviderName()); + reference.setSecretName(secretReference.getSecretName()); + reference.setFullyQualifiedSecretName(secretReference.getFullyQualifiedName()); + return reference; } @Test diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java index 236dbf98c328..b9911593828e 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java @@ -46,6 +46,7 @@ import org.apache.nifi.groups.FlowFileConcurrency; import org.apache.nifi.groups.FlowFileOutboundPolicy; import org.apache.nifi.groups.ProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.migration.ConnectorPropertyConfiguration; import org.apache.nifi.nar.ExtensionManager; @@ -2867,11 +2868,16 @@ private StandardConnectorNode createRealConnectorNode(final String identifier, f } private StandardConnectorNode createRealConnectorNode(final String identifier, final Connector connector, final boolean extensionMissing) throws FlowUpdateException { - final ExtensionManager extensionManager = mock(ExtensionManager.class); - final AssetManager assetManager = mock(AssetManager.class); final SecretsManager secretsManager = mock(SecretsManager.class); when(secretsManager.getAllSecrets()).thenReturn(List.of()); when(secretsManager.getSecrets(anySet())).thenReturn(Collections.emptyMap()); + return createRealConnectorNode(identifier, connector, extensionMissing, secretsManager); + } + + private StandardConnectorNode createRealConnectorNode(final String identifier, final Connector connector, final boolean extensionMissing, + final SecretsManager secretsManager) throws FlowUpdateException { + final ExtensionManager extensionManager = mock(ExtensionManager.class); + final AssetManager assetManager = mock(AssetManager.class); final ProcessGroup managedProcessGroup = mock(ProcessGroup.class); when(managedProcessGroup.purge()).thenReturn(CompletableFuture.completedFuture(null)); @@ -3330,6 +3336,47 @@ public void testSameBundleSyncKeepsHeldSnapshot() throws Exception { assertEquals(outgoingSnapshotBundle().getVersion(), pendingNode.getAuthoritativeFlowSnapshot().bundle().getVersion()); } + /** + * A same-bundle restart rebuilds the managed flow from the persisted configuration, giving the Connector the resolved secret + * behind its sensitive parameter, and does not restore the persisted managed group over the rebuilt flow. + */ + @Test + public void testSameBundleSyncRebuildsFlowWithSecretDerivedParameter() throws Exception { + final Secret secret = mock(Secret.class); + when(secret.getValue()).thenReturn("resolved-secret"); + final SecretsManager secretsManager = mock(SecretsManager.class); + when(secretsManager.getAllSecrets()).thenReturn(List.of()); + when(secretsManager.getSecrets(anySet())).thenAnswer(invocation -> { + final Set references = invocation.getArgument(0); + return references.stream().collect(Collectors.toMap(Function.identity(), reference -> secret)); + }); + final SecretParameterConnector connector = new SecretParameterConnector(); + final StandardConnectorNode connectorNode = createRealConnectorNode("connector-1", connector, false, secretsManager); + final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null); + repository.restoreConnector(connectorNode); + + final VersionedConnectorValueReference secretReference = new VersionedConnectorValueReference(); + secretReference.setValueType(ConnectorValueType.SECRET_REFERENCE.name()); + secretReference.setProviderId("provider-id"); + secretReference.setProviderName("Provider"); + secretReference.setSecretName("password"); + secretReference.setFullyQualifiedSecretName("Provider.password"); + final List persistedConfiguration = List.of(createVersionedStep(SecretParameterConnector.STEP, Map.of( + SecretParameterConnector.PASSWORD, secretReference))); + final VersionedConnector versioned = versionedConnector(new Bundle("org.apache.nifi", "test-standard-connector-node", "1.0.0"), flowGroup("persisted-flow")); + versioned.setType(SecretParameterConnector.class.getName()); + versioned.setActiveFlowConfiguration(persistedConfiguration); + versioned.setWorkingFlowConfiguration(persistedConfiguration); + + final ConnectorSyncResult result = repository.syncConnector(versioned); + + assertEquals(ConnectorSyncResult.Outcome.SYNCED, result.getOutcome()); + assertEquals("resolved-secret", connector.appliedPassword); + verify(connectorNode.getActiveFlowContext().getManagedProcessGroup(), never()).restoreFlowPreservingIdentifiers(any(), any()); + assertFalse(connectorNode.isPendingFlowEvolution()); + assertNotEquals("persisted-flow", connectorNode.getAuthoritativeFlowSnapshot().flow().getName()); + } + @Test public void testPersistedComponentBundleResolution() throws Exception { final StandardConnectorNode ambiguous = createRealConnectorNode("connector-1", new FlowEvolutionHookConnector()); @@ -3360,7 +3407,7 @@ public void testGhostSyncRestoreFailureFlagsConnectorAndAdoptsSnapshot() throws final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null); repository.restoreConnector(connectorNode); doThrow(new IllegalStateException("Expected restore failure")).when(connectorNode.getActiveFlowContext().getManagedProcessGroup()) - .restoreFlowPreservingIdentifiers(any(), eq(false)); + .restoreFlowPreservingIdentifiers(any(), eq(ResumeComponentState.LEAVE_STOPPED)); final VersionedProcessGroup persisted = flowGroup("ghost-flow"); final ConnectorSyncResult result = repository.syncConnector( @@ -3496,6 +3543,39 @@ private static VersionedProcessGroup componentGroup(final String name, final Bun return group; } + /** + * Sets a sensitive parameter from its secret-backed Password property when its flow is built. + */ + private static class SecretParameterConnector extends FlowEvolutionHookConnector { + private static final String STEP = "settings"; + private static final String PASSWORD = "Password"; + + private volatile String appliedPassword; + + @Override + public List getConfigurationSteps() { + final ConnectorPropertyDescriptor password = new ConnectorPropertyDescriptor.Builder() + .name(PASSWORD) + .description(PASSWORD) + .type(PropertyType.SECRET) + .build(); + return List.of(new ConfigurationStep.Builder() + .name(STEP) + .propertyGroups(List.of(ConnectorPropertyGroup.builder() + .name("General") + .description("General") + .properties(List.of(password)) + .build())) + .build()); + } + + @Override + public void applyUpdate(final FlowContext workingContext, final FlowContext activeContext) throws FlowUpdateException { + super.applyUpdate(workingContext, activeContext); + appliedPassword = workingContext.getConfigurationContext().getProperty(STEP, PASSWORD).getValue(); + } + } + private static class MigratingConnector extends TrackingConnector { private java.util.function.Consumer migration = config -> { }; diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorStateTransition.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorStateTransition.java index aaf29f016761..0e3a4aec173a 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorStateTransition.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorStateTransition.java @@ -20,7 +20,11 @@ import org.junit.jupiter.api.Test; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class TestStandardConnectorStateTransition { @@ -35,4 +39,27 @@ void testAddPendingStartFutureWhenRunningCompletesFuture() { assertTrue(startFuture.isDone()); } + + @Test + void testPendingStopFutureCompletesOnlyWhenStoppedAndFailsOnOtherStates() { + final StandardConnectorStateTransition stateTransition = new StandardConnectorStateTransition("Test Connector"); + stateTransition.setCurrentState(ConnectorState.STOPPING); + final CompletableFuture stoppedFuture = new CompletableFuture<>(); + stateTransition.addPendingStopFuture(stoppedFuture); + + stateTransition.setCurrentState(ConnectorState.STOPPING); + assertFalse(stoppedFuture.isDone()); + stateTransition.setCurrentState(ConnectorState.STOPPED); + assertTrue(stoppedFuture.isDone()); + assertFalse(stoppedFuture.isCompletedExceptionally()); + + stateTransition.setCurrentState(ConnectorState.PREPARING_FOR_UPDATE); + final CompletableFuture abandonedFuture = new CompletableFuture<>(); + stateTransition.addPendingStopFuture(abandonedFuture); + assertTrue(stateTransition.trySetCurrentState(ConnectorState.PREPARING_FOR_UPDATE, ConnectorState.UPDATE_FAILED)); + + final ExecutionException failure = assertThrows(ExecutionException.class, abandonedFuture::get); + assertInstanceOf(IllegalStateException.class, failure.getCause()); + assertTrue(failure.getCause().getMessage().contains("UPDATE_FAILED"), failure.getCause().getMessage()); + } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java index 6b24eee538b3..96f46e19a6dc 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardFlowContext.java @@ -29,6 +29,7 @@ import org.apache.nifi.flow.VersionedParameterContext; import org.apache.nifi.flow.VersionedProcessGroup; import org.apache.nifi.groups.ProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.parameter.ParameterContext; import org.junit.jupiter.api.Test; @@ -111,7 +112,7 @@ public void testRestorePersistedFlowResolvesParameterAssets() { versionedParameterContext.setName("managed-parameters"); versionedParameterContext.setParameters(Set.of(versionedParameter)); - flowContext.restorePersistedFlow(new VersionedProcessGroup(), versionedParameterContext); + flowContext.restorePersistedFlow(new VersionedProcessGroup(), versionedParameterContext, ResumeComponentState.RESUME_AS_PERSISTED); final ArgumentCaptor> valuesCaptor = ArgumentCaptor.forClass(List.class); verify(parameterContextFacade).updateParameters(valuesCaptor.capture()); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java index 8fd9a339a74f..17c7a7120550 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/service/mock/MockProcessGroup.java @@ -47,6 +47,7 @@ import org.apache.nifi.groups.ProcessGroup; import org.apache.nifi.groups.ProcessGroupCounts; import org.apache.nifi.groups.RemoteProcessGroup; +import org.apache.nifi.groups.ResumeComponentState; import org.apache.nifi.groups.StatelessGroupNode; import org.apache.nifi.groups.StatelessGroupScheduledState; import org.apache.nifi.groups.VersionedComponentAdditions; @@ -735,12 +736,7 @@ public void updateFlow(VersionedExternalFlow proposedFlow, String componentIdSee } @Override - public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedFlow) { - } - - @Override - public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedFlow, final boolean resumeComponentState) { - restoreFlowPreservingIdentifiers(proposedFlow); + public void restoreFlowPreservingIdentifiers(final VersionedExternalFlow proposedFlow, final ResumeComponentState resumeComponentState) { } @Override diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java index bf47bea441d5..9df46606a8b2 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java @@ -3896,13 +3896,8 @@ public ConnectorEntity scheduleConnector(final Revision revision, final String i case STOPPED -> connectorDAO.stopConnector(id); default -> throw new IllegalArgumentException("Unsupported scheduled state for Connector: " + state); } - // Evolution sets the desired state to RUNNING as soon as it is claimed so a joining node starts too. - // Persisting that state before the hook succeeds makes a failed evolution auto-start on restart. - // The repository saves once the upgraded flow is applied, and a failed evolution puts the desired state back. - final ConnectorNode scheduled = connectorDAO.getConnector(id, ConnectorSyncMode.LOCAL_ONLY); - if (scheduled.getCurrentState() != ConnectorState.DRAINING || !scheduled.isPendingFlowEvolution()) { - controllerFacade.save(); - } + // A start that begins a flow evolution is saved as RUNNING, so a restart while the Connector drains resumes the upgrade. + controllerFacade.save(); final ConnectorNode node = connectorDAO.getConnector(id, ConnectorSyncMode.LOCAL_ONLY); final ConnectorDTO dto = dtoFactory.createConnectorDto(node); diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java index ffb2ae33998b..ddf3c63ce139 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/FlowDefinitionFiles.java @@ -27,7 +27,8 @@ import java.util.zip.GZIPInputStream; /** - * Reads connector sections of a stopped node's conf/flow.json.gz. + * Reads connector sections of a node's conf/flow.json.gz. A read while the node runs may overlap a save and fail, so callers + * that read a running node retry. */ public final class FlowDefinitionFiles { diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java index 44b8b4bbd100..69958e856d2c 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java @@ -44,6 +44,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Predicate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -104,6 +106,10 @@ String recordPrefix() { return "org.apache.nifi:" + artifact + ":" + (version == null ? "" : version); } + boolean matches(final Bundle bundle) { + return bundle != null && bundle.getArtifact().contains(artifact) && (version == null || version.equals(bundle.getVersion())); + } + void assertMatches(final Bundle bundle, final String description) { assertNotNull(bundle, description); assertTrue(bundle.getArtifact().contains(artifact), description + " " + bundle.getArtifact()); @@ -228,7 +234,14 @@ protected void releaseFlowFiles(final int nodeIndex) throws IOException { * Lets the generator run and makes the terminator hold every FlowFile on every node. */ protected void holdFlowFiles() { - deleteFromNodeDirectories(GATE_FILE); + holdFlowFiles(GATE_FILE); + } + + /** + * Makes the terminator of every Connector whose Gate File Path is the given file hold every FlowFile on every node. + */ + protected void holdFlowFiles(final String gateFile) { + deleteFromNodeDirectories(gateFile); } private void writeToNodeDirectory(final int nodeIndex, final String fileName, final String contents) throws IOException { @@ -244,19 +257,38 @@ private void deleteFromNodeDirectories(final String fileName) { } } - protected void stopAndAssertNotPending(final String connectorId) throws IOException { - getNiFiInstance().stop(); + /** + * Waits until every node has saved the incoming bundle as the bundle that built the Connector's managed flow. + */ + protected void waitUntilUpgradedFlowSaved(final String connectorId) throws InterruptedException { + waitUntilManagedFlowBundleSaved(connectorId, incomingBundle()); + } + + protected void waitUntilPreUpgradeFlowSaved(final String connectorId) throws InterruptedException { + waitUntilManagedFlowBundleSaved(connectorId, outgoingBundle()); + } + + private void waitUntilManagedFlowBundleSaved(final String connectorId, final ExpectedBundle expected) throws InterruptedException { for (int nodeIndex = 1; nodeIndex <= nodeCount(); nodeIndex++) { - final VersionedConnector connector = FlowDefinitionFiles.readConnector(nodeInstance(nodeIndex), connectorId); - assertManagedFlowBundle(connector, incomingBundle()); + waitForPersistedConnector(nodeIndex, connectorId, connector -> expected.matches(connector.getManagedFlowBundle())); } } - protected void assertPersistedOutgoing(final String connectorId) throws IOException { - for (int nodeIndex = 1; nodeIndex <= nodeCount(); nodeIndex++) { + /** + * Reads the Connector from the node's flow.json.gz while NiFi runs, until the condition holds. Saves are asynchronous, and a read + * that overlaps a save fails and is retried. + * + * @return the first persisted Connector that satisfies the condition + */ + protected VersionedConnector waitForPersistedConnector(final int nodeIndex, final String connectorId, final Predicate condition) + throws InterruptedException { + final AtomicReference persisted = new AtomicReference<>(); + waitFor(() -> { final VersionedConnector connector = FlowDefinitionFiles.readConnector(nodeInstance(nodeIndex), connectorId); - assertManagedFlowBundle(connector, outgoingBundle()); - } + persisted.set(connector); + return condition.test(connector); + }); + return persisted.get(); } protected int nodeCount() { diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java index fb2196db7e2a..d08088e0b086 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorChangeVersionDrainIT.java @@ -18,7 +18,6 @@ import org.apache.nifi.components.connector.ConnectorState; import org.apache.nifi.components.connector.FlowEvolutionStatus; -import org.apache.nifi.tests.system.FlowDefinitionFiles; import org.apache.nifi.tests.system.NiFiInstanceFactory; import org.apache.nifi.toolkit.client.ConnectorClient; import org.apache.nifi.toolkit.client.NiFiClientException; @@ -173,7 +172,7 @@ public void testApplyFailureRetriesApplyWithoutRepeatingEvolutionPreparation() t // failed evolution treats a new start request as part of that evolution, so wait for every node to fail first. waitForNodeConnectorState(1, connectorId, ConnectorState.UPDATE_FAILED); waitForNodeConnectorState(2, connectorId, ConnectorState.UPDATE_FAILED); - assertManagedFlowBundle(FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId), outgoingBundle()); + waitForPersistedConnector(1, connectorId, connector -> outgoingBundle().matches(connector.getManagedFlowBundle())); // Node 2 already applied the upgraded flow, so the retry only applies it on node 1. Flow evolution preparation // already completed on both nodes, so the retry does not run it again. @@ -185,7 +184,7 @@ public void testApplyFailureRetriesApplyWithoutRepeatingEvolutionPreparation() t assertNodeFlowEvolutionStatus(1, connectorId, FlowEvolutionStatus.INACTIVE); assertNodeFlowEvolutionStatus(2, connectorId, FlowEvolutionStatus.INACTIVE); assertEquals("edited", findProcessor(connectorId, "GenerateFlowFile").getComponent().getConfig().getComments()); - stopAndAssertNotPending(connectorId); + waitUntilUpgradedFlowSaved(connectorId); } private T onNode(final int nodeIndex, final NodeCall call) throws Exception { diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java index 6e4f30c9c400..304e497a263a 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java @@ -16,56 +16,179 @@ */ package org.apache.nifi.tests.system.connectors; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.tests.system.InstanceConfiguration; import org.apache.nifi.tests.system.NiFiInstanceFactory; +import org.apache.nifi.tests.system.SpawnedClusterNiFiInstanceFactory; +import org.apache.nifi.util.NiFiProperties; +import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; +import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO; +import org.apache.nifi.web.api.dto.PropertyGroupConfigurationDTO; +import org.apache.nifi.web.api.entity.ConnectorEntity; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Verifies clustered startup after a Connector NAR swap. The pre-upgrade flow queues FlowFiles on the connection - * from the processor the upgrade removes to the terminator that stays, so the connector stays draining until that - * connection is empty. The processor before the removed one is replaced. + * Verifies clustered startup after a Connector NAR swap, with Connector configuration held by an external provider. */ public class ClusteredConnectorUpgradeDrainIT extends AbstractNarSwapUpgradeDrainIT { + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String UPGRADE_STEP = "Upgrade"; + private static final String COMMENT_PROPERTY = "Comment"; + private static final String LEGACY_NOTE = "Legacy Note"; + private static final String DRAIN_LABEL = "Drain Label"; + private static final String PROVIDER_EDITED_COMMENT = "edited-in-provider"; + + private final List providerStates = List.of(createProviderState(), createProviderState()); + + /** + * Each node gets its own provider state directory because the file-based provider writes through a fixed temporary file name. + */ @Override public NiFiInstanceFactory getInstanceFactory() { - return createTwoNodeInstanceFactory(); + return new SpawnedClusterNiFiInstanceFactory( + new InstanceConfiguration.Builder() + .bootstrapConfig("src/test/resources/conf/clustered/node1/bootstrap.conf") + .instanceDirectory("target/node1") + .overrideNifiProperties(providerProperties(providerStates.get(0))) + .build(), + new InstanceConfiguration.Builder() + .bootstrapConfig("src/test/resources/conf/clustered/node2/bootstrap.conf") + .instanceDirectory("target/node2") + .overrideNifiProperties(providerProperties(providerStates.get(1))) + .build()); } + /** + * Swaps the Connector NARs with two Connectors. The running Connector queues FlowFiles on the connection from the processor + * the upgrade removes to the terminator that stays, so it resumes draining until that connection is empty. The stopped + * Connector stays pending with the configuration the provider supplied while NiFi was down. + */ @Test - @Timeout(240) - public void testRunningConnectorAutoResumes() throws Exception { - final Map properties = properties("DRAIN", true, null); - properties.put(REMOVED_PROCESSOR_CHAIN, "true"); - final String connectorId = createOutgoingConnector(properties); + @Timeout(300) + public void testNarSwapResumesRunningConnectorAndAppliesProviderConfiguration() throws Exception { + final Map runningProperties = properties("DRAIN", true, null); + runningProperties.put(REMOVED_PROCESSOR_CHAIN, "true"); + final String runningConnectorId = createOutgoingConnector(runningProperties); holdFlowFiles(); - getClientUtil().startConnector(connectorId); - waitForConnectionMinQueueCount(connectorId, REMOVED_CONNECTION, 1); + getClientUtil().startConnector(runningConnectorId); + waitForConnectionMinQueueCount(runningConnectorId, REMOVED_CONNECTION, 1); + + final Map providedProperties = properties("DRAIN", true, "shared"); + providedProperties.put(LEGACY_NOTE, "v1-only"); + final String providedConnectorId = createOutgoingConnector(providedProperties); + getNiFiInstance().stop(); + editWorkingCommentInProvider(providedConnectorId); switchOutNars(); getNiFiInstance().start(true); waitForCluster(); - getClientUtil().waitForConnectorState(connectorId, ConnectorState.DRAINING); - assertNotNull(findProcessor(connectorId, RELAY_PROCESSOR)); - assertNotNull(findProcessor(connectorId, REMOVED_PROCESSOR)); - assertNotNull(findProcessor(connectorId, "TerminateFlowFile")); - assertTrue(getConnectionQueuedCount(connectorId, REMOVED_CONNECTION) > 0); + getClientUtil().waitForConnectorState(runningConnectorId, ConnectorState.DRAINING); + assertNotNull(findProcessor(runningConnectorId, RELAY_PROCESSOR)); + assertNotNull(findProcessor(runningConnectorId, REMOVED_PROCESSOR)); + assertNotNull(findProcessor(runningConnectorId, "TerminateFlowFile")); + assertTrue(getConnectionQueuedCount(runningConnectorId, REMOVED_CONNECTION) > 0); + + assertConnectorState(providedConnectorId, ConnectorState.STOPPED); + assertPending(providedConnectorId); + final ConnectorEntity pending = getNifiClient().getConnectorClient().getConnector(providedConnectorId); + assertEquals("shared", configurationValue(pending.getComponent().getActiveConfiguration(), COMMENT_PROPERTY)); + assertEquals(PROVIDER_EDITED_COMMENT, configurationValue(pending.getComponent().getWorkingConfiguration(), COMMENT_PROPERTY)); + assertNull(configurationValue(pending.getComponent().getActiveConfiguration(), LEGACY_NOTE)); + assertNull(configurationValue(pending.getComponent().getWorkingConfiguration(), LEGACY_NOTE)); + assertEquals("upgraded", configurationValue(pending.getComponent().getActiveConfiguration(), DRAIN_LABEL)); + assertEquals("upgraded", configurationValue(pending.getComponent().getWorkingConfiguration(), DRAIN_LABEL)); releaseFlowFiles(); - getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); - assertNull(findProcessor(connectorId, RELAY_PROCESSOR)); - assertNull(findProcessor(connectorId, REMOVED_PROCESSOR)); - assertNotNull(findProcessor(connectorId, SWAPPED_PROCESSOR)); - assertNotNull(findProcessor(connectorId, "TerminateFlowFile")); - assertNull(findConnection(connectorId, REMOVED_CONNECTION)); - stopAndAssertNotPending(connectorId); + getClientUtil().waitForConnectorState(runningConnectorId, ConnectorState.RUNNING); + assertNull(findProcessor(runningConnectorId, RELAY_PROCESSOR)); + assertNull(findProcessor(runningConnectorId, REMOVED_PROCESSOR)); + assertNotNull(findProcessor(runningConnectorId, SWAPPED_PROCESSOR)); + assertNotNull(findProcessor(runningConnectorId, "TerminateFlowFile")); + assertNull(findConnection(runningConnectorId, REMOVED_CONNECTION)); + + requestStart(providedConnectorId); + getClientUtil().waitForConnectorState(providedConnectorId, ConnectorState.RUNNING); + assertEquals(PROVIDER_EDITED_COMMENT, findProcessor(providedConnectorId, "GenerateFlowFile").getComponent().getConfig().getComments()); + + waitUntilUpgradedFlowSaved(runningConnectorId); + waitUntilUpgradedFlowSaved(providedConnectorId); + } + + /** + * Simulates an out-of-band edit while NiFi is stopped: sets the Comment property of the Upgrade step in the working + * configuration that each node's file-based provider stores. The active configuration is left unchanged. + */ + private void editWorkingCommentInProvider(final String connectorId) throws IOException { + for (final Path providerState : providerStates) { + setWorkingCommentProperty(providerState.resolve(connectorId).resolve("live-config.json")); + } + } + + private void setWorkingCommentProperty(final Path liveConfiguration) throws IOException { + final ObjectNode configuration = (ObjectNode) OBJECT_MAPPER.readTree(liveConfiguration.toFile()); + final JsonNode steps = configuration.get("workingFlowConfiguration"); + assertNotNull(steps, "Provider configuration has no working flow configuration"); + for (final JsonNode step : steps) { + if (!UPGRADE_STEP.equals(step.path("name").asText()) || !(step.path("properties").get(COMMENT_PROPERTY) instanceof final ObjectNode property)) { + continue; + } + + property.put("value", PROVIDER_EDITED_COMMENT); + OBJECT_MAPPER.writeValue(liveConfiguration.toFile(), configuration); + return; + } + + throw new AssertionError("Provider working configuration has no " + COMMENT_PROPERTY + " property in the " + UPGRADE_STEP + " step"); + } + + private static String configurationValue(final ConnectorConfigurationDTO configuration, final String propertyName) { + if (configuration == null || configuration.getConfigurationStepConfigurations() == null) { + return null; + } + + for (final ConfigurationStepConfigurationDTO step : configuration.getConfigurationStepConfigurations()) { + if (!UPGRADE_STEP.equals(step.getConfigurationStepName()) || step.getPropertyGroupConfigurations() == null) { + continue; + } + + for (final PropertyGroupConfigurationDTO group : step.getPropertyGroupConfigurations()) { + if (group.getPropertyValues() != null && group.getPropertyValues().containsKey(propertyName)) { + return group.getPropertyValues().get(propertyName).getValue(); + } + } + } + + return null; + } + + private static Map providerProperties(final Path providerState) { + return Map.of( + NiFiProperties.CONNECTOR_CONFIGURATION_PROVIDER_IMPLEMENTATION, "org.apache.nifi.connectors.tests.system.FileConnectorConfigurationProvider", + NiFiProperties.CONNECTOR_CONFIGURATION_PROVIDER_PROPERTIES_PREFIX + "state.directory", providerState.toAbsolutePath().toString()); + } + + private static Path createProviderState() { + try { + return Files.createTempDirectory("file-connector-provider"); + } catch (final IOException e) { + throw new IllegalStateException("Unable to create the provider state directory", e); + } } } diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java index c3ee2acd3243..e8e182632684 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorChangeVersionDrainIT.java @@ -23,7 +23,6 @@ import org.apache.nifi.flow.VersionedConnectorValueReference; import org.apache.nifi.flow.VersionedParameter; import org.apache.nifi.security.encryption.PropertyEncryptionEncoder; -import org.apache.nifi.tests.system.FlowDefinitionFiles; import org.apache.nifi.toolkit.client.NiFiClientException; import org.apache.nifi.web.api.dto.ConnectorValueReferenceDTO; import org.apache.nifi.web.api.dto.StateEntryDTO; @@ -58,79 +57,108 @@ public class ConnectorChangeVersionDrainIT extends AbstractChangeVersionDrainIT private static final String GENERATOR = "GenerateFlowFile"; private static final String CANCELLED_EVOLUTION = "Flow evolution was cancelled"; private static final String REWIRED_ENDPOINT = "Rewired Endpoint"; + private static final String DRAINING_GATE_FILE = "upgrade-drain-gate-draining.txt"; + /** + * Restarts NiFi once with four Connectors whose upgrade is pending: one whose pre-upgrade parameter secret was rotated, one + * with working edits and queued FlowFiles, one in Troubleshooting, and one draining with its own gate file. + */ @Test - @Timeout(360) - public void testPreUpgradeParameterSecretIsRefreshedAndCanBeRestored() throws Exception { + @Timeout(480) + public void testRestartKeepsPendingUpgrades() throws Exception { final SecretConnector secretConnector = createSecretConnector("original-secret"); - changeVersion(secretConnector.connectorId(), DRAIN_V2); + final String secretConnectorId = secretConnector.connectorId(); + changeVersion(secretConnectorId, DRAIN_V2); getClientUtil().updateParameterProviderProperties(secretConnector.parameterProvider(), Map.of("parameters", SECRET_NAME + "=rotated-secret")); + assertSecretPersistedAsReference(waitForPersistedConnector(1, secretConnectorId, connector -> incomingBundle().matches(connector.getBundle()))); + + final String editedConnectorId = queueStoppedUpgrade("INHERITED_DRAIN", true, "original"); + final String editedConnectionId = findConnection(editedConnectorId, REMOVED_CONNECTION).getId(); + final int editedQueued = getConnectorQueuedFlowFileCount(editedConnectorId); + final long editedGenerated = generatorCount(editedConnectorId); + assertQueueMatchesCount(editedConnectorId); + triggerUpgrade(editedConnectorId); + assertConnectorState(editedConnectorId, ConnectorState.STOPPED); + assertEquals(editedConnectionId, findConnection(editedConnectorId, REMOVED_CONNECTION).getId()); + assertEquals(editedQueued, getConnectorQueuedFlowFileCount(editedConnectorId)); + assertPending(editedConnectorId); + getClientUtil().configureConnector(editedConnectorId, "Upgrade", properties("DRAIN", true, "working-edit")); + assertPending(editedConnectorId); + final VersionedConnector editedPersisted = waitForPersistedConnector(1, editedConnectorId, connector -> incomingBundle().matches(connector.getBundle())); + assertManagedFlowBundle(editedPersisted, outgoingBundle()); + assertNotNull(findProcessor(editedPersisted.getManagedProcessGroup(), "TerminateFlowFile")); + + final String troubleshootingConnectorId = queueStoppedUpgrade("NO_OP", false, null); + final int troubleshootingQueued = getConnectorQueuedFlowFileCount(troubleshootingConnectorId); + changeVersion(troubleshootingConnectorId, DRAIN_V2); + getClientUtil().enterTroubleshooting(troubleshootingConnectorId); + final ConnectorEntity troubleshootingConnector = getNifiClient().getConnectorClient().getConnector(troubleshootingConnectorId); + final NiFiClientException endTroubleshootingFailure = assertThrows(NiFiClientException.class, () -> getNifiClient().getConnectorClient() + .endTroubleshooting(troubleshootingConnectorId, troubleshootingConnector.getRevision().getClientId(), troubleshootingConnector.getRevision().getVersion())); + assertTrue(endTroubleshootingFailure.getMessage().contains(troubleshootingQueued + " FlowFiles"), endTroubleshootingFailure.getMessage()); + assertTrue(endTroubleshootingFailure.getMessage().contains("upgrade is pending"), endTroubleshootingFailure.getMessage()); + assertConnectorState(troubleshootingConnectorId, ConnectorState.TROUBLESHOOTING); + waitUntilPreUpgradeFlowSaved(troubleshootingConnectorId); + + final Map drainingProperties = properties("DRAIN", true, null); + drainingProperties.put("Gate File Path", DRAINING_GATE_FILE); + holdFlowFiles(DRAINING_GATE_FILE); + final String drainingConnectorId = queueAtLeastOneFlowFileAndStop(createOutgoingConnector(drainingProperties)); + triggerUpgrade(drainingConnectorId); + requestStart(drainingConnectorId); + waitUntilDraining(drainingConnectorId); + final int drainingQueued = getConnectorQueuedFlowFileCount(drainingConnectorId); + final long drainingGenerated = generatorCount(drainingConnectorId); + // The start that begins an evolution is saved, so the restarted node resumes the upgrade. + waitForPersistedConnector(1, drainingConnectorId, connector -> connector.getScheduledState() == VersionedConnectorState.RUNNING); - getNiFiInstance().stop(); - assertSecretPersistedAsReference(FlowDefinitionFiles.readConnector(nodeInstance(1), secretConnector.connectorId())); - getNiFiInstance().start(true); - waitForCluster(); - - requestStart(secretConnector.connectorId()); - getClientUtil().waitForConnectorState(secretConnector.connectorId(), ConnectorState.RUNNING); - stopAndAssertNotPending(secretConnector.connectorId()); - } - - @Test - @Timeout(360) - public void testPendingUpgradeEditsThenStartsWithoutReEvolving() throws Exception { - final String connectorId = queueStoppedUpgrade("INHERITED_DRAIN", true, "original"); - final String connectionId = findConnection(connectorId, REMOVED_CONNECTION).getId(); - final int queued = getConnectorQueuedFlowFileCount(connectorId); - final long generated = generatorCount(connectorId); - assertQueueMatchesCount(connectorId); - triggerUpgrade(connectorId); - - assertConnectorState(connectorId, ConnectorState.STOPPED); - assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); - assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); - assertPending(connectorId); - - getClientUtil().configureConnector(connectorId, "Upgrade", properties("DRAIN", true, "working-edit")); - assertPending(connectorId); - getNiFiInstance().stop(); - final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); - assertLoadedBundle(persisted, incomingBundle()); - assertManagedFlowBundle(persisted, outgoingBundle()); - assertNotNull(findProcessor(persisted.getManagedProcessGroup(), "TerminateFlowFile")); - getNiFiInstance().start(true); - waitForCluster(); - - assertEquals(generated, generatorCount(connectorId)); - assertQueueMatchesCount(connectorId); + restartKeepingIncomingVersion(); + assertConnectorState(troubleshootingConnectorId, ConnectorState.TROUBLESHOOTING); + assertFlowEvolutionStatus(troubleshootingConnectorId, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING); + assertEquals(troubleshootingQueued, getConnectorQueuedFlowFileCount(troubleshootingConnectorId)); + + getClientUtil().waitForConnectorState(drainingConnectorId, ConnectorState.DRAINING); + getClientUtil().cancelDrain(drainingConnectorId); + getClientUtil().waitForConnectorStopped(drainingConnectorId); + assertEquals(drainingQueued, getConnectorQueuedFlowFileCount(drainingConnectorId)); + assertEquals(drainingGenerated, generatorCount(drainingConnectorId)); + assertQueueMatchesCount(drainingConnectorId); + assertNotNull(findConnection(drainingConnectorId, REMOVED_CONNECTION)); + assertPending(drainingConnectorId); + final VersionedConnector drainingPersisted = waitForPersistedConnector(1, drainingConnectorId, + connector -> connector.getScheduledState() == VersionedConnectorState.ENABLED); + assertLoadedBundle(drainingPersisted, incomingBundle()); + assertManagedFlowBundle(drainingPersisted, outgoingBundle()); + + requestStart(secretConnectorId); + getClientUtil().waitForConnectorState(secretConnectorId, ConnectorState.RUNNING); + waitUntilUpgradedFlowSaved(secretConnectorId); + + assertEquals(editedGenerated, generatorCount(editedConnectorId)); + assertQueueMatchesCount(editedConnectorId); // Releasing FlowFiles stops the generator, so its count must not move while the pre-upgrade flow drains and evolves. releaseFlowFiles(); - requestStart(connectorId); - getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); - assertNull(findConnection(connectorId, REMOVED_CONNECTION)); - assertEquals("working-edit", findProcessor(connectorId, GENERATOR).getComponent().getConfig().getComments()); - assertTrue(findProcessor(connectorId, GENERATOR).getComponent().getBundle().getArtifact().contains("nifi-system-test-extensions2")); - assertEquals(generated, generatorCount(connectorId)); - - getNiFiInstance().stop(); - final VersionedConnector evolved = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); - assertManagedFlowBundle(evolved, incomingBundle()); + requestStart(editedConnectorId); + getClientUtil().waitForConnectorState(editedConnectorId, ConnectorState.RUNNING); + assertNull(findConnection(editedConnectorId, REMOVED_CONNECTION)); + assertEquals("working-edit", findProcessor(editedConnectorId, GENERATOR).getComponent().getConfig().getComments()); + assertTrue(findProcessor(editedConnectorId, GENERATOR).getComponent().getBundle().getArtifact().contains("nifi-system-test-extensions2")); + assertEquals(editedGenerated, generatorCount(editedConnectorId)); + assertFlowEvolutionStatus(editedConnectorId, FlowEvolutionStatus.INACTIVE); + + final VersionedConnector evolved = waitForPersistedConnector(1, editedConnectorId, connector -> incomingBundle().matches(connector.getManagedFlowBundle())); assertEquals(VersionedConnectorState.RUNNING, evolved.getScheduledState()); assertEquals("working-edit", configurationProperty(evolved.getActiveFlowConfiguration(), "Comment")); assertEquals("working-edit", configurationProperty(evolved.getWorkingFlowConfiguration(), "Comment")); - assertEquals("working-edit", findProcessor(evolved.getManagedProcessGroup(), "GenerateFlowFile").getComments()); - assertTrue(findProcessor(evolved.getManagedProcessGroup(), "GenerateFlowFile").getBundle().getArtifact().contains("nifi-system-test-extensions2")); - getNiFiInstance().start(true); - waitForCluster(); - getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); - assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.INACTIVE); - - getClientUtil().stopConnector(connectorId); - getClientUtil().configureConnector(connectorId, "Upgrade", properties("DRAIN", true, "after-evolution")); - getClientUtil().applyConnectorUpdate(getNifiClient().getConnectorClient().getConnector(connectorId)); - getClientUtil().waitForValidConnector(connectorId); - assertEquals("after-evolution", findProcessor(connectorId, "GenerateFlowFile").getComponent().getConfig().getComments()); + assertEquals("working-edit", findProcessor(evolved.getManagedProcessGroup(), GENERATOR).getComments()); + assertTrue(findProcessor(evolved.getManagedProcessGroup(), GENERATOR).getBundle().getArtifact().contains("nifi-system-test-extensions2")); + + getClientUtil().stopConnector(editedConnectorId); + getClientUtil().configureConnector(editedConnectorId, "Upgrade", properties("DRAIN", true, "after-evolution")); + getClientUtil().applyConnectorUpdate(getNifiClient().getConnectorClient().getConnector(editedConnectorId)); + getClientUtil().waitForValidConnector(editedConnectorId); + assertEquals("after-evolution", findProcessor(editedConnectorId, GENERATOR).getComponent().getConfig().getComments()); } @Test @@ -156,41 +184,7 @@ public void testPendingUpgradeClearsWhenBundleMatchesManagedFlow() throws Except getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); assertNotNull(findConnection(connectorId, REMOVED_CONNECTION)); - getNiFiInstance().stop(); - final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); - assertLoadedBundle(persisted, outgoingBundle()); - assertManagedFlowBundle(persisted, outgoingBundle()); - } - - @Test - @Timeout(240) - public void testRestartDuringDrainingComesBackPending() throws Exception { - final String connectorId = queueStoppedUpgrade("DRAIN", true, null); - triggerUpgrade(connectorId); - holdFlowFiles(); - assertTrue(getConnectorQueuedFlowFileCount(connectorId) > 0); - requestStart(connectorId); - waitUntilDraining(connectorId); - final int queued = getConnectorQueuedFlowFileCount(connectorId); - final long generated = generatorCount(connectorId); - - // An evolution in progress keeps the Connector's desired state RUNNING, so the restarted node resumes it. - getNiFiInstance().stop(); - assertEquals(VersionedConnectorState.RUNNING, FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId).getScheduledState()); - getNiFiInstance().start(true); - waitForCluster(); - - getClientUtil().cancelDrain(connectorId); - getClientUtil().waitForConnectorStopped(connectorId); - assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); - assertEquals(generated, generatorCount(connectorId)); - assertQueueMatchesCount(connectorId); - assertNotNull(findConnection(connectorId, REMOVED_CONNECTION)); - assertPending(connectorId); - getNiFiInstance().stop(); - final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); - assertEquals(VersionedConnectorState.ENABLED, persisted.getScheduledState()); - assertLoadedBundle(persisted, incomingBundle()); + final VersionedConnector persisted = waitForPersistedConnector(1, connectorId, connector -> outgoingBundle().matches(connector.getBundle())); assertManagedFlowBundle(persisted, outgoingBundle()); } @@ -211,9 +205,7 @@ public void testUpdatingPreUpgradeFlowDuringPreparationFailsEvolution() throws E assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); assertEquals(generated, generatorCount(connectorId)); - getNiFiInstance().stop(); - final VersionedConnector persisted = FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId); - assertLoadedBundle(persisted, incomingBundle()); + final VersionedConnector persisted = waitForPersistedConnector(1, connectorId, connector -> incomingBundle().matches(connector.getBundle())); assertManagedFlowBundle(persisted, outgoingBundle()); } @@ -241,7 +233,7 @@ public void testInvalidEvolutionResultLeavesUpgradePendingUntilValid() throws Ex assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); assertEquals(generated, generatorCount(connectorId)); - assertPersistedOutgoing(connectorId); + waitUntilPreUpgradeFlowSaved(connectorId); } // The upgraded flow keeps the queued connection. FlowFiles are still held, so the generator keeps running and its @@ -255,7 +247,7 @@ public void testInvalidEvolutionResultLeavesUpgradePendingUntilValid() throws Ex assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); assertQueueMatchesCount(connectorId); assertTrue(generatorCount(connectorId) >= generated); - stopAndAssertNotPending(connectorId); + waitUntilUpgradedFlowSaved(connectorId); } @Test @@ -277,14 +269,14 @@ public void testMovingSourceOfQueuedConnectionFailsEvolutionUntilQueueIsEmpty() assertEquals(connectionId, findConnection(connectorId, REMOVED_CONNECTION).getId()); assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); assertEquals(generated, generatorCount(connectorId)); - assertPersistedOutgoing(connectorId); + waitUntilPreUpgradeFlowSaved(connectorId); getClientUtil().purgeConnectorFlowFiles(connectorId); getClientUtil().waitForConnectorStopped(connectorId); requestStart(connectorId); getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); assertEquals(RELAY_PROCESSOR, findConnection(connectorId, REMOVED_CONNECTION).getComponent().getSource().getName()); - stopAndAssertNotPending(connectorId); + waitUntilUpgradedFlowSaved(connectorId); } @Test @@ -311,7 +303,7 @@ public void testMovingDestinationOfQueuedConnectionKeepsQueuedFlowFiles() throws final long generatedAfterUpgrade = generatorCount(connectorId); assertTrue(generatedAfterUpgrade >= generated); assertEquals(generatedAfterUpgrade, getConnectorQueuedFlowFileCount(connectorId)); - stopAndAssertNotPending(connectorId); + waitUntilUpgradedFlowSaved(connectorId); } @Test @@ -346,7 +338,7 @@ public void testStopDuringEvolutionDrainFailsEvolution() throws Exception { assertStoppedPending(connectorId, CANCELLED_EVOLUTION); assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.FAILED); assertNotNull(findConnection(connectorId, REMOVED_CONNECTION)); - assertPersistedOutgoing(connectorId); + waitUntilPreUpgradeFlowSaved(connectorId); } @Test @@ -365,29 +357,7 @@ public void testEndingTroubleshootingAfterFailedApplyCompletesUpgrade() throws E assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.INACTIVE); getClientUtil().applyConnectorUpdate(getNifiClient().getConnectorClient().getConnector(connectorId)); getClientUtil().waitForValidConnector(connectorId); - stopAndAssertNotPending(connectorId); - } - - @Test - @Timeout(240) - public void testPendingUpgradeBlocksEndingTroubleshootingWithQueuedFlowFiles() throws Exception { - final String connectorId = queueStoppedUpgrade("NO_OP", false, null); - final int queued = getConnectorQueuedFlowFileCount(connectorId); - changeVersion(connectorId, DRAIN_V2); - getClientUtil().enterTroubleshooting(connectorId); - - final ConnectorEntity connector = getNifiClient().getConnectorClient().getConnector(connectorId); - final NiFiClientException failure = assertThrows(NiFiClientException.class, () -> getNifiClient().getConnectorClient() - .endTroubleshooting(connectorId, connector.getRevision().getClientId(), connector.getRevision().getVersion())); - assertTrue(failure.getMessage().contains(queued + " FlowFiles"), failure.getMessage()); - assertTrue(failure.getMessage().contains("upgrade is pending"), failure.getMessage()); - assertConnectorState(connectorId, ConnectorState.TROUBLESHOOTING); - assertPersistedOutgoing(connectorId); - - restartKeepingIncomingVersion(); - assertConnectorState(connectorId, ConnectorState.TROUBLESHOOTING); - assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.EVOLVE_DRAIN_PENDING); - assertEquals(queued, getConnectorQueuedFlowFileCount(connectorId)); + waitUntilUpgradedFlowSaved(connectorId); } @Test @@ -406,9 +376,7 @@ public void testSecondUpgradeAfterCompletedUpgrade() throws Exception { requestStart(connectorId); getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); assertFlowEvolutionStatus(connectorId, FlowEvolutionStatus.INACTIVE); - - getNiFiInstance().stop(); - assertManagedFlowBundle(FlowDefinitionFiles.readConnector(nodeInstance(1), connectorId), outgoingBundle()); + waitUntilPreUpgradeFlowSaved(connectorId); } /** diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java index b4113a39c670..40b46eeacb0d 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorParameterContextIT.java @@ -17,7 +17,6 @@ package org.apache.nifi.tests.system.connectors; -import org.apache.nifi.components.connector.ConnectorState; import org.apache.nifi.tests.system.NiFiSystemIT; import org.apache.nifi.toolkit.client.ConnectorClient; import org.apache.nifi.toolkit.client.NiFiClientException; @@ -109,20 +108,6 @@ public void testParameterContextInheritanceWithSensitiveAndAssetParameters() thr assertEquals(SENSITIVE_SECRET_VALUE, sensitiveContent, "Sensitive output file should contain the secret value"); assertEquals(ASSET_FILE_CONTENT, assetContent, "Asset output file should contain the asset file contents"); - - // A same-bundle restart resumes the Connector with its sensitive and asset parameters still resolved - getNiFiInstance().stop(); - assertTrue(sensitiveOutputFile.delete()); - assertTrue(assetOutputFile.delete()); - getNiFiInstance().start(); - if (getNumberOfNodes() > 1) { - waitForAllNodesConnected(); - } - - getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); - waitFor(() -> sensitiveOutputFile.exists() && assetOutputFile.exists()); - assertEquals(SENSITIVE_SECRET_VALUE, Files.readString(sensitiveOutputFile.toPath()).trim()); - assertEquals(ASSET_FILE_CONTENT, Files.readString(assetOutputFile.toPath()).trim()); } private ConnectorValueReferenceDTO createStringLiteralRef(final String value) { diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java deleted file mode 100644 index 721411035bd0..000000000000 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorUpgradeDrainProviderIT.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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.connectors; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.nifi.components.connector.ConnectorState; -import org.apache.nifi.util.NiFiProperties; -import org.apache.nifi.web.api.dto.ConfigurationStepConfigurationDTO; -import org.apache.nifi.web.api.dto.ConnectorConfigurationDTO; -import org.apache.nifi.web.api.dto.PropertyGroupConfigurationDTO; -import org.apache.nifi.web.api.entity.ConnectorEntity; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * A NAR-swap upgrade applies configuration supplied by the external provider. - */ -public class ConnectorUpgradeDrainProviderIT extends AbstractNarSwapUpgradeDrainIT { - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - private static final String COMMENT = "Comment"; - private static final String LEGACY_NOTE = "Legacy Note"; - private static final String DRAIN_LABEL = "Drain Label"; - private static final String SUPPLIED_COMMENT = "supplied-by-provider"; - - private final Path providerState = createProviderState(); - - @Override - protected Map getNifiPropertiesOverrides() { - return Map.of(NiFiProperties.CONNECTOR_CONFIGURATION_PROVIDER_IMPLEMENTATION, "org.apache.nifi.connectors.tests.system.FileConnectorConfigurationProvider", NiFiProperties - .CONNECTOR_CONFIGURATION_PROVIDER_PROPERTIES_PREFIX + "state.directory", providerState.toAbsolutePath().toString()); - } - - @Test - @Timeout(240) - public void testProviderSuppliedConfigurationIsAppliedByUpgrade() throws Exception { - final Map initial = properties("DRAIN", true, "shared"); - initial.put(LEGACY_NOTE, "v1-only"); - final String connectorId = createConnector("UpgradeDrainConnector", initial); - - getNiFiInstance().stop(); - supplyComment(connectorId, SUPPLIED_COMMENT); - switchOutNars(); - getNiFiInstance().start(true); - waitForCluster(); - - assertConnectorState(connectorId, ConnectorState.STOPPED); - assertPending(connectorId); - final ConnectorEntity pending = getNifiClient().getConnectorClient().getConnector(connectorId); - assertEquals("shared", configurationValue(pending.getComponent().getActiveConfiguration(), COMMENT)); - assertEquals(SUPPLIED_COMMENT, configurationValue(pending.getComponent().getWorkingConfiguration(), COMMENT)); - assertNull(configurationValue(pending.getComponent().getActiveConfiguration(), LEGACY_NOTE)); - assertNull(configurationValue(pending.getComponent().getWorkingConfiguration(), LEGACY_NOTE)); - assertEquals("upgraded", configurationValue(pending.getComponent().getActiveConfiguration(), DRAIN_LABEL)); - assertEquals("upgraded", configurationValue(pending.getComponent().getWorkingConfiguration(), DRAIN_LABEL)); - - releaseFlowFiles(); - requestStart(connectorId); - getClientUtil().waitForConnectorState(connectorId, ConnectorState.RUNNING); - assertEquals(SUPPLIED_COMMENT, findProcessor(connectorId, "GenerateFlowFile").getComponent().getConfig().getComments()); - } - - private void supplyComment(final String connectorId, final String comment) throws IOException { - final Path liveConfiguration = providerState.resolve(connectorId).resolve("live-config.json"); - final ObjectNode configuration = (ObjectNode) OBJECT_MAPPER.readTree(liveConfiguration.toFile()); - final JsonNode steps = configuration.get("workingFlowConfiguration"); - assertNotNull(steps, "Provider configuration has no working flow configuration"); - boolean updated = false; - for (final JsonNode step : steps) { - final ObjectNode properties = step.get("properties") instanceof ObjectNode objectNode ? objectNode : null; - final ObjectNode property = properties == null || !(properties.get(COMMENT) instanceof ObjectNode) ? null : (ObjectNode) properties.get(COMMENT); - if (property != null) { - property.put("value", comment); - updated = true; - } - } - if (!updated) { - throw new AssertionError("Provider configuration has no " + COMMENT + " property"); - } - OBJECT_MAPPER.writeValue(liveConfiguration.toFile(), configuration); - } - - private static String configurationValue(final ConnectorConfigurationDTO configuration, final String propertyName) { - if (configuration == null || configuration.getConfigurationStepConfigurations() == null) { - return null; - } - for (final ConfigurationStepConfigurationDTO step : configuration.getConfigurationStepConfigurations()) { - if (!"Upgrade".equals(step.getConfigurationStepName()) || step.getPropertyGroupConfigurations() == null) { - continue; - } - for (final PropertyGroupConfigurationDTO group : step.getPropertyGroupConfigurations()) { - if (group.getPropertyValues() != null && group.getPropertyValues().containsKey(propertyName)) { - return group.getPropertyValues().get(propertyName).getValue(); - } - } - } - return null; - } - - private static Path createProviderState() { - try { - return Files.createTempDirectory("file-connector-provider"); - } catch (final IOException e) { - throw new IllegalStateException("Unable to create the provider state directory", e); - } - } -} From 4901e516579b426c6aa8767f8675c3ae17a1285d Mon Sep 17 00:00:00 2001 From: Bob Paulin Date: Wed, 18 Nov 2026 17:37:53 -0600 Subject: [PATCH 3/5] NIFI-16477: Address further review feedback on Connector flow evolution - Remove the flow evolution drain timeout; log a WARN every 10 minutes with the queued FlowFile count - Report an unreachable secrets provider separately from a missing secret - Make mapConnectorState exhaustive using ConnectorNode#getPreUpdateDesiredState - Fold AbstractNarSwapUpgradeDrainIT into ClusteredConnectorUpgradeDrainIT --- .../org/apache/nifi/util/NiFiProperties.java | 2 - .../main/asciidoc/administration-guide.adoc | 10 ---- .../src/main/asciidoc/developer-guide.adoc | 4 +- .../mapping/VersionedComponentFlowMapper.java | 15 +++-- .../TestVersionedComponentFlowMapper.java | 58 +++++++++++++++++++ .../components/connector/ConnectorNode.java | 6 ++ ...nectorRepositoryInitializationContext.java | 9 --- .../connector/ConnectorFlowEvolution.java | 26 ++++++--- .../connector/ParameterSecretReferences.java | 35 ++++++----- .../connector/StandardConnectorNode.java | 7 +++ ...ardConnectorRepoInitializationContext.java | 10 +--- .../StandardConnectorRepository.java | 29 +++++----- .../nifi/controller/FlowController.java | 5 +- .../TestParameterSecretReferences.java | 1 + .../connector/TestStandardConnectorNode.java | 13 +++++ .../TestStandardConnectorRepository.java | 21 ------- .../nifi-framework/nifi-resources/pom.xml | 1 - .../src/main/resources/conf/nifi.properties | 3 - .../AbstractChangeVersionDrainIT.java | 4 +- .../AbstractConnectorUpgradeDrainIT.java | 9 +-- .../AbstractNarSwapUpgradeDrainIT.java | 56 ------------------ .../ClusteredConnectorUpgradeDrainIT.java | 19 +++++- 22 files changed, 172 insertions(+), 171 deletions(-) delete mode 100644 nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java diff --git a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java index a6465052f475..12a3f01ed691 100644 --- a/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java +++ b/nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/NiFiProperties.java @@ -148,8 +148,6 @@ public class NiFiProperties extends ApplicationProperties { public static final String CONNECTOR_REPOSITORY_IMPLEMENTATION = "nifi.connector.repository.implementation"; public static final String CONNECTOR_SYNC_TIMEOUT = "nifi.connector.sync.timeout"; public static final String DEFAULT_CONNECTOR_SYNC_TIMEOUT = "5 mins"; - public static final String CONNECTOR_FLOW_EVOLUTION_TIMEOUT = "nifi.connector.flow.evolution.timeout"; - public static final String DEFAULT_CONNECTOR_FLOW_EVOLUTION_TIMEOUT = "30 mins"; // Connector Configuration Provider properties public static final String CONNECTOR_CONFIGURATION_PROVIDER_IMPLEMENTATION = "nifi.connector.configuration.provider.implementation"; diff --git a/nifi-docs/src/main/asciidoc/administration-guide.adoc b/nifi-docs/src/main/asciidoc/administration-guide.adoc index ad5fc98bf29b..936a6d8fe36d 100644 --- a/nifi-docs/src/main/asciidoc/administration-guide.adoc +++ b/nifi-docs/src/main/asciidoc/administration-guide.adoc @@ -3921,16 +3921,6 @@ The NiFi Registry NAR provider retrieves NARs from a NiFi Registry instance. In |`nifi.nar.library.provider.nifi-registry.url`| The URL of the NiFi Registry instance, such as `http://localhost:18080`. If the URL begins with `https`, then the NiFi keystore and truststore will be used to make the TLS connection. |==== -[[connector_properties]] -=== Connector Properties - -These properties configure how NiFi manages Connectors. For what flow evolution is and how it runs, see <> in the Developer's Guide. - -|==== -|*Property*|*Description* -|`nifi.connector.flow.evolution.timeout`|How long a Connector may spend draining its outgoing flow in `prepareForFlowEvolution`. Each cluster node applies this timeout to its own drain. A node that finishes first waits for the others, and that wait ends as soon as any node fails, times out, or disconnects. Accepts any NiFi time duration value such as `30 mins`. The default value is `30 mins`. A timeout leaves the Connector stopped and still pending. -|==== - [[secrets_manager_properties]] === Secrets Manager Properties diff --git a/nifi-docs/src/main/asciidoc/developer-guide.adoc b/nifi-docs/src/main/asciidoc/developer-guide.adoc index 4ba4081653b8..082e6dddea54 100644 --- a/nifi-docs/src/main/asciidoc/developer-guide.adoc +++ b/nifi-docs/src/main/asciidoc/developer-guide.adoc @@ -2733,7 +2733,7 @@ The default implementation of `prepareForFlowEvolution` does nothing and returns * If any connection that the upgraded flow removes still holds FlowFiles, the Connector must drain. The hook must finish with every such connection empty, or the upgrade fails. * The Connector does not need to drain when every connection that the upgraded flow removes is already empty. A connection that the upgraded flow keeps, with the same identifier, is updated in place and keeps its queue, so it never requires a drain. * The framework stops the outgoing processors only after the hook's future completes. The hook can start them so that queues empty, and the processors are stopped afterward. -* The framework can cancel the future, for example when the Connector is stopped or the evolution timeout is reached. Stop any work promptly when the future is cancelled. The framework does not wait for code that ignores cancellation. +* The framework can cancel the future, for example when the Connector is stopped or its drain is cancelled. Stop any work promptly when the future is cancelled. The framework does not wait for code that ignores cancellation. [[connector_applying_upgraded_flow]] === Applying the upgraded flow @@ -2746,7 +2746,7 @@ Each node prepares on its own. Every node has already finished the hook, so the === What operators see -In a cluster, each node drains its own Connector. No node applies the upgraded flow until every node that still has the outgoing flow has drained it, so the Connector reports `DRAINING` while the nodes wait for one another. A node that has already applied the upgraded flow has nothing to drain and does not hold back the others. A node that disconnects after applying the upgraded flow does not block the others either: the connected nodes start. `nifi.connector.flow.evolution.timeout` limits only the local drain in `prepareForFlowEvolution`. See <> in the Administration Guide. +In a cluster, each node drains its own Connector. No node applies the upgraded flow until every node that still has the outgoing flow has drained it, so the Connector reports `DRAINING` while the nodes wait for one another. A node that has already applied the upgraded flow has nothing to drain and does not hold back the others. A node that disconnects after applying the upgraded flow does not block the others either: the connected nodes start. The drain has no time limit. While it runs, NiFi logs a warning every 10 minutes with the number of FlowFiles still queued in the Connector. Stopping the Connector or cancelling the drain abandons the attempt. If evolution fails before the upgraded flow is applied, including while a node waits for the others to drain, the Connector remains stopped and still pending, and the next START runs the hook again. Stopping the Connector while it drains cancels the attempt. The START that begins an evolution is saved, so a restart while the Connector drains resumes the upgrade. The failure is not saved, because shutting down also interrupts the drain and must not prevent the upgrade from resuming. After a restart the Connector comes back in the state that was last saved. diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java index 482b1f0ba105..7d4cbce03ab2 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/registry/flow/mapping/VersionedComponentFlowMapper.java @@ -1122,7 +1122,7 @@ public VersionedConnector mapConnector(final ConnectorNode connectorNode, final final VersionedConnector versionedConnector = new VersionedConnector(); versionedConnector.setInstanceIdentifier(connectorNode.getIdentifier()); versionedConnector.setName(connectorNode.getName()); - versionedConnector.setScheduledState(mapConnectorState(connectorNode.getDesiredState())); + versionedConnector.setScheduledState(mapConnectorState(connectorNode)); versionedConnector.setType(connectorNode.getCanonicalClassName()); final ConnectorFlowSnapshot authoritativeSnapshot = connectorNode.getAuthoritativeFlowSnapshot(); @@ -1224,15 +1224,20 @@ private VersionedConnectorValueReference mapValueReference(final ConnectorValueR return versionedReference; } - private VersionedConnectorState mapConnectorState(final ConnectorState connectorState) { - if (connectorState == null) { + private VersionedConnectorState mapConnectorState(final ConnectorNode connectorNode) { + final ConnectorState desiredState = connectorNode.getDesiredState(); + if (desiredState == null) { return null; } - return switch (connectorState) { + return switch (desiredState) { case RUNNING, STARTING -> VersionedConnectorState.RUNNING; case TROUBLESHOOTING -> VersionedConnectorState.TROUBLESHOOTING; - default -> VersionedConnectorState.ENABLED; + // A failed update leaves the Connector stopped until it is corrected and started again + case STOPPED, STOPPING, DRAINING, PURGING, UPDATE_FAILED -> VersionedConnectorState.ENABLED; + // An update in progress is saved as the state the Connector returns to once the update completes + case PREPARING_FOR_UPDATE, UPDATING, UPDATED -> connectorNode.getPreUpdateDesiredState() == ConnectorState.RUNNING + ? VersionedConnectorState.RUNNING : VersionedConnectorState.ENABLED; }; } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java index 5916ef43cd33..fe097c2b89bc 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/test/java/org/apache/nifi/registry/flow/mapping/TestVersionedComponentFlowMapper.java @@ -22,6 +22,11 @@ import org.apache.nifi.bundle.BundleCoordinate; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.Validator; +import org.apache.nifi.components.connector.ConnectorConfiguration; +import org.apache.nifi.components.connector.ConnectorNode; +import org.apache.nifi.components.connector.ConnectorState; +import org.apache.nifi.components.connector.FrameworkFlowContext; +import org.apache.nifi.components.connector.MutableConnectorConfigurationContext; import org.apache.nifi.components.state.Scope; import org.apache.nifi.components.state.StateManager; import org.apache.nifi.components.state.StateManagerProvider; @@ -35,6 +40,8 @@ import org.apache.nifi.controller.service.ControllerServiceProvider; import org.apache.nifi.controller.state.StandardStateMap; import org.apache.nifi.flow.VersionedComponentState; +import org.apache.nifi.flow.VersionedConnector; +import org.apache.nifi.flow.VersionedConnectorState; import org.apache.nifi.flow.VersionedNodeState; import org.apache.nifi.flow.VersionedProcessor; import org.apache.nifi.logging.LogLevel; @@ -56,6 +63,8 @@ import org.apache.nifi.security.encryption.SensitivePropertyContext; import org.apache.nifi.security.encryption.SensitivePropertyContextFactory; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.stubbing.Answer; import java.io.IOException; @@ -65,6 +74,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -307,6 +317,54 @@ public void testClusteredExportCapturesBothLocalAndClusterState() throws IOExcep assertEquals(localState, localNodeStates.get(1).getState()); } + @ParameterizedTest + @EnumSource(ConnectorState.class) + public void testMapConnectorSavesStateForEveryDesiredState(final ConnectorState desiredState) { + final ConnectorNode connectorNode = createConnectorNode(desiredState); + when(connectorNode.getPreUpdateDesiredState()).thenReturn(ConnectorState.RUNNING); + + final Map expectedStates = Map.ofEntries( + Map.entry(ConnectorState.STARTING, VersionedConnectorState.RUNNING), + Map.entry(ConnectorState.RUNNING, VersionedConnectorState.RUNNING), + Map.entry(ConnectorState.STOPPING, VersionedConnectorState.ENABLED), + Map.entry(ConnectorState.STOPPED, VersionedConnectorState.ENABLED), + Map.entry(ConnectorState.DRAINING, VersionedConnectorState.ENABLED), + Map.entry(ConnectorState.PURGING, VersionedConnectorState.ENABLED), + Map.entry(ConnectorState.PREPARING_FOR_UPDATE, VersionedConnectorState.RUNNING), + Map.entry(ConnectorState.UPDATING, VersionedConnectorState.RUNNING), + Map.entry(ConnectorState.UPDATE_FAILED, VersionedConnectorState.ENABLED), + Map.entry(ConnectorState.UPDATED, VersionedConnectorState.RUNNING), + Map.entry(ConnectorState.TROUBLESHOOTING, VersionedConnectorState.TROUBLESHOOTING)); + + final VersionedComponentFlowMapper mapper = new VersionedComponentFlowMapper(mock(ExtensionManager.class), FlowMappingOptions.DEFAULT_OPTIONS); + final VersionedConnector versionedConnector = mapper.mapConnector(connectorNode, null); + assertEquals(expectedStates.get(desiredState), versionedConnector.getScheduledState()); + } + + @Test + public void testMapConnectorSavesEnabledWhenPreUpdateDesiredStateIsUnknown() { + final ConnectorNode connectorNode = createConnectorNode(ConnectorState.UPDATING); + + final VersionedComponentFlowMapper mapper = new VersionedComponentFlowMapper(mock(ExtensionManager.class), FlowMappingOptions.DEFAULT_OPTIONS); + final VersionedConnector versionedConnector = mapper.mapConnector(connectorNode, null); + assertEquals(VersionedConnectorState.ENABLED, versionedConnector.getScheduledState()); + } + + private ConnectorNode createConnectorNode(final ConnectorState desiredState) { + final MutableConnectorConfigurationContext configurationContext = mock(MutableConnectorConfigurationContext.class); + when(configurationContext.toConnectorConfiguration()).thenReturn(new ConnectorConfiguration(Set.of())); + final FrameworkFlowContext activeFlowContext = mock(FrameworkFlowContext.class); + when(activeFlowContext.getConfigurationContext()).thenReturn(configurationContext); + + final ConnectorNode connectorNode = mock(ConnectorNode.class); + when(connectorNode.getIdentifier()).thenReturn("connector-id"); + when(connectorNode.getBundleCoordinate()).thenReturn(new BundleCoordinate("org.apache.nifi", "connector-nar", "1.0.0")); + when(connectorNode.getActiveFlowContext()).thenReturn(activeFlowContext); + when(connectorNode.getCurrentState()).thenReturn(ConnectorState.STOPPED); + when(connectorNode.getDesiredState()).thenReturn(desiredState); + return connectorNode; + } + private FlowMappingOptions buildComponentStateMappingOptions(final ProcessorNode procNode, final Map localState, final Map clusterState, final boolean clusterProviderEnabled, final int localNodeOrdinal) throws IOException { diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java index e80254d71e45..daeb792139d5 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java @@ -50,6 +50,12 @@ public interface ConnectorNode extends ComponentAuthorizable, VersionedComponent ConnectorState getDesiredState(); + /** + * @return the desired state recorded when the most recent update began, which the flow saves while that update is in + * progress, or null if no update has begun + */ + ConnectorState getPreUpdateDesiredState(); + /** * Verifies that the Connector is in a state that allows it to be deleted. If the Connector is not in a state * that allows it to be deleted, this method will throw an IllegalStateException. diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java index 0309f748b0d2..7e6e1db372b9 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorRepositoryInitializationContext.java @@ -59,13 +59,4 @@ default Duration getConnectorSyncTimeout() { return Duration.ofMinutes(5); } - /** - * Returns the time allowed for each node to drain a connector during the local evolve-drain phase of flow evolution. - * - * @return the flow evolution drain timeout, defaults to 30 minutes - */ - default Duration getConnectorFlowEvolutionTimeout() { - return Duration.ofMinutes(30); - } - } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java index 4f7f7f12a5fe..963d6ee7a792 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ConnectorFlowEvolution.java @@ -297,15 +297,7 @@ private void refreshPreUpgradeParameterSecrets(final StandardFlowEvolutionContex final ParameterSecretReferences.Resolution resolution = connector.resolveParameterSecrets(snapshot.parameterContext(), snapshot.parameterSecretReferences()); if (!resolution.unresolvedReferences().isEmpty()) { - final Map.Entry unresolved = resolution.unresolvedReferences().entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .findFirst() - .orElseThrow(); - final SecretReference reference = unresolved.getValue(); - final String secretName = reference.getFullyQualifiedName() == null ? reference.getSecretName() : reference.getFullyQualifiedName(); - final String explanation = "Flow evolution cannot start: secret [%s] used by parameter [%s] could not be resolved. " - .formatted(secretName, unresolved.getKey()) - + "Restore the secret in its provider, then start the Connector to resume the upgrade."; + final String explanation = explainUnresolvedSecrets(resolution); verifyContext(context); connector.setUnresolvedParameterSecretReferences(Map.copyOf(resolution.unresolvedReferences())); fail(context, explanation, null); @@ -319,6 +311,22 @@ private void refreshPreUpgradeParameterSecrets(final StandardFlowEvolutionContex } } + private static String explainUnresolvedSecrets(final ParameterSecretReferences.Resolution resolution) { + if (resolution.secretsProviderFailure() != null) { + return "Flow evolution cannot start: the secrets provider could not be reached: %s. Restore access to the provider, then start the Connector to resume the upgrade." + .formatted(resolution.secretsProviderFailure()); + } + + final Map.Entry unresolved = resolution.unresolvedReferences().entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .findFirst() + .orElseThrow(); + final SecretReference reference = unresolved.getValue(); + final String secretName = reference.getFullyQualifiedName() == null ? reference.getSecretName() : reference.getFullyQualifiedName(); + return "Flow evolution cannot start: secret [%s] used by parameter [%s] could not be resolved. Restore the secret in its provider, then start the Connector to resume the upgrade." + .formatted(secretName, unresolved.getKey()); + } + private void completeEvolveDrainPhase(final StandardFlowEvolutionContext context) throws FlowUpdateException { // The hook may start processors so queues can empty. Those processors must be stopped before the upgraded // flow is verified, so no FlowFile reaches a connection the upgraded flow removes after it has been checked. diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java index 57f58ced3b53..64e9a081df4c 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/ParameterSecretReferences.java @@ -122,18 +122,18 @@ static Map matchSensitiveParametersToSecretReferences(f * Resolves the values of a persisted managed Parameter Context without modifying it. A sensitive parameter bound to a * Secret Reference takes the current value of that secret, or is left null and reported when the secret cannot be * resolved. Any other sensitive parameter takes its persisted value decrypted with the supplied provider, or is left null - * and reported when the value cannot be decrypted. + * and reported when the value cannot be decrypted. A Secrets Provider that cannot be reached leaves every reference + * unresolved, so a restore installs the flow with its components stopped instead of failing, and the failure is reported. */ static Resolution resolve(final VersionedParameterContext parameterContext, final Map parameterSecretReferences, final SecretsManager secretsManager, final PropertyEncryptionProvider propertyEncryptionProvider) { if (parameterContext == null) { - return new Resolution(null, List.of(), Map.of(), Set.of()); + return new Resolution(null, List.of(), Map.of(), Set.of(), null); } final VersionedParameterContext resolved = copyContext(parameterContext); final Map references = parameterSecretReferences == null ? Map.of() : parameterSecretReferences; - final Set distinctReferences = new HashSet<>(references.values()); - final Map secrets = getSecrets(distinctReferences, secretsManager); + final SecretsLookup secretsLookup = getSecrets(new HashSet<>(references.values()), secretsManager); final Map unresolved = new HashMap<>(); final Set undecryptable = new HashSet<>(); final List resolvedValues = new ArrayList<>(); @@ -160,7 +160,7 @@ static Resolution resolve(final VersionedParameterContext parameterContext, fina continue; } - final Secret secret = secrets.get(reference); + final Secret secret = secretsLookup.secrets().get(reference); if (secret == null) { parameter.setValue(null); unresolved.put(parameter.getName(), reference); @@ -176,23 +176,19 @@ static Resolution resolve(final VersionedParameterContext parameterContext, fina } } - return new Resolution(resolved, resolvedValues, unresolved, undecryptable); + return new Resolution(resolved, resolvedValues, unresolved, undecryptable, secretsLookup.failure()); } - /** - * A Secrets Provider that cannot be reached leaves every reference unresolved, so a restore installs the flow with its - * components stopped instead of failing. - */ - private static Map getSecrets(final Set references, final SecretsManager secretsManager) { + private static SecretsLookup getSecrets(final Set references, final SecretsManager secretsManager) { if (references.isEmpty()) { - return Map.of(); + return new SecretsLookup(Map.of(), null); } try { - return secretsManager.getSecrets(references, false); + return new SecretsLookup(secretsManager.getSecrets(references, false), null); } catch (final RuntimeException e) { logger.warn("Failed to retrieve {} Secret References from the Secrets Manager; treating them as unresolved", references.size(), e); - return Map.of(); + return new SecretsLookup(Map.of(), e.getMessage() == null ? e.getClass().getName() : e.getMessage()); } } @@ -233,11 +229,20 @@ private static VersionedParameterContext copyContext(final VersionedParameterCon * @param parameterValues the values taken from Secret References * @param unresolvedReferences Secret References that could not be resolved, keyed by parameter name * @param undecryptableParameters names of parameters whose persisted value could not be decrypted + * @param secretsProviderFailure the reason the Secrets Provider could not be reached, or null if it was reached */ record Resolution( VersionedParameterContext parameterContext, List parameterValues, Map unresolvedReferences, - Set undecryptableParameters) { + Set undecryptableParameters, + String secretsProviderFailure) { + } + + /** + * @param secrets the secrets retrieved from the Secrets Manager, keyed by reference + * @param failure the reason the Secrets Manager could not be reached, or null if it was reached + */ + private record SecretsLookup(Map secrets, String failure) { } } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java index a624cdf38577..9920ebcc3cb0 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java @@ -130,6 +130,7 @@ public class StandardConnectorNode implements ConnectorNode, GroupedComponent { private final AtomicReference> drainFutureRef = new AtomicReference<>(); private volatile ValidationResult unresolvedBundleValidationResult = null; private volatile Map unresolvedParameterSecretReferences = Map.of(); + private volatile ConnectorState preUpdateDesiredState; private final Object workingFlowContextLock = new Object(); private volatile WorkingFlowContextState workingFlowContextState = new WorkingFlowContextState(null); @@ -297,6 +298,7 @@ public void transitionStateForUpdating() { return; } + preUpdateDesiredState = getDesiredState(); stateTransition.setDesiredState(ConnectorState.UPDATING); stateTransition.setCurrentState(ConnectorState.PREPARING_FOR_UPDATE); } @@ -973,6 +975,11 @@ public ConnectorState getDesiredState() { return stateTransition.getDesiredState(); } + @Override + public ConnectorState getPreUpdateDesiredState() { + return preUpdateDesiredState; + } + @Override public Optional getIdleDuration() { final ProcessGroup processGroup = getActiveFlowContext().getManagedProcessGroup(); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java index 4f5aa96b4138..10fe9b49af02 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorRepoInitializationContext.java @@ -34,7 +34,6 @@ public class StandardConnectorRepoInitializationContext implements ConnectorRepo private final ConnectorRequestReplicator requestReplicator; private final ConnectorConfigurationProvider connectorConfigurationProvider; private final Duration connectorSyncTimeout; - private final Duration connectorFlowEvolutionTimeout; public StandardConnectorRepoInitializationContext(final FlowManager flowManager, final ExtensionManager extensionManager, @@ -43,8 +42,7 @@ public StandardConnectorRepoInitializationContext(final FlowManager flowManager, final NodeTypeProvider nodeTypeProvider, final ConnectorRequestReplicator requestReplicator, final ConnectorConfigurationProvider connectorConfigurationProvider, - final Duration connectorSyncTimeout, - final Duration connectorFlowEvolutionTimeout) { + final Duration connectorSyncTimeout) { this.flowManager = flowManager; this.extensionManager = extensionManager; this.secretsManager = secretsManager; @@ -53,7 +51,6 @@ public StandardConnectorRepoInitializationContext(final FlowManager flowManager, this.requestReplicator = requestReplicator; this.connectorConfigurationProvider = connectorConfigurationProvider; this.connectorSyncTimeout = connectorSyncTimeout; - this.connectorFlowEvolutionTimeout = connectorFlowEvolutionTimeout; } @Override @@ -95,9 +92,4 @@ public ConnectorConfigurationProvider getConnectorConfigurationProvider() { public Duration getConnectorSyncTimeout() { return connectorSyncTimeout; } - - @Override - public Duration getConnectorFlowEvolutionTimeout() { - return connectorFlowEvolutionTimeout; - } } 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 10f33507cd5d..4fc9b3ae6034 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 @@ -68,7 +68,7 @@ public class StandardConnectorRepository implements ConnectorRepository { private static final Duration SYNC_POLL_INTERVAL = Duration.ofSeconds(2); private static final List FLOW_EVOLUTION_POLL_INTERVALS = List.of( Duration.ofSeconds(2), Duration.ofSeconds(5), Duration.ofSeconds(10), Duration.ofSeconds(30)); - private static final Duration DEFAULT_FLOW_EVOLUTION_DRAIN_TIMEOUT = Duration.ofMinutes(30); + private static final Duration FLOW_EVOLUTION_DRAIN_WARNING_INTERVAL = Duration.ofMinutes(10); /** * Soft cardinality limit beyond which a WARN is emitted when a {@link ConnectorConfigurationProvider} @@ -91,7 +91,6 @@ public class StandardConnectorRepository implements ConnectorRepository { private volatile AssetManager assetManager; private volatile ConnectorConfigurationProvider configurationProvider; private volatile Duration syncTimeout; - private volatile Duration flowEvolutionDrainTimeout = DEFAULT_FLOW_EVOLUTION_DRAIN_TIMEOUT; @Override public void initialize(final ConnectorRepositoryInitializationContext context) { @@ -103,7 +102,6 @@ public void initialize(final ConnectorRepositoryInitializationContext context) { this.assetManager = context.getAssetManager(); this.configurationProvider = context.getConnectorConfigurationProvider(); this.syncTimeout = context.getConnectorSyncTimeout(); - this.flowEvolutionDrainTimeout = canonicalFlowEvolutionDrainTimeout(context.getConnectorFlowEvolutionTimeout()); logger.debug("Successfully initialized ConnectorRepository with configurationProvider={}, syncTimeout={}", configurationProvider != null ? configurationProvider.getClass().getSimpleName() : "null", syncTimeout); } @@ -719,12 +717,19 @@ private Future runFlowEvolution(final ConnectorNode connector, final Conne } private void awaitFlowEvolutionDrain(final ConnectorNode connector, final Future future) throws Throwable { + final long drainStartNanos = System.nanoTime(); try { - future.get(flowEvolutionDrainTimeout.toNanos(), TimeUnit.NANOSECONDS); - } catch (final TimeoutException e) { - final FlowUpdateException timedOut = new FlowUpdateException("Flow evolution drain timed out for " + connector, e); - connector.abortUpdate(timedOut); - throw timedOut; + while (true) { + try { + future.get(FLOW_EVOLUTION_DRAIN_WARNING_INTERVAL.toNanos(), TimeUnit.NANOSECONDS); + return; + } catch (final TimeoutException e) { + final long elapsedMinutes = Duration.ofNanos(System.nanoTime() - drainStartNanos).toMinutes(); + final int queuedFlowFiles = connector.getActiveFlowContext().getManagedProcessGroup().getQueueSize().getObjectCount(); + logger.warn("Flow evolution drain for {} is still running after {} minutes with {} FlowFiles queued; verify that nothing is blocking the drain", + connector, elapsedMinutes, queuedFlowFiles); + } + } } catch (final InterruptedException e) { connector.abortUpdate(e); throw e; @@ -739,14 +744,6 @@ private void awaitFlowEvolutionDrain(final ConnectorNode connector, final Future } } - private static Duration canonicalFlowEvolutionDrainTimeout(final Duration timeout) { - if (timeout == null || timeout.isZero() || timeout.isNegative()) { - return DEFAULT_FLOW_EVOLUTION_DRAIN_TIMEOUT; - } - - return timeout; - } - private void handleFlowEvolutionFailure(final ConnectorNode connector, final CompletableFuture evolutionFuture, final Throwable failure, final boolean startAttempted) { // A failed evolution is not saved; the persisted flow stays as it was last saved until the connector is corrected. diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java index 58a149e0bff9..5059bfca18ec 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java @@ -973,8 +973,6 @@ private static ConnectorRepository createConnectorRepository(final NiFiPropertie final String syncTimeoutValue = properties.getProperty(NiFiProperties.CONNECTOR_SYNC_TIMEOUT, NiFiProperties.DEFAULT_CONNECTOR_SYNC_TIMEOUT); final long syncTimeoutMillis = FormatUtils.getTimeDuration(syncTimeoutValue, TimeUnit.MILLISECONDS); final Duration connectorSyncTimeout = Duration.ofMillis(syncTimeoutMillis); - final String evolutionTimeoutValue = properties.getProperty(NiFiProperties.CONNECTOR_FLOW_EVOLUTION_TIMEOUT, NiFiProperties.DEFAULT_CONNECTOR_FLOW_EVOLUTION_TIMEOUT); - final long evolutionTimeoutMillis = FormatUtils.getTimeDuration(evolutionTimeoutValue, TimeUnit.MILLISECONDS); final ConnectorRepositoryInitializationContext initializationContext = new StandardConnectorRepoInitializationContext( flowManager, @@ -984,8 +982,7 @@ private static ConnectorRepository createConnectorRepository(final NiFiPropertie nodeTypeProvider, requestReplicator, connectorConfigurationProvider, - connectorSyncTimeout, - Duration.ofMillis(evolutionTimeoutMillis) + connectorSyncTimeout ); synchronized (created) { diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java index eed7f03b62f1..f239184b7e33 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestParameterSecretReferences.java @@ -101,6 +101,7 @@ void testResolveDecryptsPersistedValuesAndTakesCurrentSecrets() { assertEquals("plain", getParameter(resolution.parameterContext(), "Plain").getValue()); assertEquals(Map.of("Missing", missingReference), resolution.unresolvedReferences()); assertEquals(Set.of("Undecryptable"), resolution.undecryptableParameters()); + assertNull(resolution.secretsProviderFailure()); assertEquals(Set.of("Resolved", "Nullable"), resolution.parameterValues().stream().map(ParameterValue::getName).collect(Collectors.toSet())); assertEquals(encrypt("Generated", "Bearer generated"), getParameter(persisted, "Generated").getValue()); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java index f729383ece7d..4bc2647e842f 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java @@ -2499,7 +2499,12 @@ public void testEvolveFlowRejectsMissingManagedComponents() throws Exception { public void testFlowEvolutionWithMissingSecretThenRestoredSecret() throws Exception { final SecretReference secretReference = new SecretReference("provider-id", "Provider", "password", "Provider.group.password"); final AtomicReference currentSecret = new AtomicReference<>(); + final AtomicBoolean providerUnavailable = new AtomicBoolean(true); when(secretsManager.getSecrets(anySet(), eq(false))).thenAnswer(invocation -> { + if (providerUnavailable.get()) { + throw new IllegalStateException("Secrets Provider unavailable"); + } + final Secret secret = currentSecret.get(); return secret == null ? Map.of() : Map.of(secretReference, secret); }); @@ -2509,6 +2514,14 @@ public void testFlowEvolutionWithMissingSecretThenRestoredSecret() throws Except persistedParameterContext("Source Database Password"), Map.of("Source Database Password", secretReference), outgoingSnapshotBundle()); + connectorNode.prepareFlowEvolution(scheduler); + final ExecutionException providerFailure = assertThrows(ExecutionException.class, + () -> connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS)); + assertTrue(providerFailure.getCause().getMessage().contains("secrets provider could not be reached: Secrets Provider unavailable"), + providerFailure.getCause().getMessage()); + assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); + + providerUnavailable.set(false); connectorNode.prepareFlowEvolution(scheduler); final ExecutionException failure = assertThrows(ExecutionException.class, () -> connectorNode.evolveFlow(flowEvolutionExecutor).get(5, TimeUnit.SECONDS)); diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java index b9911593828e..ca43139c9e1c 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorRepository.java @@ -2971,10 +2971,6 @@ private void seedWorkingConfiguration(final StandardConnectorNode connectorNode, } private StandardConnectorRepository createRepositoryWithShortTimeout(final ConnectorConfigurationProvider provider) { - return createRepositoryWithShortTimeout(provider, Duration.ofMinutes(30)); - } - - private StandardConnectorRepository createRepositoryWithShortTimeout(final ConnectorConfigurationProvider provider, final Duration flowEvolutionTimeout) { final StandardConnectorRepository repository = new StandardConnectorRepository(); final ConnectorRepositoryInitializationContext initContext = mock(ConnectorRepositoryInitializationContext.class); when(initContext.getFlowManager()).thenReturn(mock(FlowManager.class)); @@ -2982,7 +2978,6 @@ private StandardConnectorRepository createRepositoryWithShortTimeout(final Conne when(initContext.getAssetManager()).thenReturn(mock(AssetManager.class)); when(initContext.getConnectorConfigurationProvider()).thenReturn(provider); when(initContext.getConnectorSyncTimeout()).thenReturn(Duration.ofSeconds(5)); - when(initContext.getConnectorFlowEvolutionTimeout()).thenReturn(flowEvolutionTimeout); repository.initialize(initContext); return repository; } @@ -3442,22 +3437,6 @@ public void testPersistenceFailureAfterApplyLeavesUpdateFailedAndLaterStartRunsN assertEquals(ConnectorState.RUNNING, connectorNode.getCurrentState()); } - @Test - public void testFlowEvolutionDrainTimeoutFailsEvolution() throws Exception { - final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); - connector.leaveFutureIncomplete = true; - final StandardConnectorNode connectorNode = pendingEvolutionNode("drain-timeout", connector); - final StandardConnectorRepository repository = createRepositoryWithShortTimeout(null, Duration.ofMillis(500)); - - assertThrows(ExecutionException.class, () -> repository.startConnector(connectorNode, NO_OP_PERSISTENCE).get(5, TimeUnit.SECONDS)); - assertEquals(ConnectorState.STOPPED, connectorNode.getCurrentState()); - assertEquals(FlowEvolutionStatus.FAILED, connectorNode.getReportedFlowEvolutionStatus()); - assertTrue(connectorNode.isPendingFlowEvolution()); - assertEquals(0, connector.applyCalls); - assertTrue(connectorNode.getValidationErrors().stream() - .anyMatch(result -> StandardConnectorNode.FLOW_EVOLUTION_VALIDATION_SUBJECT.equals(result.getSubject()) && result.getExplanation().contains("timed out"))); - } - @Test public void testConfigurationUpdateSavesAgainWithRestoredState() throws Exception { final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); diff --git a/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml b/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml index 3eed01855a5e..390c6585d43a 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml +++ b/nifi-framework-bundle/nifi-framework/nifi-resources/pom.xml @@ -127,7 +127,6 @@ ./assets org.apache.nifi.asset.StandardConnectorAssetManager ./connector_assets - 30 mins diff --git a/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties b/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties index f25efcc09c0d..bbe41a671358 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties +++ b/nifi-framework-bundle/nifi-framework/nifi-resources/src/main/resources/conf/nifi.properties @@ -142,9 +142,6 @@ nifi.asset.manager.properties.directory=${nifi.asset.manager.properties.director nifi.connector.asset.manager.implementation=${nifi.connector.asset.manager.implementation} nifi.connector.asset.manager.properties.directory=${nifi.connector.asset.manager.properties.directory} -# How long a connector may spend draining during flow evolution. -nifi.connector.flow.evolution.timeout=${nifi.connector.flow.evolution.timeout} - # Connector Configuration Provider nifi.connector.configuration.provider.implementation= diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java index a5cf82e6eece..41de5896b33e 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractChangeVersionDrainIT.java @@ -67,7 +67,9 @@ protected String createOutgoingConnector(final Map properties) t return createDrainConnector(DRAIN_V1, properties); } - @Override + /** + * Moves the stopped Connector to its incoming version, leaving it STOPPED with the upgrade pending. + */ protected void triggerUpgrade(final String connectorId) throws Exception { changeVersion(connectorId, DRAIN_V2); } diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java index 69958e856d2c..3daac807c408 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractConnectorUpgradeDrainIT.java @@ -53,8 +53,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Upgrade-drain scenarios that hold for every way a Connector can move to a new version. Each subclass supplies the - * trigger: a NAR swap followed by a restart, or a version change while the Connector is stopped. + * Upgrade-drain support shared by every way a Connector can move to a new version: a NAR swap followed by a restart, or a + * version change while the Connector is stopped. Each subclass supplies the outgoing Connector and the expected bundles. */ public abstract class AbstractConnectorUpgradeDrainIT extends AbstractNarSwapMigrationIT { @@ -124,11 +124,6 @@ void assertMatches(final Bundle bundle, final String description) { */ protected abstract String createOutgoingConnector(Map properties) throws Exception; - /** - * Moves the stopped Connector to its incoming version, leaving it STOPPED with the upgrade pending. - */ - protected abstract void triggerUpgrade(String connectorId) throws Exception; - protected abstract ExpectedBundle outgoingBundle(); protected abstract ExpectedBundle incomingBundle(); diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java deleted file mode 100644 index 5b0d1fc30acc..000000000000 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/AbstractNarSwapUpgradeDrainIT.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.connectors; - -import java.io.IOException; -import java.util.Map; - -/** - * Upgrade-drain support whose trigger is a NAR swap and restart. - */ -public abstract class AbstractNarSwapUpgradeDrainIT extends AbstractConnectorUpgradeDrainIT { - - static final String V1_BUNDLE = "nifi-system-test-extensions-nar"; - static final String V2_BUNDLE = "nifi-alternate-config-extensions-nar"; - - @Override - protected String createOutgoingConnector(final Map properties) throws Exception { - return createConnector("UpgradeDrainConnector", properties); - } - - @Override - protected void triggerUpgrade(final String connectorId) throws IOException { - swapAndRestart(); - } - - @Override - protected ExpectedBundle outgoingBundle() { - return new ExpectedBundle(V1_BUNDLE, null); - } - - @Override - protected ExpectedBundle incomingBundle() { - return new ExpectedBundle(V2_BUNDLE, null); - } - - protected void swapAndRestart() throws IOException { - getNiFiInstance().stop(); - switchOutNars(); - getNiFiInstance().start(true); - waitForCluster(); - } -} diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java index 304e497a263a..f497a19594df 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ClusteredConnectorUpgradeDrainIT.java @@ -45,9 +45,11 @@ /** * Verifies clustered startup after a Connector NAR swap, with Connector configuration held by an external provider. */ -public class ClusteredConnectorUpgradeDrainIT extends AbstractNarSwapUpgradeDrainIT { +public class ClusteredConnectorUpgradeDrainIT extends AbstractConnectorUpgradeDrainIT { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String OUTGOING_BUNDLE = "nifi-system-test-extensions-nar"; + private static final String INCOMING_BUNDLE = "nifi-alternate-config-extensions-nar"; private static final String UPGRADE_STEP = "Upgrade"; private static final String COMMENT_PROPERTY = "Comment"; private static final String LEGACY_NOTE = "Legacy Note"; @@ -74,6 +76,21 @@ public NiFiInstanceFactory getInstanceFactory() { .build()); } + @Override + protected String createOutgoingConnector(final Map properties) throws Exception { + return createConnector("UpgradeDrainConnector", properties); + } + + @Override + protected ExpectedBundle outgoingBundle() { + return new ExpectedBundle(OUTGOING_BUNDLE, null); + } + + @Override + protected ExpectedBundle incomingBundle() { + return new ExpectedBundle(INCOMING_BUNDLE, null); + } + /** * Swaps the Connector NARs with two Connectors. The running Connector queues FlowFiles on the connection from the processor * the upgrade removes to the terminator that stays, so it resumes draining until that connection is empty. The stopped From 42d93fde0e3012c3063bb2404bb3851311b8b721 Mon Sep 17 00:00:00 2001 From: Bob Paulin Date: Fri, 20 Nov 2026 11:16:19 -0600 Subject: [PATCH 4/5] NIFI-16477: Address latest review feedback on Connector flow evolution - Refresh the authoritative snapshot when a Connector migration is committed - Wait for joining cluster nodes only at the flow evolution drain barrier - Adopt the pre-upgrade snapshot when restoring a pending evolution fails to load configuration - Fill the managed Parameter Context for a legacy Troubleshooting save restored after an upgrade --- .../ClusteredConnectorRequestReplicator.java | 8 +- ...stClusteredConnectorRequestReplicator.java | 22 ++++- .../components/connector/ConnectorNode.java | 9 +- .../connector/StandardConnectorNode.java | 87 +++++++++++++++---- .../StandardConnectorRepository.java | 17 +--- .../connector/FlowEvolutionHookConnector.java | 19 +++- .../connector/TestStandardConnectorNode.java | 67 +++++++++++++- ...nectorVersionedFlowMigrationRestartIT.java | 29 ++++++- 8 files changed, 212 insertions(+), 46 deletions(-) diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java index d5473e717aab..9019de0751f6 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/http/replication/ClusteredConnectorRequestReplicator.java @@ -88,7 +88,9 @@ public FlowEvolutionStatus getFlowEvolutionStatus(final String connectorId) thro private ConnectorEntity getConnectorEntity(final String connectorId, final boolean requireAllConnected) throws IOException { final RequestReplicator requestReplicator = getRequestReplicator(); - verifyClusterMembership(connectorId, requireAllConnected); + if (requireAllConnected) { + verifyClusterMembership(connectorId); + } final URI uri = URI.create(replicationScheme + "://localhost/nifi-api/connectors/" + connectorId); @@ -155,7 +157,7 @@ private ConnectorEntity getConnectorEntity(final String connectorId, final boole } } - private void verifyClusterMembership(final String connectorId, final boolean requireAllConnected) throws IOException { + private void verifyClusterMembership(final String connectorId) throws IOException { final ClusterCoordinator clusterCoordinator = clusterCoordinatorSupplier.get(); if (clusterCoordinator == null || !clusterCoordinator.isConnected()) { throw new ConnectorClusterUnavailableException("No connected nodes while retrieving Connector %s".formatted(connectorId)); @@ -168,7 +170,7 @@ private void verifyClusterMembership(final String connectorId, final boolean req throw new ConnectorClusterUnavailableException("Cannot retrieve Connector %s because node %s is still joining the cluster" .formatted(connectorId, connectionStatus.getNodeIdentifier())); } - if (requireAllConnected && state != NodeConnectionState.CONNECTED && state != NodeConnectionState.REMOVED) { + if (state != NodeConnectionState.CONNECTED && state != NodeConnectionState.REMOVED) { throw new IOException("Cannot retrieve flow evolution status for Connector %s because node %s is %s" .formatted(connectorId, connectionStatus.getNodeIdentifier(), state)); } diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java index f15aaaaff3d7..7be5de5952ac 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/replication/TestClusteredConnectorRequestReplicator.java @@ -24,6 +24,7 @@ import org.apache.nifi.cluster.manager.NodeResponse; import org.apache.nifi.cluster.manager.exception.NoConnectedNodesException; import org.apache.nifi.components.connector.ConnectorClusterUnavailableException; +import org.apache.nifi.components.connector.ConnectorState; import org.apache.nifi.components.connector.FlowEvolutionStatus; import org.apache.nifi.web.api.dto.ConnectorDTO; import org.apache.nifi.web.api.entity.ConnectorEntity; @@ -48,7 +49,7 @@ class TestClusteredConnectorRequestReplicator { private static final String CONNECTOR_ID = "connector-1"; @Test - void testFlowEvolutionStatusWaitsForMembershipToSettle() { + void testOnlyFlowEvolutionStatusWaitsForMembershipToSettle() throws Exception { final RequestReplicator requestReplicator = mock(RequestReplicator.class); final ClusterCoordinator clusterCoordinator = mock(ClusterCoordinator.class); final NodeConnectionStatus connectionStatus = mock(NodeConnectionStatus.class); @@ -68,6 +69,15 @@ void testFlowEvolutionStatusWaitsForMembershipToSettle() { assertThrows(ConnectorClusterUnavailableException.class, () -> replicator.getFlowEvolutionStatus(CONNECTOR_ID)); verify(requestReplicator, never()).replicate(isNull(), eq("GET"), any(), anyMap(), anyMap()); + + // A node that never returns after a cluster restart stays NOT_YET_CONNECTED, so Connector state is read from the connected nodes. + final AsyncClusterResponse asyncResponse = mock(AsyncClusterResponse.class); + final NodeResponse nodeResponse = mock(NodeResponse.class); + when(requestReplicator.replicate(isNull(), eq("GET"), any(), anyMap(), anyMap())).thenReturn(asyncResponse); + when(asyncResponse.awaitMergedResponse()).thenReturn(nodeResponse); + when(nodeResponse.getUpdatedEntity()).thenReturn(connectorEntity(ConnectorState.UPDATED)); + + assertEquals(ConnectorState.UPDATED, replicator.getState(CONNECTOR_ID)); } @Test @@ -126,6 +136,16 @@ void testReplicateNoConnectedNodesIsTranslated() { private static ConnectorEntity connectorEntity(final FlowEvolutionStatus status) { final ConnectorDTO connector = new ConnectorDTO(); connector.setFlowEvolutionStatus(status.name()); + return connectorEntity(connector); + } + + private static ConnectorEntity connectorEntity(final ConnectorState state) { + final ConnectorDTO connector = new ConnectorDTO(); + connector.setState(state.name()); + return connectorEntity(connector); + } + + private static ConnectorEntity connectorEntity(final ConnectorDTO connector) { final ConnectorEntity entity = new ConnectorEntity(); entity.setComponent(connector); return entity; diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java index daeb792139d5..d01c1e994030 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/components/connector/ConnectorNode.java @@ -465,15 +465,16 @@ void inheritConfiguration(List activeFlowConfigurati /** * Commits the merged configuration returned by {@link #applyMigratedConfiguration} onto this Connector's active - * configuration so the migration outcome is persisted to {@code flow.json.gz}. Each step in {@code mergedConfiguration} - * is written via {@code replaceProperties} so the resulting active configuration matches the merged configuration - * exactly, including property removals. + * configuration so the migration outcome is persisted to {@code flow.json.gz}. The active configuration is replaced + * so that it matches the merged configuration exactly, including property removals, and the authoritative flow + * snapshot is then captured again so that flow saves write the migrated configuration and managed flow. * *

* The framework calls this method only after the state-migration phase and all staged component-state writes have * succeeded. Until this commit runs, the active configuration still holds the pre-migration values, so a failure * in either migration phase can be rolled back by restoring the initial flow without having to revert active - * configuration mutations. + * configuration mutations. If the snapshot cannot be captured, the pre-migration active configuration is restored + * before the exception is thrown. *

* * @param mergedConfiguration the configuration produced by {@link #applyMigratedConfiguration} during this migration diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java index 9920ebcc3cb0..bc1397980c93 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/components/connector/StandardConnectorNode.java @@ -387,13 +387,24 @@ public void commitMigratedConfiguration(final ConnectorConfiguration mergedConfi } Objects.requireNonNull(mergedConfiguration, "Merged configuration is required"); - // Write the merged configuration onto the active configuration so the migration outcome is persisted to - // flow.json.gz. Each step is written via replaceProperties so the resulting active configuration matches the - // merged configuration exactly, including any properties the connector removed during migration. This is the - // durability boundary of the two-phase migration: once this commit runs the migration is part of the persisted - // flow and will be restored on every restart via inheritConfiguration(...). - for (final NamedStepConfiguration stepConfig : mergedConfiguration.getNamedStepConfigurations()) { - activeFlowContext.getConfigurationContext().replaceProperties(stepConfig.stepName(), stepConfig.configuration()); + // Replace the active configuration with the merged configuration, including any properties the connector removed + // during migration, then capture a fresh authoritative snapshot. Flow saves write the active configuration and the + // managed flow from that snapshot, so this is the durability boundary of the two-phase migration: once this commit + // runs the migration is part of the persisted flow and will be restored on every restart via inheritConfiguration(...). + // The migration manager rolls back the managed flow if commit fails, so a failed capture restores the pre-migration + // active configuration to match it. + final ConnectorConfiguration preMigrationConfiguration = activeFlowContext.getConfigurationContext().toConnectorConfiguration(); + replaceActiveConfiguration(mergedConfiguration); + try { + captureAuthoritativeSnapshot(); + } catch (final RuntimeException e) { + try { + replaceActiveConfiguration(preMigrationConfiguration); + } catch (final RuntimeException restoreFailure) { + e.addSuppressed(restoreFailure); + } + + throw e; } resetValidationState(); @@ -402,6 +413,18 @@ public void commitMigratedConfiguration(final ConnectorConfiguration mergedConfi logger.info("Committed migrated configuration onto active configuration for {}", this); } + /** + * Replaces the complete active configuration, so a step that the given configuration does not contain is removed. + */ + private void replaceActiveConfiguration(final ConnectorConfiguration configuration) { + final Map stepConfigurations = new LinkedHashMap<>(); + for (final NamedStepConfiguration stepConfig : configuration.getNamedStepConfigurations()) { + stepConfigurations.put(stepConfig.stepName(), stepConfig.configuration()); + } + + activeFlowContext.getConfigurationContext().replaceConfiguration(stepConfigurations); + } + @Override public void inheritConfiguration(final List activeConfig, final List workingConfig, final Bundle flowContextBundle) throws FlowUpdateException { @@ -749,12 +772,7 @@ private void applyUpdate(final FrameworkFlowContext contextToInherit) throws Flo // Update the active flow context based on the properties of the provided context, as the connector has now been updated. // The supplied context is the complete configuration, so a step it does not contain has been removed. - final ConnectorConfiguration workingConfig = contextToInherit.getConfigurationContext().toConnectorConfiguration(); - final Map inheritedConfiguration = new LinkedHashMap<>(); - for (final NamedStepConfiguration stepConfig : workingConfig.getNamedStepConfigurations()) { - inheritedConfiguration.put(stepConfig.stepName(), stepConfig.configuration()); - } - activeFlowContext.getConfigurationContext().replaceConfiguration(inheritedConfiguration); + replaceActiveConfiguration(contextToInherit.getConfigurationContext().toConnectorConfiguration()); getComponentLog().info("Working Context has been applied to Active Context"); captureAuthoritativeSnapshot(); @@ -1814,8 +1832,9 @@ public boolean restorePendingFlowEvolution(final VersionedConnector persisted, f if (!extensionMissing && !sameManagedBundle(managedFlowBundle) && persistedManagedGroup != null) { // Skip inheritConfiguration. Its applyUpdate would replace the pre-upgrade group with the new bundle's - // flow. The restored group keeps the previous bundle, so the next start evolves it. A failed restore still loads - // the configuration and adopts the persisted snapshot, so the next flow save keeps the pre-upgrade flow. + // flow. The restored group keeps the previous bundle, so the next start evolves it. A failed restore or a failed + // configuration load still adopts the persisted snapshot, so the next flow save keeps the pre-upgrade flow. The + // snapshot is adopted after the load because flow saves write the active configuration from the snapshot. try { restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, ResumeComponentState.RESUME_AS_PERSISTED); } catch (final Exception e) { @@ -1823,14 +1842,48 @@ public boolean restorePendingFlowEvolution(final VersionedConnector persisted, f markManagedFlowRestoreFailed(); } - loadConfigurationsWithoutRebuildingFlow(activeConfiguration, workingConfiguration); - adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); + ConnectorFlowSnapshot filledParameters = null; + try { + loadConfigurationsWithoutRebuildingFlow(activeConfiguration, workingConfiguration); + + // A group saved without its parameter context (Troubleshooting under NiFi 2.12 or earlier) has no values to restore, + // and its components must run to empty the queues before Troubleshooting can end while the upgrade is pending. + if (persisted.getManagedParameterContext() == null) { + filledParameters = fillParametersFromActiveFlow(managedFlowBundle); + } + } finally { + final VersionedParameterContext parameterContext = filledParameters == null ? persisted.getManagedParameterContext() : filledParameters.parameterContext(); + final Map secretReferences = filledParameters == null ? parameterSecretReferences : filledParameters.parameterSecretReferences(); + adoptAuthoritativeSnapshot(persistedManagedGroup, parameterContext, secretReferences, managedFlowBundle); + } + return true; } return false; } + /** + * Applies the parameter values of the Connector's authoritative flow to the managed Parameter Context without changing the + * managed flow, and captures the resulting parameter context and secret references. + * + * @return the captured snapshot, or {@code null} if the parameter values could not be applied + */ + private ConnectorFlowSnapshot fillParametersFromActiveFlow(final Bundle managedFlowBundle) { + try { + final VersionedExternalFlow activeFlow = resolveAuthoritativeFlow(); + if (activeFlow.getParameterContexts() != null) { + final ConnectorParameterLookup parameterLookup = new ConnectorParameterLookup(activeFlow.getParameterContexts().values(), initializationContext.getAssetManager()); + activeFlowContext.getParameterContext().updateParameters(parameterLookup.getParameterValues()); + } + + return snapshotMapper.capture(activeFlowContext, managedFlowBundle, initializationContext.getSecretsManager()); + } catch (final Exception e) { + logger.warn("{} failed to fill the managed Parameter Context from its authoritative flow; components that reference parameters may be invalid", this, e); + return null; + } + } + @Override public void restorePersistedManagedFlow(final VersionedConnector persisted) { if (!extensionMissing) { 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 4fc9b3ae6034..1721281ec540 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 @@ -896,22 +896,7 @@ private void waitForState(final ConnectorNode connector, final Set evolutionFuture; volatile int remainingApplyFailures; volatile int remainingStartFailures; + volatile boolean failStepConfigured; + volatile VersionedParameterContext activeFlowParameterContext; + volatile boolean failActiveFlow; final AtomicInteger startCalls = new AtomicInteger(); final CountDownLatch hookEntered = new CountDownLatch(1); final CountDownLatch evolutionFuturePublished = new CountDownLatch(1); @@ -55,8 +60,15 @@ public VersionedExternalFlow getInitialFlow() { @Override public VersionedExternalFlow getActiveFlow(final FlowContext flowContext) { + if (failActiveFlow) { + throw new IllegalStateException("Intentional active flow failure"); + } + final VersionedExternalFlow flow = new VersionedExternalFlow(); flow.setFlowContents(new VersionedProcessGroup()); + if (activeFlowParameterContext != null) { + flow.setParameterContexts(Map.of(activeFlowParameterContext.getName(), activeFlowParameterContext)); + } return flow; } @@ -89,7 +101,10 @@ public void start(final FlowContext activeContext) throws FlowUpdateException { } @Override - protected void onStepConfigured(final String stepName, final FlowContext workingContext) { + protected void onStepConfigured(final String stepName, final FlowContext workingContext) throws FlowUpdateException { + if (failStepConfigured) { + throw new FlowUpdateException("Intentional step configuration failure"); + } } @Override diff --git a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java index 4bc2647e842f..3b1d8376658d 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java +++ b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/components/connector/TestStandardConnectorNode.java @@ -112,6 +112,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -1345,6 +1346,10 @@ public void testCommitMigratedConfigurationWritesMergedConfigurationOntoActive() assertEquals(Map.of("propA", new StringLiteralValue("after-migration")), activeStepProperties(connectorNode, "stepA")); // replaceProperties removed propB and introduced propB-renamed. assertEquals(Map.of("propB-renamed", new StringLiteralValue("after-migration")), activeStepProperties(connectorNode, "stepB")); + + // Flow saves write the active configuration from the authoritative snapshot, so it must hold the migrated configuration. + final ConnectorConfiguration snapshotConfiguration = connectorNode.getAuthoritativeFlowSnapshot().activeConfiguration(); + assertEquals(Map.of("propA", new StringLiteralValue("after-migration")), snapshotConfiguration.getNamedStepConfiguration("stepA").configuration().getPropertyValues()); } @Test @@ -2608,7 +2613,7 @@ public void testStartRefusedWhileUpgradePending() throws Exception { } @Test - public void testRestorePendingFlowEvolutionAdoptsSnapshotWhenRestoreFails() throws Exception { + public void testRestorePendingFlowEvolutionAdoptsSnapshotWhenRestoreOrConfigurationFails() throws Exception { final StandardConnectorNode connectorNode = createConnectorNode(new FlowEvolutionHookConnector()); doThrow(new IllegalStateException("Restore failed")).when(managedProcessGroup) .restoreFlowPreservingIdentifiers(any(VersionedExternalFlow.class), eq(ResumeComponentState.RESUME_AS_PERSISTED)); @@ -2635,6 +2640,21 @@ public void testRestorePendingFlowEvolutionAdoptsSnapshotWhenRestoreFails() thro assertEquals(outgoingSnapshotBundle(), snapshot.bundle()); final ConnectorValueReference activeGreeting = snapshot.activeConfiguration().getNamedStepConfiguration("settings").configuration().getPropertyValue("Greeting"); assertEquals(new StringLiteralValue("Welcome"), activeGreeting); + + // The upgraded Connector rejects the persisted working configuration after the pre-upgrade flow was restored + final FlowEvolutionHookConnector rejectingConnector = new FlowEvolutionHookConnector(); + rejectingConnector.failStepConfigured = true; + final StandardConnectorNode rejectingNode = createConnectorNode(rejectingConnector); + doNothing().when(managedProcessGroup).restoreFlowPreservingIdentifiers(any(VersionedExternalFlow.class), eq(ResumeComponentState.RESUME_AS_PERSISTED)); + + assertThrows(FlowUpdateException.class, () -> rejectingNode.restorePendingFlowEvolution(persisted, List.of(activeStep), List.of(activeStep))); + + assertTrue(rejectingNode.isPendingFlowEvolution()); + final ConnectorFlowSnapshot rejectedSnapshot = rejectingNode.getAuthoritativeFlowSnapshot(); + assertSame(persistedGroup, rejectedSnapshot.flow()); + assertEquals(outgoingSnapshotBundle(), rejectedSnapshot.bundle()); + final ConnectorValueReference rejectedGreeting = rejectedSnapshot.activeConfiguration().getNamedStepConfiguration("settings").configuration().getPropertyValue("Greeting"); + assertEquals(new StringLiteralValue("Welcome"), rejectedGreeting); } private static VersionedConnectorValueReference versionedSecretReference(final SecretReference secretReference) { @@ -2669,6 +2689,51 @@ public void testRestorePendingFlowEvolutionRestoresDerivedSensitiveParameter() t assertTrue(connectorNode.isPendingFlowEvolution()); } + @Test + public void testRestorePendingFlowEvolutionFillsParametersMissingFromLegacySave() throws Exception { + // A Troubleshooting group saved before the managed Parameter Context was persisted is attributed to the stored Connector bundle + final VersionedProcessGroup persistedGroup = flowGroup("pre-upgrade"); + final VersionedConnector persisted = new VersionedConnector(); + persisted.setManagedProcessGroup(persistedGroup); + persisted.setBundle(outgoingSnapshotBundle()); + + final VersionedParameter greeting = new VersionedParameter(); + greeting.setName("Greeting"); + greeting.setValue("Welcome"); + greeting.setSensitive(false); + final VersionedParameterContext activeFlowParameters = new VersionedParameterContext(); + activeFlowParameters.setName("Active Flow Parameters"); + activeFlowParameters.setParameters(Set.of(greeting)); + final FlowEvolutionHookConnector connector = new FlowEvolutionHookConnector(); + connector.activeFlowParameterContext = activeFlowParameters; + final StandardConnectorNode connectorNode = createConnectorNode(connector); + clearInvocations(parameterContextFacade); + + assertTrue(connectorNode.restorePendingFlowEvolution(persisted, List.of(), List.of())); + + final ArgumentCaptor> valuesCaptor = ArgumentCaptor.forClass(Collection.class); + verify(parameterContextFacade).updateParameters(valuesCaptor.capture()); + final ParameterValue filledValue = valuesCaptor.getValue().iterator().next(); + assertEquals("Greeting", filledValue.getName()); + assertEquals("Welcome", filledValue.getValue()); + assertTrue(connectorNode.isPendingFlowEvolution()); + final ConnectorFlowSnapshot snapshot = connectorNode.getAuthoritativeFlowSnapshot(); + assertSame(persistedGroup, snapshot.flow()); + assertEquals(outgoingSnapshotBundle(), snapshot.bundle()); + + // An active flow that cannot be built leaves the parameters unfilled and the restored upgrade pending + final FlowEvolutionHookConnector failingConnector = new FlowEvolutionHookConnector(); + failingConnector.failActiveFlow = true; + final StandardConnectorNode failingNode = createConnectorNode(failingConnector); + clearInvocations(parameterContextFacade); + + assertTrue(failingNode.restorePendingFlowEvolution(persisted, List.of(), List.of())); + + verify(parameterContextFacade, never()).updateParameters(any()); + assertTrue(failingNode.isPendingFlowEvolution()); + assertSame(persistedGroup, failingNode.getAuthoritativeFlowSnapshot().flow()); + } + private static VersionedProcessGroup flowGroup(final String name) { final VersionedProcessGroup group = new VersionedProcessGroup(); group.setName(name); diff --git a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorVersionedFlowMigrationRestartIT.java b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorVersionedFlowMigrationRestartIT.java index e659e9f2ee25..a2bb00ad7dc9 100644 --- a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorVersionedFlowMigrationRestartIT.java +++ b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/connectors/ConnectorVersionedFlowMigrationRestartIT.java @@ -28,12 +28,15 @@ import org.apache.nifi.web.api.entity.FlowRegistryClientEntity; import org.apache.nifi.web.api.entity.MigrationRequestEntity; import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity; +import org.apache.nifi.web.api.entity.ProcessorEntity; import org.junit.jupiter.api.Test; import java.io.File; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -142,17 +145,39 @@ public void testMigrateActionStaysDisallowedAfterMigrationAndAcrossRestart() thr final ConnectorEntity connector = getClientUtil().createConnector("MigrationTargetConnector"); final String connectorId = connector.getId(); + // Restarting before the migration gives the Connector an authoritative flow snapshot, so later flow saves write the Connector from that snapshot + getNiFiInstance().stop(); + getNiFiInstance().start(); + setupClient(); + final MigrationRequestEntity requestEntity = getClientUtil().startMigrationFromLocalSource(connectorId, sourceFixture.processGroup().getId()); getClientUtil().waitForMigrationSuccess(connectorId, requestEntity.getRequest().getRequestId()); + final String managedGroupId = getNifiClient().getConnectorClient().getConnector(connectorId).getComponent().getManagedProcessGroupId(); + final String migratedCountProcessorId = getProcessorId(connectorId, managedGroupId, "StatefulCountProcessor"); + getNiFiInstance().stop(); getNiFiInstance().start(); setupClient(); // After restart the framework rebuilds the Connector from its persisted configuration. MigrationTargetConnector // records the migrated flow's configuration as its own configuration properties and rebuilds the managed - // Process Group from those properties inside applyUpdate(...); the initial-flow check must therefore still - // report the Connector as modified and MIGRATE must remain disallowed. + // Process Group from those properties inside applyUpdate(...); the migrated processor must still be present, + // the initial-flow check must still report the Connector as modified, and MIGRATE must remain disallowed. + final String managedGroupIdAfterRestart = getNifiClient().getConnectorClient().getConnector(connectorId).getComponent().getManagedProcessGroupId(); + final Set processorsAfterRestart = getNifiClient().getConnectorClient().getFlow(connectorId, managedGroupIdAfterRestart).getProcessGroupFlow().getFlow().getProcessors(); + final List processorTypesAfterRestart = new ArrayList<>(); + if (processorsAfterRestart != null) { + for (final ProcessorEntity processor : processorsAfterRestart) { + processorTypesAfterRestart.add(processor.getComponent().getType()); + } + } + + assertTrue(processorTypesAfterRestart.stream().anyMatch(type -> type.endsWith("StatefulCountProcessor")), + "Managed flow after restart lacks the migrated StatefulCountProcessor, so it was rebuilt from the pre-migration configuration and the migration was lost; processor types: %s" + .formatted(processorTypesAfterRestart)); + assertEquals(migratedCountProcessorId, getProcessorId(connectorId, managedGroupIdAfterRestart, "StatefulCountProcessor")); + final ConnectorActionDTO migrateAfterRestart = findMigrateAction(getNifiClient().getConnectorClient().getConnector(connectorId)); assertNotNull(migrateAfterRestart, "MIGRATE action must remain present after a restart"); assertEquals(Boolean.FALSE, migrateAfterRestart.getAllowed(), From 71b6490dd7df33b6cb693855100407dfb1376849 Mon Sep 17 00:00:00 2001 From: Bob Paulin Date: Fri, 20 Nov 2026 11:40:15 -0600 Subject: [PATCH 5/5] NIFI-16477: Read bundle from the coordinator's local connector - Add NiFiServiceFacade.getConnectorBundle, which reads the loaded bundle with LOCAL_ONLY and without filtering by permissions - Fill expectedBundle on every clustered START, including requests from users who can only operate the Connector - Stop START from syncing the coordinator alone with the configuration provider --- .../java/org/apache/nifi/web/NiFiServiceFacade.java | 9 +++++++++ .../apache/nifi/web/StandardNiFiServiceFacade.java | 6 ++++++ .../org/apache/nifi/web/api/ConnectorResource.java | 11 ++++------- .../apache/nifi/web/api/TestConnectorResource.java | 10 ++++------ 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java index f862c712cbce..c1810d4cff88 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/NiFiServiceFacade.java @@ -207,6 +207,15 @@ public interface NiFiServiceFacade { ConnectorEntity getConnector(String id, boolean clusterNodeRequest); + /** + * Returns the bundle of the Connector loaded on this node, without synchronizing with the configuration provider and + * without filtering by the user's permissions. For use in replicated requests only, never in a client response. + * + * @param id the Connector id + * @return the loaded bundle + */ + BundleDTO getConnectorBundle(String id); + void verifyUpdateConnector(ConnectorDTO connectorDTO); ConnectorEntity updateConnector(Revision revision, ConnectorDTO connectorDTO); diff --git a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java index 9df46606a8b2..529dbca8be94 100644 --- a/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java +++ b/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java @@ -3769,6 +3769,12 @@ public ConnectorEntity getConnector(final String id, final boolean clusterNodeRe return entity; } + @Override + public BundleDTO getConnectorBundle(final String id) { + final ConnectorNode connector = connectorDAO.getConnector(id, ConnectorSyncMode.LOCAL_ONLY); + return dtoFactory.createBundleDto(connector.getBundleCoordinate()); + } + @Override public void verifyUpdateConnector(final ConnectorDTO connectorDTO) { // Run-status verification shares this method. Loading the provider here would apply an external edit that 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 5a5657a68eb9..3063a761fe0d 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 @@ -730,15 +730,12 @@ public Response updateRunStatus( /** * Fills the coordinator's loaded bundle onto the run-status request so each node can reject a START in the - * validation phase when its own loaded bundle differs. Avoids an extra replicated GET. + * validation phase when its own loaded bundle differs. Avoids an extra replicated GET. The bundle is read from the + * in-memory Connector without a provider sync or a permission filter, so every START carries it and every node + * compares the same in-memory state. */ private void populateExpectedBundle(final String connectorId, final ConnectorRunStatusEntity requestRunStatus) { - final ConnectorEntity localConnector = serviceFacade.getConnector(connectorId); - if (localConnector == null || localConnector.getComponent() == null || localConnector.getComponent().getBundle() == null) { - return; - } - - requestRunStatus.setExpectedBundle(localConnector.getComponent().getBundle()); + requestRunStatus.setExpectedBundle(serviceFacade.getConnectorBundle(connectorId)); } /** 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 24b6a8cf08d7..4936af9376ca 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 @@ -538,7 +538,7 @@ public void testUpdateRunStatus() { } assertNull(requestEntity.getExpectedBundle()); - verify(serviceFacade, never()).getConnector(CONNECTOR_ID); + verify(serviceFacade, never()).getConnectorBundle(CONNECTOR_ID); verify(serviceFacade).verifyUpdateConnector(any(ConnectorDTO.class)); verify(serviceFacade).scheduleConnector(any(Revision.class), eq(CONNECTOR_ID), eq(ScheduledState.RUNNING)); } @@ -578,23 +578,21 @@ public void testUpdateRunStatusWithNullRevision() { @Test public void testUpdateRunStatusReplicateFillsExpectedBundleForClusterStart() { final ConnectorRunStatusEntity requestEntity = createConnectorRunStatusEntity(); - final ConnectorEntity localConnector = createConnectorEntity(); final BundleDTO localBundle = new BundleDTO("org.apache.nifi", "nifi-test-nar", "1.0.0"); - localConnector.getComponent().setBundle(localBundle); final Response replicatedResponse = Response.ok().build(); final ConnectorResource spyResource = spy(connectorResource); doReturn(true).when(spyResource).isReplicateRequest(); doReturn(ApplicationResource.ReplicationTarget.CLUSTER_NODES).when(spyResource).getReplicationTarget(); doReturn(replicatedResponse).when(spyResource).replicate(eq(HttpMethod.PUT), any(ConnectorRunStatusEntity.class)); - when(serviceFacade.getConnector(CONNECTOR_ID)).thenReturn(localConnector); + when(serviceFacade.getConnectorBundle(CONNECTOR_ID)).thenReturn(localBundle); try (Response response = spyResource.updateRunStatus(CONNECTOR_ID, requestEntity)) { assertEquals(200, response.getStatus()); } assertEquals(localBundle, requestEntity.getExpectedBundle()); - verify(serviceFacade).getConnector(CONNECTOR_ID); + verify(serviceFacade, never()).getConnector(CONNECTOR_ID); verify(spyResource).replicate(eq(HttpMethod.PUT), same(requestEntity)); verify(serviceFacade, never()).scheduleConnector(any(Revision.class), anyString(), any(ScheduledState.class)); } @@ -614,7 +612,7 @@ public void testUpdateRunStatusReplicateDoesNotFillExpectedBundleForStop() { } assertNull(requestEntity.getExpectedBundle()); - verify(serviceFacade, never()).getConnector(CONNECTOR_ID); + verify(serviceFacade, never()).getConnectorBundle(CONNECTOR_ID); verify(spyResource, never()).getReplicationTarget(); }