This is an automated email from the ASF dual-hosted git repository.

exceptionfactory pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi-api.git


The following commit(s) were added to refs/heads/main by this push:
     new 8aeafdc  NIFI-16574 Add NiFi API support for draining a Process Group 
(#115)
8aeafdc is described below

commit 8aeafdc5f46bf60a91caec42d0006d05b7988508
Author: Mark Payne <[email protected]>
AuthorDate: Tue Dec 1 10:31:02 2026 -0500

    NIFI-16574 Add NiFi API support for draining a Process Group (#115)
    
    Add the OnDrainInitiated and OnDrainCompleted lifecycle annotations so that 
Processors and Controller Services can change their behavior while their 
Process Group is being drained. Add beginDrain and endDrain to 
ProcessGroupLifecycle, and use them in AbstractConnector so that a Connector 
drains its flow in the same way as a Process Group.
    
    Co-authored-by: Cursor <[email protected]>
    Signed-off-by: David Handermann <[email protected]>
---
 .../annotation/lifecycle/OnDrainCompleted.java     | 63 ++++++++++++++++++++
 .../annotation/lifecycle/OnDrainInitiated.java     | 69 ++++++++++++++++++++++
 .../components/connector/AbstractConnector.java    | 55 +++--------------
 .../components/ProcessGroupLifecycle.java          | 30 ++++++++++
 .../connector/TestAbstractConnector.java           | 29 ---------
 5 files changed, 171 insertions(+), 75 deletions(-)

diff --git 
a/src/main/java/org/apache/nifi/annotation/lifecycle/OnDrainCompleted.java 
b/src/main/java/org/apache/nifi/annotation/lifecycle/OnDrainCompleted.java
new file mode 100644
index 0000000..6bd09c8
--- /dev/null
+++ b/src/main/java/org/apache/nifi/annotation/lifecycle/OnDrainCompleted.java
@@ -0,0 +1,63 @@
+/*
+ * 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.annotation.lifecycle;
+
+import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.processor.ProcessContext;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * <p>
+ * Marker annotation a {@link org.apache.nifi.processor.Processor Processor} or
+ * {@link org.apache.nifi.controller.ControllerService ControllerService} 
implementation
+ * can use to indicate that a method should be called when a drain of its 
Process Group ends, so
+ * that the component can return to its normal behavior. A drain may end 
before all of the data in
+ * the group has been processed, for example if it is cancelled. For a given 
drain, this method is
+ * called at most once, and only if the methods marked with {@link 
OnDrainInitiated} were called
+ * for that drain. It is not guaranteed to be called for every drain that 
began with
+ * {@link OnDrainInitiated}, such as when NiFi is restarted during a drain, so 
the component should
+ * not persist anything that depends on a drain being in progress.
+ * </p>
+ *
+ * <p>
+ * The component may be in any lifecycle state when this method is called, and 
the order in which
+ * this method is called relative to other lifecycle methods, such as those 
marked with
+ * {@link OnScheduled}, {@link OnUnscheduled}, and {@link OnStopped}, is not 
guaranteed. It may also
+ * be called while other threads are running the {@code onTrigger} method. The 
method must therefore
+ * be thread-safe and should do little more than take note that the drain has 
ended, for example
+ * by clearing a flag.
+ * </p>
+ *
+ * <p>
+ * Methods with this annotation are permitted to take either 0 or 1 argument. 
If an argument is
+ * used, it must be of type {@link ProcessContext} if the component is a 
Processor or of type
+ * {@link ConfigurationContext} if the component is a Controller Service.
+ * </p>
+ */
+@Documented
+@Target({ElementType.METHOD})
+@Retention(RetentionPolicy.RUNTIME)
+@Inherited
+public @interface OnDrainCompleted {
+
+}
diff --git 
a/src/main/java/org/apache/nifi/annotation/lifecycle/OnDrainInitiated.java 
b/src/main/java/org/apache/nifi/annotation/lifecycle/OnDrainInitiated.java
new file mode 100644
index 0000000..5ad2823
--- /dev/null
+++ b/src/main/java/org/apache/nifi/annotation/lifecycle/OnDrainInitiated.java
@@ -0,0 +1,69 @@
+/*
+ * 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.annotation.lifecycle;
+
+import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.processor.ProcessContext;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * <p>
+ * Marker annotation a {@link org.apache.nifi.processor.Processor Processor} or
+ * {@link org.apache.nifi.controller.ControllerService ControllerService} 
implementation
+ * can use to indicate that a method should be called when a drain of its 
Process Group begins.
+ * While a drain is in progress, no new data is brought into the group, so the 
component should
+ * process the data that it already has rather than wait for more. For 
example, a Processor that
+ * groups FlowFiles into bins might send its bins on sooner.
+ * </p>
+ *
+ * <p>
+ * The component may be in any lifecycle state when this method is called, and 
the order in which
+ * this method is called relative to other lifecycle methods, such as those 
marked with
+ * {@link OnScheduled}, {@link OnUnscheduled}, and {@link OnStopped}, is not 
guaranteed. It may be
+ * called before the component is scheduled, while it is being scheduled, 
after it is scheduled, or
+ * for a component that is not scheduled at all during the drain. It may also 
be called while other
+ * threads are running the {@code onTrigger} method. The method must therefore 
be thread-safe, must
+ * not depend on anything created by a method marked with {@link OnScheduled}, 
and should do little
+ * more than take note that a drain has begun, for example by setting a flag.
+ * </p>
+ *
+ * <p>
+ * This method is called at most once for each drain. When the drain ends, 
methods marked with
+ * {@link OnDrainCompleted} are called. Because the component may be stopped 
and started again
+ * while the drain is in progress, anything noted when the drain began should 
be cleared only by
+ * a method marked with {@link OnDrainCompleted}, not by a method marked with 
{@link OnScheduled}.
+ * </p>
+ *
+ * <p>
+ * Methods with this annotation are permitted to take either 0 or 1 argument. 
If an argument is
+ * used, it must be of type {@link ProcessContext} if the component is a 
Processor or of type
+ * {@link ConfigurationContext} if the component is a Controller Service.
+ * </p>
+ */
+@Documented
+@Target({ElementType.METHOD})
+@Retention(RetentionPolicy.RUNTIME)
+@Inherited
+public @interface OnDrainInitiated {
+
+}
diff --git 
a/src/main/java/org/apache/nifi/components/connector/AbstractConnector.java 
b/src/main/java/org/apache/nifi/components/connector/AbstractConnector.java
index 464d1bf..b51594c 100644
--- a/src/main/java/org/apache/nifi/components/connector/AbstractConnector.java
+++ b/src/main/java/org/apache/nifi/components/connector/AbstractConnector.java
@@ -142,6 +142,9 @@ public abstract class AbstractConnector implements 
Connector {
                 final ProcessGroupFacade rootGroup = context.getRootGroup();
                 final ProcessGroupLifecycle lifecycle = 
rootGroup.getLifecycle();
 
+                // A drain that is still being prepared could otherwise start 
components after they have been stopped
+                lifecycle.endDrain();
+
                 try {
                     
lifecycle.stopProcessors(ComponentHierarchyScope.INCLUDE_CHILD_GROUPS).get(1, 
TimeUnit.MINUTES);
                 } catch (final TimeoutException e) {
@@ -183,7 +186,8 @@ public abstract class AbstractConnector implements 
Connector {
     }
 
     /**
-     * Drains all FlowFiles from the Connector instance.
+     * Drains all FlowFiles from the Connector instance by draining its root 
Process Group using {@link ProcessGroupLifecycle#beginDrain()}.
+     * Once no FlowFiles remain, the drain is ended and the Connector is 
stopped.
      *
      * @param flowContext the FlowContext to use for drainage
      * @return a CompletableFuture that will be completed when drainage is 
complete
@@ -202,9 +206,9 @@ public abstract class AbstractConnector implements 
Connector {
             initialQueueSize.getObjectCount(), 
NumberFormat.getNumberInstance().format(initialQueueSize.getByteCount()));
 
         Thread.startVirtualThread(() -> {
+            final ProcessGroupLifecycle lifecycle = 
flowContext.getRootGroup().getLifecycle();
             try {
-                stopSourceComponents(flowContext).get();
-                startNonSourceComponents(result, flowContext);
+                lifecycle.beginDrain().get();
 
                 if (!result.isDone()) {
                     completeDrain(result, flowContext, initialQueueSize);
@@ -213,6 +217,8 @@ public abstract class AbstractConnector implements 
Connector {
                 if (!result.isDone()) {
                     result.completeExceptionally(new RuntimeException("Failed 
while draining FlowFiles", e));
                 }
+            } finally {
+                lifecycle.endDrain();
             }
         });
 
@@ -277,34 +283,6 @@ public abstract class AbstractConnector implements 
Connector {
         }
     }
 
-    private void startNonSourceComponents(final CompletableFuture<Void> 
result, final FlowContext flowContext) {
-        if (result.isDone()) {
-            return;
-        }
-
-        final CompletableFuture<Void> enableServices = 
flowContext.getRootGroup().getLifecycle().enableControllerServices(
-            ControllerServiceReferenceScope.INCLUDE_REFERENCED_SERVICES_ONLY,
-            ComponentHierarchyScope.INCLUDE_CHILD_GROUPS);
-
-        try {
-            // Wait for all referenced services to be enabled.
-            enableServices.get();
-
-            if (!result.isDone()) {
-                getLogger().info("Starting all non-source components to 
facilitate drainage of FlowFiles");
-                startNonSourceComponents(flowContext).get();
-            }
-        } catch (final Exception e) {
-            try {
-                
flowContext.getRootGroup().getLifecycle().disableControllerServices(ComponentHierarchyScope.INCLUDE_CHILD_GROUPS).get();
-            } catch (final Exception e1) {
-                e.addSuppressed(e1);
-            }
-
-            result.completeExceptionally(new RuntimeException("Failed to start 
non-source components while draining FlowFiles", e.getCause()));
-        }
-    }
-
     /**
      * <p>
      *     A method designed to be overridden by subclasses that need to 
ensure that any
@@ -414,15 +392,6 @@ public abstract class AbstractConnector implements 
Connector {
         return group.getQueueSize().getObjectCount() == 0;
     }
 
-    protected CompletableFuture<Void> stopSourceComponents(final FlowContext 
context) {
-        final List<CompletableFuture<Void>> stopFutures = new ArrayList<>();
-        for (final ProcessorFacade sourceProcessor : 
getSourceProcessors(context.getRootGroup())) {
-            stopFutures.add(sourceProcessor.getLifecycle().stop());
-        }
-
-        return CompletableFuture.allOf(stopFutures.toArray(new 
CompletableFuture[0]));
-    }
-
     protected CompletableFuture<Void> startNonSourceComponents(final 
FlowContext flowContext) {
         final ProcessGroupFacade rootGroup = flowContext.getRootGroup();
         final List<CompletableFuture<Void>> startFutures = new ArrayList<>();
@@ -438,12 +407,6 @@ public abstract class AbstractConnector implements 
Connector {
         return CompletableFuture.allOf(startFutures.toArray(new 
CompletableFuture[0]));
     }
 
-    protected List<ProcessorFacade> getSourceProcessors(final 
ProcessGroupFacade group) {
-        final Set<String> nonSourceIds = getNonSourceProcessorIds(group);
-
-        return findProcessors(group, processor -> 
!nonSourceIds.contains(processor.getDefinition().getIdentifier()));
-    }
-
     protected List<ProcessorFacade> getNonSourceProcessors(final 
ProcessGroupFacade group) {
         final Set<String> nonSourceIds = getNonSourceProcessorIds(group);
 
diff --git 
a/src/main/java/org/apache/nifi/components/connector/components/ProcessGroupLifecycle.java
 
b/src/main/java/org/apache/nifi/components/connector/components/ProcessGroupLifecycle.java
index 3f98fac..c0ee0e6 100644
--- 
a/src/main/java/org/apache/nifi/components/connector/components/ProcessGroupLifecycle.java
+++ 
b/src/main/java/org/apache/nifi/components/connector/components/ProcessGroupLifecycle.java
@@ -51,4 +51,34 @@ public interface ProcessGroupLifecycle {
     CompletableFuture<Void> stopStatelessGroups(ComponentHierarchyScope scope);
 
     int getActiveThreadCount();
+
+    /**
+     * Begins draining the Process Group. While the drain is active, the 
components that bring data into the group remain stopped and the
+     * rest of the group runs in order to process the data that is already 
queued. The drain does not end on its own, even once no data
+     * remains; it stays active until {@link #endDrain()} is called.
+     *
+     * @return a future that completes once the components that bring data 
into the group have stopped, the Controller Services referenced
+     *         by the group's components have been enabled, the other 
components in the group have been told to start, and the methods annotated
+     *         with {@link 
org.apache.nifi.annotation.lifecycle.OnDrainInitiated OnDrainInitiated} have 
been scheduled to be called. The future does
+     *         not wait for those methods to return. If any of these steps 
fails, the future completes exceptionally, the drain is no longer active,
+     *         and any components that were already stopped or started are 
left as they are.
+     * @throws IllegalStateException if this group, a parent group, or a child 
group is already being drained, if this group uses the
+     *         Stateless Execution Engine, or if a component that brings data 
into the group cannot be stopped
+     */
+    default CompletableFuture<Void> beginDrain() {
+        throw new UnsupportedOperationException("Draining is not supported by 
" + getClass().getName());
+    }
+
+    /**
+     * Ends the active drain of the Process Group. The caller decides when a 
drain is over, either because all data has been processed or
+     * because the drain has been cancelled. Once the drain has ended, a new 
drain may begin. For each component whose methods annotated with
+     * {@link org.apache.nifi.annotation.lifecycle.OnDrainInitiated 
OnDrainInitiated} were scheduled to be called for this drain, the methods
+     * annotated with {@link 
org.apache.nifi.annotation.lifecycle.OnDrainCompleted OnDrainCompleted} are 
called once its
+     * {@link org.apache.nifi.annotation.lifecycle.OnDrainInitiated 
OnDrainInitiated} methods have returned. This method does not wait for them.
+     * Ending a drain does not start or stop any components: the components 
that bring data into the group remain stopped and the rest of the
+     * group keeps running. If the drain is ended before the future returned 
by {@link #beginDrain()} completes, components that have not yet
+     * been told to start are not started, and the future still completes 
normally. Calling this method when no drain is active has no effect.
+     */
+    default void endDrain() {
+    }
 }
diff --git 
a/src/test/java/org/apache/nifi/components/connector/TestAbstractConnector.java 
b/src/test/java/org/apache/nifi/components/connector/TestAbstractConnector.java
index 960ab52..e0ccfca 100644
--- 
a/src/test/java/org/apache/nifi/components/connector/TestAbstractConnector.java
+++ 
b/src/test/java/org/apache/nifi/components/connector/TestAbstractConnector.java
@@ -942,34 +942,6 @@ public class TestAbstractConnector {
         verify(rootGroup.getLifecycle(), 
times(1)).startStatelessGroups(ComponentHierarchyScope.INCLUDE_CHILD_GROUPS);
     }
 
-    @Test
-    void testStopSourceComponentsStopsNestedProcessorsOnce() {
-        final ProcessorFacade rootGenerate = mockProcessor("root-generate");
-        final ProcessorFacade rootTerminate = mockProcessor("root-terminate");
-        final ProcessorFacade childGenerate = mockProcessor("child-generate");
-        final ProcessorFacade childTerminate = 
mockProcessor("child-terminate");
-        final ProcessorFacade grandchildGenerate = 
mockProcessor("grandchild-generate");
-        final ProcessorFacade grandchildTerminate = 
mockProcessor("grandchild-terminate");
-
-        final ProcessGroupFacade grandchildGroup = 
mockGroup(Set.of(grandchildGenerate, grandchildTerminate),
-            Set.of(mockConnection("grandchild-generate", 
"grandchild-terminate")), Set.of());
-        final ProcessGroupFacade childGroup = mockGroup(Set.of(childGenerate, 
childTerminate),
-            Set.of(mockConnection("child-generate", "child-terminate")), 
Set.of(grandchildGroup));
-        final ProcessGroupFacade rootGroup = mockGroup(Set.of(rootGenerate, 
rootTerminate),
-            Set.of(mockConnection("root-generate", "root-terminate")), 
Set.of(childGroup));
-        when(flowContext.getRootGroup()).thenReturn(rootGroup);
-
-        final CompletableFuture<Void> stopFuture = 
connector.stopSourceComponents(flowContext);
-
-        assertDoesNotThrow(() -> stopFuture.get(5, TimeUnit.SECONDS));
-        for (final ProcessorFacade source : List.of(rootGenerate, 
childGenerate, grandchildGenerate)) {
-            verify(source.getLifecycle(), times(1)).stop();
-        }
-        for (final ProcessorFacade nonSource : List.of(rootTerminate, 
childTerminate, grandchildTerminate)) {
-            verify(nonSource.getLifecycle(), never()).stop();
-        }
-    }
-
     private static ProcessorFacade mockProcessor(final String identifier) {
         final VersionedProcessor definition = new VersionedProcessor();
         definition.setIdentifier(identifier);
@@ -978,7 +950,6 @@ public class TestAbstractConnector {
         // start of an already running processor returns a future that never 
completes.
         final ProcessorLifecycle lifecycle = mock(ProcessorLifecycle.class);
         
when(lifecycle.start()).thenReturn(CompletableFuture.completedFuture(null), new 
CompletableFuture<>());
-        
when(lifecycle.stop()).thenReturn(CompletableFuture.completedFuture(null));
 
         final ProcessorFacade processor = mock(ProcessorFacade.class);
         when(processor.getDefinition()).thenReturn(definition);

Reply via email to