markap14 commented on code in PR #11914:
URL: https://github.com/apache/nifi/pull/11914#discussion_r4682586252


##########
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:
   [claude-opus-5.5] Agreed @exceptionfactory. The test now checks only that 
the failure reason names each node without a record of the drain, in 
6dd48e06b16.



##########
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:
   [claude-opus-5.5] Simplified in 6dd48e06b16 @exceptionfactory. The test now 
checks only that the merged failure reason names both nodes that failed.



##########
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:
   [claude-opus-5.5] Good point @exceptionfactory. Only the calls to the 
Service Facade in a standalone instance need the current user, because the 
drain request it creates includes the details of a component only if the user 
can read that component. A replicated request is given the user directly. In 
6dd48e06b16 the user is now set only around those two Service Facade calls, 
with a comment explaining why.



##########
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:
   [claude-opus-5.5] Thanks @exceptionfactory, each drain check now creates its 
`NiFiAuthenticationToken` once in its constructor and reuses it, in 6dd48e06b16.



##########
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:
   [claude-opus-5.5] Agreed @exceptionfactory. In 6dd48e06b16 an HTTP 403 from 
the replicated request now stops the monitor from watching the drain, as a 404 
does, and logs a warning that another user must end the drain. 
`ProcessGroupDrainMonitorTest` now covers this case.



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

Reply via email to