exceptionfactory commented on code in PR #11914: URL: https://github.com/apache/nifi/pull/11914#discussion_r4672267170
########## nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/util/ProcessGroupDrainMonitor.java: ########## @@ -0,0 +1,233 @@ +/* + * 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.web.util; + +import jakarta.ws.rs.HttpMethod; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response.Status; +import org.apache.nifi.authorization.user.NiFiUser; +import org.apache.nifi.authorization.user.NiFiUserDetails; +import org.apache.nifi.cluster.coordination.ClusterCoordinator; +import org.apache.nifi.cluster.coordination.http.replication.RequestReplicator; +import org.apache.nifi.cluster.coordination.node.NodeConnectionState; +import org.apache.nifi.cluster.exception.NoClusterCoordinatorException; +import org.apache.nifi.cluster.manager.NodeResponse; +import org.apache.nifi.cluster.protocol.NodeIdentifier; +import org.apache.nifi.groups.ProcessGroupDrainState; +import org.apache.nifi.web.NiFiServiceFacade; +import org.apache.nifi.web.ResourceNotFoundException; +import org.apache.nifi.web.api.dto.ProcessGroupDrainRequestDTO; +import org.apache.nifi.web.api.entity.ProcessGroupDrainRequestEntity; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.context.SecurityContextHolder; + +import java.io.IOException; +import java.net.URI; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Ends a drain of a Process Group once the data has left the group, so that the drain ends even if no client is watching it. Only the node that + * received the request to begin the drain watches it, acting as the user who began it. A FlowFile that is being moved between nodes by a + * load-balanced connection can be missed by a single check, so the drain is ended only after two empty checks in a row. A node that is not + * connected does not report its data, so no check counts while any node is not connected. + */ +public class ProcessGroupDrainMonitor { + private static final Logger logger = LoggerFactory.getLogger(ProcessGroupDrainMonitor.class); + + private static final long CHECK_INTERVAL_SECONDS = 2; + private static final int EMPTY_CHECKS_REQUIRED = 2; + + private final ClusterCoordinator clusterCoordinator; + private final RequestReplicator requestReplicator; + private final NiFiServiceFacade serviceFacade; + private final ScheduledExecutorService executor; + + /** + * @param clusterCoordinator the cluster coordinator, or null if this instance is not part of a cluster + * @param requestReplicator the request replicator, or null if this instance is not part of a cluster + */ + public ProcessGroupDrainMonitor(final ClusterCoordinator clusterCoordinator, final RequestReplicator requestReplicator, final NiFiServiceFacade serviceFacade) { + this.clusterCoordinator = clusterCoordinator; + this.requestReplicator = requestReplicator; + this.serviceFacade = serviceFacade; + this.executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + final Thread thread = new Thread(runnable, "Process Group Drain Monitor"); + thread.setDaemon(true); + return thread; + }); + } + + public void watch(final String processGroupId, final String drainRequestId, final NiFiUser user) { + schedule(new DrainCheck(null, processGroupId, drainRequestId, user)); + } + + /** + * @param drainRequestUri the URI of the drain request on this node, which is replicated across the cluster to check and end the drain + */ + public void watch(final URI drainRequestUri, final String processGroupId, final String drainRequestId, final NiFiUser user) { + schedule(new DrainCheck(drainRequestUri, processGroupId, drainRequestId, user)); + } + + public void shutdown() { + executor.shutdownNow(); + } + + private void schedule(final DrainCheck check) { + if (!executor.isShutdown()) { + executor.schedule(check, CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS); + } + } + + enum CheckResult { + CHECK_AGAIN, + STOP_CHECKING + } + + /** + * Each check is run by the single monitor thread, so the number of empty checks needs no synchronization. + */ + class DrainCheck implements Runnable { + private final URI drainRequestUri; + private final String processGroupId; + private final String drainRequestId; + private final NiFiUser user; + private int emptyCheckCount = 0; + + DrainCheck(final URI drainRequestUri, final String processGroupId, final String drainRequestId, final NiFiUser user) { + this.drainRequestUri = drainRequestUri; + this.processGroupId = processGroupId; + this.drainRequestId = drainRequestId; + this.user = user; + } + + @Override + public void run() { + if (check() == CheckResult.CHECK_AGAIN) { + schedule(this); + } + } + + CheckResult check() { + SecurityContextHolder.getContext().setAuthentication(new NiFiAuthenticationToken(new NiFiUserDetails(user))); Review Comment: It also looks like the `NiFiAuthenticationToken` could be constructed once and reused, instead of on every invocation of `check()` ########## nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/endpoints/ProcessGroupDrainRequestEndpointMergerTest.java: ########## @@ -0,0 +1,159 @@ +/* + * 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.endpoints; + +import org.apache.nifi.cluster.protocol.NodeIdentifier; +import org.apache.nifi.web.api.dto.DrainBlockingComponentDTO; +import org.apache.nifi.web.api.dto.ProcessGroupDrainRequestDTO; +import org.apache.nifi.web.api.entity.ProcessGroupDrainRequestEntity; +import org.junit.jupiter.api.Test; + +import java.net.URI; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ProcessGroupDrainRequestEndpointMergerTest { + private static final String DRAINING = "DRAINING"; + private static final String FAILED = "FAILED"; + private static final String ENDED = "ENDED"; + private static final String PROCESS_GROUP_ID = "abcdef00-abcd-abcd-abcd-abcdef000000"; + private static final String DRAIN_REQUEST_ID = "00000000-0000-0000-0000-000000000001"; + private static final String DRAIN_REQUESTS_URI = "/nifi-api/process-groups/" + PROCESS_GROUP_ID + "/drain-requests"; + private static final String DRAIN_REQUEST_URI = DRAIN_REQUESTS_URI + "/" + DRAIN_REQUEST_ID; + private static final long BYTES_PER_FLOWFILE = 1000L; + + private final ProcessGroupDrainRequestEndpointMerger merger = new ProcessGroupDrainRequestEndpointMerger(); + + @Test + void testCanHandle() { + assertTrue(merger.canHandle(URI.create(DRAIN_REQUESTS_URI), "POST")); + assertTrue(merger.canHandle(URI.create(DRAIN_REQUEST_URI), "GET")); + assertTrue(merger.canHandle(URI.create(DRAIN_REQUEST_URI), "DELETE")); + assertFalse(merger.canHandle(URI.create(DRAIN_REQUESTS_URI), "GET")); + assertFalse(merger.canHandle(URI.create(DRAIN_REQUEST_URI), "POST")); + } + + @Test + void testMergeSumsCountsAndSizes() { + final ProcessGroupDrainRequestDTO merged = merge(createRequest(DRAINING, 10, 0), createRequest(DRAINING, 30, 20)); + assertEquals(40, merged.getOriginalCount()); + assertEquals(40 * BYTES_PER_FLOWFILE, merged.getOriginalSize()); + assertEquals(20, merged.getCurrentCount()); + assertEquals(20 * BYTES_PER_FLOWFILE, merged.getCurrentSize()); + assertTrue(merged.getPrepared()); + + // The drain is prepared only once it is prepared on every node + final ProcessGroupDrainRequestDTO unpreparedRequest = createRequest(DRAINING, 30, 0); + unpreparedRequest.setPrepared(false); + assertFalse(merge(createRequest(DRAINING, 10, 0), unpreparedRequest).getPrepared()); + } + + @Test + void testMergeStateAndFailureReason() { + assertEquals(ENDED, merge(createRequest(ENDED, 0, 0), createRequest(ENDED, 0, 0)).getState()); + + final ProcessGroupDrainRequestDTO draining = merge(createRequest(ENDED, 0, 0), createRequest(DRAINING, 0, 0)); + assertEquals(DRAINING, draining.getState()); + assertNull(draining.getFailureReason()); + + final ProcessGroupDrainRequestDTO secondNodeRequest = createRequest(FAILED, 0, 0); + secondNodeRequest.setFailureReason("Could not start processor"); + final ProcessGroupDrainRequestDTO thirdNodeRequest = createRequest(FAILED, 0, 0); + thirdNodeRequest.setFailureReason("Could not enable service"); + + final ProcessGroupDrainRequestDTO failed = merge(createRequest(DRAINING, 0, 0), secondNodeRequest, thirdNodeRequest); + assertEquals(FAILED, failed.getState()); + assertEquals("localhost:8002 -- Could not start processor\nlocalhost:8003 -- Could not enable service", failed.getFailureReason()); Review Comment: Recommend removing or simplifying this assertion to avoid tight coupling to the exception message ########## nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/dao/impl/StandardProcessGroupDAOTest.java: ########## @@ -133,4 +139,35 @@ void testGetProcessGroupWithNonExistentIdThrows() { processGroupDAO.getProcessGroup(NON_EXISTENT_ID) ); } + + @Test + void testEndDrainEndsOnlyTheRequestedDrain() { + final ProcessGroupDrain drain = mock(ProcessGroupDrain.class); + when(drain.getIdentifier()).thenReturn("current-drain"); + when(drain.getProcessGroup()).thenReturn(rootGroup); + when(rootGroup.getDrain()).thenReturn(Optional.of(drain)); + when(rootGroup.endDrain()).thenReturn(Optional.of(drain)); + + // A request to end an earlier drain of the group does not end the drain that the group has now + assertEquals(Optional.empty(), processGroupDAO.endDrain(ROOT_GROUP_ID, "earlier-drain")); + verify(rootGroup, never()).endDrain(); + + assertEquals(Optional.of(drain), processGroupDAO.endDrain(ROOT_GROUP_ID, "current-drain")); + verify(rootGroup).endDrain(); + } + + @Test + void testVerifyBeginDrainRejectsConnectorManagedGroup() { + when(owningConnector.getCurrentState()).thenReturn(ConnectorState.TROUBLESHOOTING); + when(connectorManagedGroup.findOwningConnectorIdentifier()).thenReturn(Optional.of("connector-1")); Review Comment: As above, recommend declaring `connector-1` once as reusing the variable in the assertion ########## nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/web/dao/impl/StandardProcessGroupDAOTest.java: ########## @@ -133,4 +139,35 @@ void testGetProcessGroupWithNonExistentIdThrows() { processGroupDAO.getProcessGroup(NON_EXISTENT_ID) ); } + + @Test + void testEndDrainEndsOnlyTheRequestedDrain() { + final ProcessGroupDrain drain = mock(ProcessGroupDrain.class); + when(drain.getIdentifier()).thenReturn("current-drain"); Review Comment: Recommend declaring `current-drain` once and reusing in the assertion ########## nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/util/ProcessGroupDrainMonitor.java: ########## @@ -0,0 +1,233 @@ +/* + * 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.web.util; + +import jakarta.ws.rs.HttpMethod; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response.Status; +import org.apache.nifi.authorization.user.NiFiUser; +import org.apache.nifi.authorization.user.NiFiUserDetails; +import org.apache.nifi.cluster.coordination.ClusterCoordinator; +import org.apache.nifi.cluster.coordination.http.replication.RequestReplicator; +import org.apache.nifi.cluster.coordination.node.NodeConnectionState; +import org.apache.nifi.cluster.exception.NoClusterCoordinatorException; +import org.apache.nifi.cluster.manager.NodeResponse; +import org.apache.nifi.cluster.protocol.NodeIdentifier; +import org.apache.nifi.groups.ProcessGroupDrainState; +import org.apache.nifi.web.NiFiServiceFacade; +import org.apache.nifi.web.ResourceNotFoundException; +import org.apache.nifi.web.api.dto.ProcessGroupDrainRequestDTO; +import org.apache.nifi.web.api.entity.ProcessGroupDrainRequestEntity; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.context.SecurityContextHolder; + +import java.io.IOException; +import java.net.URI; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Ends a drain of a Process Group once the data has left the group, so that the drain ends even if no client is watching it. Only the node that + * received the request to begin the drain watches it, acting as the user who began it. A FlowFile that is being moved between nodes by a + * load-balanced connection can be missed by a single check, so the drain is ended only after two empty checks in a row. A node that is not + * connected does not report its data, so no check counts while any node is not connected. + */ +public class ProcessGroupDrainMonitor { + private static final Logger logger = LoggerFactory.getLogger(ProcessGroupDrainMonitor.class); + + private static final long CHECK_INTERVAL_SECONDS = 2; + private static final int EMPTY_CHECKS_REQUIRED = 2; + + private final ClusterCoordinator clusterCoordinator; + private final RequestReplicator requestReplicator; + private final NiFiServiceFacade serviceFacade; + private final ScheduledExecutorService executor; + + /** + * @param clusterCoordinator the cluster coordinator, or null if this instance is not part of a cluster + * @param requestReplicator the request replicator, or null if this instance is not part of a cluster + */ + public ProcessGroupDrainMonitor(final ClusterCoordinator clusterCoordinator, final RequestReplicator requestReplicator, final NiFiServiceFacade serviceFacade) { + this.clusterCoordinator = clusterCoordinator; + this.requestReplicator = requestReplicator; + this.serviceFacade = serviceFacade; + this.executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + final Thread thread = new Thread(runnable, "Process Group Drain Monitor"); + thread.setDaemon(true); + return thread; + }); + } + + public void watch(final String processGroupId, final String drainRequestId, final NiFiUser user) { + schedule(new DrainCheck(null, processGroupId, drainRequestId, user)); + } + + /** + * @param drainRequestUri the URI of the drain request on this node, which is replicated across the cluster to check and end the drain + */ + public void watch(final URI drainRequestUri, final String processGroupId, final String drainRequestId, final NiFiUser user) { + schedule(new DrainCheck(drainRequestUri, processGroupId, drainRequestId, user)); + } + + public void shutdown() { + executor.shutdownNow(); + } + + private void schedule(final DrainCheck check) { + if (!executor.isShutdown()) { + executor.schedule(check, CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS); + } + } + + enum CheckResult { + CHECK_AGAIN, + STOP_CHECKING + } + + /** + * Each check is run by the single monitor thread, so the number of empty checks needs no synchronization. + */ + class DrainCheck implements Runnable { + private final URI drainRequestUri; + private final String processGroupId; + private final String drainRequestId; + private final NiFiUser user; + private int emptyCheckCount = 0; + + DrainCheck(final URI drainRequestUri, final String processGroupId, final String drainRequestId, final NiFiUser user) { + this.drainRequestUri = drainRequestUri; + this.processGroupId = processGroupId; + this.drainRequestId = drainRequestId; + this.user = user; + } + + @Override + public void run() { + if (check() == CheckResult.CHECK_AGAIN) { + schedule(this); + } + } + + CheckResult check() { + SecurityContextHolder.getContext().setAuthentication(new NiFiAuthenticationToken(new NiFiUserDetails(user))); Review Comment: This type of approach to setting the current user makes tracing difficult in terms of where it is needed. At minimum, I recommend adding a comment what exactly which calls need this set. Is it possible to set this closer to where it is used? ########## nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/util/ProcessGroupDrainMonitor.java: ########## @@ -0,0 +1,233 @@ +/* + * 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.web.util; + +import jakarta.ws.rs.HttpMethod; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response.Status; +import org.apache.nifi.authorization.user.NiFiUser; +import org.apache.nifi.authorization.user.NiFiUserDetails; +import org.apache.nifi.cluster.coordination.ClusterCoordinator; +import org.apache.nifi.cluster.coordination.http.replication.RequestReplicator; +import org.apache.nifi.cluster.coordination.node.NodeConnectionState; +import org.apache.nifi.cluster.exception.NoClusterCoordinatorException; +import org.apache.nifi.cluster.manager.NodeResponse; +import org.apache.nifi.cluster.protocol.NodeIdentifier; +import org.apache.nifi.groups.ProcessGroupDrainState; +import org.apache.nifi.web.NiFiServiceFacade; +import org.apache.nifi.web.ResourceNotFoundException; +import org.apache.nifi.web.api.dto.ProcessGroupDrainRequestDTO; +import org.apache.nifi.web.api.entity.ProcessGroupDrainRequestEntity; +import org.apache.nifi.web.security.token.NiFiAuthenticationToken; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.context.SecurityContextHolder; + +import java.io.IOException; +import java.net.URI; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Ends a drain of a Process Group once the data has left the group, so that the drain ends even if no client is watching it. Only the node that + * received the request to begin the drain watches it, acting as the user who began it. A FlowFile that is being moved between nodes by a + * load-balanced connection can be missed by a single check, so the drain is ended only after two empty checks in a row. A node that is not + * connected does not report its data, so no check counts while any node is not connected. + */ +public class ProcessGroupDrainMonitor { + private static final Logger logger = LoggerFactory.getLogger(ProcessGroupDrainMonitor.class); + + private static final long CHECK_INTERVAL_SECONDS = 2; + private static final int EMPTY_CHECKS_REQUIRED = 2; + + private final ClusterCoordinator clusterCoordinator; + private final RequestReplicator requestReplicator; + private final NiFiServiceFacade serviceFacade; + private final ScheduledExecutorService executor; + + /** + * @param clusterCoordinator the cluster coordinator, or null if this instance is not part of a cluster + * @param requestReplicator the request replicator, or null if this instance is not part of a cluster + */ + public ProcessGroupDrainMonitor(final ClusterCoordinator clusterCoordinator, final RequestReplicator requestReplicator, final NiFiServiceFacade serviceFacade) { + this.clusterCoordinator = clusterCoordinator; + this.requestReplicator = requestReplicator; + this.serviceFacade = serviceFacade; + this.executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + final Thread thread = new Thread(runnable, "Process Group Drain Monitor"); + thread.setDaemon(true); + return thread; + }); + } + + public void watch(final String processGroupId, final String drainRequestId, final NiFiUser user) { + schedule(new DrainCheck(null, processGroupId, drainRequestId, user)); + } + + /** + * @param drainRequestUri the URI of the drain request on this node, which is replicated across the cluster to check and end the drain + */ + public void watch(final URI drainRequestUri, final String processGroupId, final String drainRequestId, final NiFiUser user) { + schedule(new DrainCheck(drainRequestUri, processGroupId, drainRequestId, user)); + } + + public void shutdown() { + executor.shutdownNow(); + } + + private void schedule(final DrainCheck check) { + if (!executor.isShutdown()) { + executor.schedule(check, CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS); + } + } + + enum CheckResult { + CHECK_AGAIN, + STOP_CHECKING + } + + /** + * Each check is run by the single monitor thread, so the number of empty checks needs no synchronization. + */ + class DrainCheck implements Runnable { + private final URI drainRequestUri; + private final String processGroupId; + private final String drainRequestId; + private final NiFiUser user; + private int emptyCheckCount = 0; + + DrainCheck(final URI drainRequestUri, final String processGroupId, final String drainRequestId, final NiFiUser user) { + this.drainRequestUri = drainRequestUri; + this.processGroupId = processGroupId; + this.drainRequestId = drainRequestId; + this.user = user; + } + + @Override + public void run() { + if (check() == CheckResult.CHECK_AGAIN) { + schedule(this); + } + } + + CheckResult check() { + SecurityContextHolder.getContext().setAuthentication(new NiFiAuthenticationToken(new NiFiUserDetails(user))); + try { + if (drainRequestUri != null && !clusterCoordinator.getNodeIdentifiers(NodeConnectionState.CONNECTING, NodeConnectionState.DISCONNECTING, + NodeConnectionState.DISCONNECTED, NodeConnectionState.OFFLOADING).isEmpty()) { + logger.debug("Not checking drain {} of Process Group {} because not every node is connected", drainRequestId, processGroupId); + emptyCheckCount = 0; + return CheckResult.CHECK_AGAIN; + } + + final Optional<ProcessGroupDrainRequestDTO> drainRequest = getDrainRequest(); + if (drainRequest.isPresent() && ProcessGroupDrainState.FAILED.name().equals(drainRequest.get().getState())) { + logger.info("Ending drain {} of Process Group {} because it failed: {}", drainRequestId, processGroupId, drainRequest.get().getFailureReason()); + endDrain(); + return CheckResult.STOP_CHECKING; + } + + if (drainRequest.isEmpty() || !ProcessGroupDrainState.DRAINING.name().equals(drainRequest.get().getState())) { + logger.debug("Stopped watching drain {} of Process Group {} because it is no longer draining", drainRequestId, processGroupId); + return CheckResult.STOP_CHECKING; + } + + if (drainRequest.get().getCurrentCount() > 0 || !Boolean.TRUE.equals(drainRequest.get().getPrepared())) { + emptyCheckCount = 0; + return CheckResult.CHECK_AGAIN; + } + + emptyCheckCount++; + if (emptyCheckCount < EMPTY_CHECKS_REQUIRED) { + return CheckResult.CHECK_AGAIN; + } + + logger.info("Ending drain {} of Process Group {} because no FlowFiles were queued in the group for {} checks in a row", drainRequestId, processGroupId, emptyCheckCount); + endDrain(); + return CheckResult.STOP_CHECKING; + } catch (final ResourceNotFoundException e) { + logger.info("Stopped watching drain {} because Process Group {} no longer exists", drainRequestId, processGroupId); + return CheckResult.STOP_CHECKING; + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + return CheckResult.STOP_CHECKING; + } catch (final Throwable t) { + emptyCheckCount = 0; + logger.warn("Failed to check drain {} of Process Group {}; will check again in {} seconds", drainRequestId, processGroupId, CHECK_INTERVAL_SECONDS, t); + return CheckResult.CHECK_AGAIN; + } finally { + SecurityContextHolder.getContext().setAuthentication(null); + } + } + + private Optional<ProcessGroupDrainRequestDTO> getDrainRequest() throws IOException, InterruptedException { + if (drainRequestUri == null) { + return serviceFacade.getProcessGroupDrainRequest(processGroupId, drainRequestId); + } + + final NodeResponse response = replicate(HttpMethod.GET); + if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { + throw new ResourceNotFoundException("Process Group " + processGroupId + " was not found"); + } + + final ProcessGroupDrainRequestEntity entity = (ProcessGroupDrainRequestEntity) response.getUpdatedEntity(); + if (entity == null) { + return Optional.ofNullable(response.getClientResponse().readEntity(ProcessGroupDrainRequestEntity.class).getDrainRequest()); + } + + return Optional.ofNullable(entity.getDrainRequest()); + } + + private void endDrain() throws IOException, InterruptedException { + if (drainRequestUri == null) { + serviceFacade.endProcessGroupDrain(processGroupId, drainRequestId); + return; + } + + replicate(HttpMethod.DELETE); + } + + private NodeResponse replicate(final String method) throws IOException, InterruptedException { + final Map<String, String> headers = new HashMap<>(); + headers.put("content-type", MediaType.APPLICATION_JSON); + + final NodeResponse response; + if (clusterCoordinator.isActiveClusterCoordinator()) { + response = requestReplicator.replicate(user, method, drainRequestUri, Collections.emptyMap(), headers).awaitMergedResponse(); + } else { + final NodeIdentifier coordinatorNode = clusterCoordinator.getElectedActiveCoordinatorNode(); + if (coordinatorNode == null) { + throw new NoClusterCoordinatorException(); + } + + response = requestReplicator.forwardToCoordinator(coordinatorNode, user, method, drainRequestUri, Collections.emptyMap(), headers).awaitMergedResponse(); + } + + final int status = response.getStatus(); + if (status != Status.OK.getStatusCode() && status != Status.NOT_FOUND.getStatusCode()) { Review Comment: What about an HTTP 403, where the user authorization changes? That seems unlikely for a given drain, but calling it out and handling it as a terminal condition, like a 404, seems like a safer approach. ########## nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/test/java/org/apache/nifi/cluster/coordination/http/endpoints/ProcessGroupDrainRequestEndpointMergerTest.java: ########## @@ -0,0 +1,159 @@ +/* + * 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.endpoints; + +import org.apache.nifi.cluster.protocol.NodeIdentifier; +import org.apache.nifi.web.api.dto.DrainBlockingComponentDTO; +import org.apache.nifi.web.api.dto.ProcessGroupDrainRequestDTO; +import org.apache.nifi.web.api.entity.ProcessGroupDrainRequestEntity; +import org.junit.jupiter.api.Test; + +import java.net.URI; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ProcessGroupDrainRequestEndpointMergerTest { + private static final String DRAINING = "DRAINING"; + private static final String FAILED = "FAILED"; + private static final String ENDED = "ENDED"; + private static final String PROCESS_GROUP_ID = "abcdef00-abcd-abcd-abcd-abcdef000000"; + private static final String DRAIN_REQUEST_ID = "00000000-0000-0000-0000-000000000001"; + private static final String DRAIN_REQUESTS_URI = "/nifi-api/process-groups/" + PROCESS_GROUP_ID + "/drain-requests"; + private static final String DRAIN_REQUEST_URI = DRAIN_REQUESTS_URI + "/" + DRAIN_REQUEST_ID; + private static final long BYTES_PER_FLOWFILE = 1000L; + + private final ProcessGroupDrainRequestEndpointMerger merger = new ProcessGroupDrainRequestEndpointMerger(); + + @Test + void testCanHandle() { + assertTrue(merger.canHandle(URI.create(DRAIN_REQUESTS_URI), "POST")); + assertTrue(merger.canHandle(URI.create(DRAIN_REQUEST_URI), "GET")); + assertTrue(merger.canHandle(URI.create(DRAIN_REQUEST_URI), "DELETE")); + assertFalse(merger.canHandle(URI.create(DRAIN_REQUESTS_URI), "GET")); + assertFalse(merger.canHandle(URI.create(DRAIN_REQUEST_URI), "POST")); + } + + @Test + void testMergeSumsCountsAndSizes() { + final ProcessGroupDrainRequestDTO merged = merge(createRequest(DRAINING, 10, 0), createRequest(DRAINING, 30, 20)); + assertEquals(40, merged.getOriginalCount()); + assertEquals(40 * BYTES_PER_FLOWFILE, merged.getOriginalSize()); + assertEquals(20, merged.getCurrentCount()); + assertEquals(20 * BYTES_PER_FLOWFILE, merged.getCurrentSize()); + assertTrue(merged.getPrepared()); + + // The drain is prepared only once it is prepared on every node + final ProcessGroupDrainRequestDTO unpreparedRequest = createRequest(DRAINING, 30, 0); + unpreparedRequest.setPrepared(false); + assertFalse(merge(createRequest(DRAINING, 10, 0), unpreparedRequest).getPrepared()); + } + + @Test + void testMergeStateAndFailureReason() { + assertEquals(ENDED, merge(createRequest(ENDED, 0, 0), createRequest(ENDED, 0, 0)).getState()); + + final ProcessGroupDrainRequestDTO draining = merge(createRequest(ENDED, 0, 0), createRequest(DRAINING, 0, 0)); + assertEquals(DRAINING, draining.getState()); + assertNull(draining.getFailureReason()); + + final ProcessGroupDrainRequestDTO secondNodeRequest = createRequest(FAILED, 0, 0); + secondNodeRequest.setFailureReason("Could not start processor"); + final ProcessGroupDrainRequestDTO thirdNodeRequest = createRequest(FAILED, 0, 0); + thirdNodeRequest.setFailureReason("Could not enable service"); + + final ProcessGroupDrainRequestDTO failed = merge(createRequest(DRAINING, 0, 0), secondNodeRequest, thirdNodeRequest); + assertEquals(FAILED, failed.getState()); + assertEquals("localhost:8002 -- Could not start processor\nlocalhost:8003 -- Could not enable service", failed.getFailureReason()); + } + + @Test + void testMergeBlockingComponents() { + final ProcessGroupDrainRequestDTO firstNodeRequest = createRequest(DRAINING, 10, 10); + firstNodeRequest.setBlockingComponents(List.of(createBlockingComponent("component-b", 1), createBlockingComponent("component-a", 3))); + + final ProcessGroupDrainRequestDTO secondNodeRequest = createRequest(DRAINING, 10, 10); + secondNodeRequest.setBlockingComponents(List.of(createBlockingComponent("component-c", 2), createBlockingComponent("component-a", 4), createBlockingComponent("component-b", 5))); + + // The components are sorted by identifier, so their order does not depend on the order in which the nodes respond + final List<DrainBlockingComponentDTO> blockingComponents = merge(firstNodeRequest, secondNodeRequest).getBlockingComponents(); + assertEquals(List.of("component-a", "component-b", "component-c"), blockingComponents.stream().map(DrainBlockingComponentDTO::getId).toList()); + assertEquals(List.of(7, 6, 2), blockingComponents.stream().map(DrainBlockingComponentDTO::getQueuedCount).toList()); + } + + @Test + void testMergeReportsNodesWithoutRecordAsFailed() { + // A node that has no record of the drain, such as a node that restarted, may still have data queued, so the drain cannot complete + final ProcessGroupDrainRequestDTO merged = merge(null, createRequest(DRAINING, 10, 0), null); + assertEquals(DRAIN_REQUEST_ID, merged.getId()); + assertEquals(FAILED, merged.getState()); + assertEquals(10, merged.getOriginalCount()); + assertEquals("localhost:8001 -- The node has no record of the drain, for example because it restarted, so the FlowFile counts do not include its FlowFiles\n" + + "localhost:8003 -- The node has no record of the drain, for example because it restarted, so the FlowFile counts do not include its FlowFiles", merged.getFailureReason()); Review Comment: Asserting this full reason equality seems brittle since it is derived from exception messages ########## nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/java/org/apache/nifi/processors/tests/system/GenerateFlowFile.java: ########## @@ -101,6 +102,14 @@ public class GenerateFlowFile extends AbstractProcessor { .addValidator(NON_EMPTY_VALIDATOR) .expressionLanguageSupported(NONE) .build(); + static final PropertyDescriptor GATE_FILE = new Builder() + .name("Gate File") + .description("An optional file path. If specified, each invocation waits until this file exists before generating FlowFiles, even if the Processor " + + "is stopped while it waits. This simulates a source that is still waiting for data from an external system when it is asked to stop.") Review Comment: Although this is just a test, `Gate File` is not very intuitive. Maybe something like `Trigger Sleep File` or similar? ########## nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/pg/ProcessGroupDrainIT.java: ########## @@ -0,0 +1,266 @@ +/* + * 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.pg; + +import jakarta.ws.rs.WebApplicationException; +import org.apache.nifi.controller.ScheduledState; +import org.apache.nifi.groups.StatelessGroupScheduledState; +import org.apache.nifi.tests.system.NiFiSystemIT; +import org.apache.nifi.toolkit.client.NiFiClientException; +import org.apache.nifi.web.api.dto.DrainBlockingComponentDTO; +import org.apache.nifi.web.api.dto.ProcessGroupDrainRequestDTO; +import org.apache.nifi.web.api.dto.ProcessGroupDrainSummaryDTO; +import org.apache.nifi.web.api.entity.ConnectionEntity; +import org.apache.nifi.web.api.entity.ProcessGroupEntity; +import org.apache.nifi.web.api.entity.ProcessorEntity; +import org.apache.nifi.web.api.entity.ScheduleComponentsEntity; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; + +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.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +public class ProcessGroupDrainIT extends NiFiSystemIT { + private static final String WRITE_LIFECYCLE_EVENTS = "WriteLifecycleEvents"; + private static final String DRAINING = "DRAINING"; + private static final String ENDED = "ENDED"; + + @Override + protected void destroyFlow() throws NiFiClientException, IOException, InterruptedException { + getClientUtil().endProcessGroupDrains("root"); + super.destroyFlow(); + } + + /** + * Drains a group that has a running source in the group itself and in a child group. The last Processor of the group removes FlowFiles only + * once a gate file exists, so the start/stop rules are checked while data is still queued. The source in the child group is still waiting + * for its own gate file when the drain begins, as a source does while it waits for an external system, so the drain does not end while that + * source can still produce data, even once nothing is queued. Once both gates open, the data flows out and NiFi ends the drain without any + * request from the client. WriteLifecycleEvents records the calls to its {@code @OnDrainInitiated} and {@code @OnDrainCompleted} methods. + * An empty Stateless child group can receive no data, so the drain does not start it. Ending the drain leaves every component as it is, + * and the run states that the drain set are kept when NiFi restarts. + */ + @Test + public void testDrainEmptiesGroupWhileSourcesStayStoppedAndThenEnds() throws NiFiClientException, IOException, InterruptedException { + final File eventFile = new File(getNiFiInstance().getInstanceDirectory(), "drain-lifecycle-events.txt"); + Files.deleteIfExists(eventFile.toPath()); + final File gateFile = createGateFile("drain-gate.txt"); + final File sourceGateFile = createGateFile("drain-source-gate.txt"); + try { + drainGroupWithSourceStillRunning(eventFile, gateFile, sourceGateFile); + } finally { + // The gated source cannot stop until its gate file exists + sourceGateFile.createNewFile(); + } + } + + private void drainGroupWithSourceStillRunning(final File eventFile, final File gateFile, final File sourceGateFile) throws NiFiClientException, IOException, InterruptedException { + final ProcessGroupEntity group = getClientUtil().createProcessGroup("Drained", "root"); + final ProcessorEntity generate = getClientUtil().createProcessor(GENERATE_FLOWFILE, group.getId()); + final ProcessorEntity writeLifecycleEvents = getClientUtil().createProcessor(WRITE_LIFECYCLE_EVENTS, group.getId()); + final ProcessorEntity terminate = getClientUtil().createProcessor(TERMINATE_FLOWFILE, group.getId()); + final ConnectionEntity connection = getClientUtil().createConnection(generate, writeLifecycleEvents, SUCCESS, group.getId()); + final ConnectionEntity gatedConnection = getClientUtil().createConnection(writeLifecycleEvents, terminate, SUCCESS, group.getId()); + getClientUtil().updateProcessorProperties(writeLifecycleEvents, Map.of("Event File", eventFile.getAbsolutePath())); + getClientUtil().updateProcessorProperties(terminate, Map.of("Gate File", gateFile.getAbsolutePath())); Review Comment: Recommend declaring `Gate File` and other properties as static final strings and reusing -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
