Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions nifi-docs/src/main/asciidoc/developer-guide.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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 <<connector_applying_upgraded_flow>>.

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 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

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. 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.

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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<ConnectorActionDTO> getAvailableActions() {
return availableActions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}
}


Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -41,30 +49,71 @@ public class ClusteredConnectorRequestReplicator implements ConnectorRequestRepl
private static final String GET = "GET";

private final Supplier<RequestReplicator> requestReplicatorSupplier;
private final Supplier<ClusterCoordinator> clusterCoordinatorSupplier;
private final String replicationScheme;

public ClusteredConnectorRequestReplicator(final Supplier<RequestReplicator> requestReplicatorSupplier, final boolean httpsEnabled) {
public ClusteredConnectorRequestReplicator(final Supplier<RequestReplicator> requestReplicatorSupplier, final Supplier<ClusterCoordinator> 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5] Running verifyClusterMembership here changes the behavior of every Connector update, not just evolutions. getState is what waitForState uses for ordinary applyUpdate calls, and waitForState now retries ConnectorClusterUnavailableException every second with no limit (line 902).

After a full cluster restart, the coordinator restores the nodes it knew about and marks each one DISCONNECTED with NOT_YET_CONNECTED until it comes back (NodeClusterCoordinator.recoverState). If one node never returns and nobody removes it from the cluster, then every Connector update:

  1. is still accepted once the user acknowledges the disconnected node,
  2. stops the Connector's flow in prepareForUpdate,
  3. then waits in PREPARING_FOR_UPDATE forever, because this check keeps throwing.

Before this change, getState simply replicated to the connected nodes. If the waiting is meant for an evolution that resumes during startup, could ordinary updates keep the old behavior (or stop waiting after some time), with the strict check used only on the evolution path?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5] Agreed, that's a real hang. The membership wait only exists for an evolution that resumes during startup, and that path already settles membership in the drain barrier: getFlowEvolutionStatus waits for joining nodes and fails on any node that isn't connected, and runFlowEvolution always passes it before completeUpdate. So getState doesn't need the check on either path. I've restored its previous behavior: it replicates to the connected nodes, and waitForState no longer retries when the cluster is unavailable, so an ordinary update fails to UPDATE_FAILED as before instead of waiting in PREPARING_FOR_UPDATE. The strict membership check now applies only to the flow evolution barrier.

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();
if (requireAllConnected) {
verifyClusterMembership(connectorId);
}

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());
Expand All @@ -77,10 +126,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);
}
Expand All @@ -93,19 +142,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) 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 (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) {
}
Expand Down
Loading
Loading