pvillard31 commented on code in PR #11570: URL: https://github.com/apache/nifi/pull/11570#discussion_r4147073796
########## nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/RemovedConnectionDrainCoordinator.java: ########## @@ -0,0 +1,567 @@ +/* + * 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; + +import org.apache.nifi.connectable.ConnectableType; +import org.apache.nifi.controller.ScheduledState; +import org.apache.nifi.web.api.dto.AffectedComponentDTO; +import org.apache.nifi.web.api.entity.AffectedComponentEntity; +import org.apache.nifi.web.util.CancellableTimedPause; +import org.apache.nifi.web.util.ComponentLifecycle; +import org.apache.nifi.web.util.InvalidComponentAction; +import org.apache.nifi.web.util.LifecycleManagementException; +import org.apache.nifi.web.util.Pause; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.URI; +import java.time.Duration; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; +import java.util.stream.Collectors; + +public final class RemovedConnectionDrainCoordinator { + private static final Logger logger = LoggerFactory.getLogger(RemovedConnectionDrainCoordinator.class); + static final Duration DEFAULT_DRAIN_TIMEOUT = Duration.ofSeconds(30); + private static final Duration DEFAULT_POLL_INTERVAL = Duration.ofMillis(250); + + private final RemovedConnectionDrainClassifier classifier; + private final PauseFactory pauseFactory; + private final Duration drainTimeout; + + public RemovedConnectionDrainCoordinator() { + this(new RemovedConnectionDrainClassifier(), new MonotonicPauseFactory(DEFAULT_POLL_INTERVAL, System::nanoTime), DEFAULT_DRAIN_TIMEOUT); + } + + RemovedConnectionDrainCoordinator(final RemovedConnectionDrainClassifier classifier, final PauseFactory pauseFactory, final Duration drainTimeout) { + this.classifier = Objects.requireNonNull(classifier, "Removed Connection Drain Classifier required"); + this.pauseFactory = Objects.requireNonNull(pauseFactory, "Pause Factory required"); + this.drainTimeout = Objects.requireNonNull(drainTimeout, "Drain Timeout required"); + } + + public DrainResult coordinateDrain(final FlowUpdateImpact flowUpdateImpact, final RemovedConnectionDrainClassifier.Context context, + final ComponentLifecycle componentLifecycle, final URI requestUri, final String groupId, + final CancellationHandle cancellationHandle) throws LifecycleManagementException { + Objects.requireNonNull(flowUpdateImpact, "Flow Update Impact required"); + Objects.requireNonNull(context, "Removed Connection Drain Context required"); + Objects.requireNonNull(componentLifecycle, "Component Lifecycle required"); + Objects.requireNonNull(requestUri, "Request URI required"); + Objects.requireNonNull(groupId, "Group ID required"); + Objects.requireNonNull(cancellationHandle, "Cancellation Handle required"); + + final RemovedConnectionDrainClassifier.Context queueAwareContext = createQueueAwareContext(flowUpdateImpact, context, componentLifecycle, requestUri); + final RemovedConnectionDrainClassifier.BatchResult batchResult = classifier.classify(flowUpdateImpact, queueAwareContext); + if (!batchResult.isSupported()) { + throw new LifecycleManagementException(buildClassificationFailureMessage(batchResult)); + } + + final Set<String> candidateConnectionIds = batchResult.connectionResults().stream() + .filter(result -> result.classification() == RemovedConnectionDrainClassifier.Classification.CANDIDATE) + .map(result -> result.connection().getConnectionInstanceId()) + .collect(Collectors.toCollection(LinkedHashSet::new)); + + if (candidateConnectionIds.isEmpty()) { + return DrainResult.success(Collections.emptySet(), Collections.emptySet()); + } + + final Map<String, AffectedComponentEntity> affectedComponentsById = flowUpdateImpact.getAffectedComponents().stream() + .collect(Collectors.toMap(AffectedComponentEntity::getId, entity -> entity, (left, right) -> left, LinkedHashMap::new)); + final Set<AffectedComponentEntity> componentsToStop = new LinkedHashSet<>(); + for (final String producerBarrierComponentId : batchResult.producerBarrierComponentIds()) { + final AffectedComponentEntity entity = getProducerBarrierEntity(affectedComponentsById, queueAwareContext, producerBarrierComponentId); + if (entity == null || entity.getComponent() == null) { + continue; + } + + if (isActive(entity.getComponent())) { + componentsToStop.add(entity); + } + } + + final List<String> orderedCandidateConnectionIds = candidateConnectionIds.stream().sorted().toList(); + final List<String> orderedProducerBarrierIds = componentsToStop.stream().map(AffectedComponentEntity::getId).sorted().toList(); + logger.info("Starting drain of removed connections {} with producer barriers {}", orderedCandidateConnectionIds, orderedProducerBarrierIds); + + final DeadlinePause drainPause = pauseFactory.createDrainPause(drainTimeout); + cancellationHandle.setCancelCallback(drainPause::cancel); + + final Set<AffectedComponentEntity> drainStoppedComponents = new LinkedHashSet<>(); + try { + if (!componentsToStop.isEmpty()) { + final Set<AffectedComponentEntity> updatedStoppedComponents = componentLifecycle.scheduleComponents( + requestUri, groupId, componentsToStop, ScheduledState.STOPPED, drainPause, InvalidComponentAction.SKIP); + drainStoppedComponents.addAll(getStoppedComponents(componentsToStop, updatedStoppedComponents)); + + if (!allComponentsStopped(componentsToStop, updatedStoppedComponents)) { + if (cancellationHandle.isCancelled()) { + return restoreAfterCancellation(componentLifecycle, requestUri, groupId, candidateConnectionIds, drainStoppedComponents); + } + + final Set<String> producerBarrierIds = componentsToStop.stream() + .map(AffectedComponentEntity::getId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + throw new LifecycleManagementException(buildStopTimeoutMessage(producerBarrierIds)); + } + } + + if (cancellationHandle.isCancelled()) { + return restoreAfterCancellation(componentLifecycle, requestUri, groupId, candidateConnectionIds, drainStoppedComponents); + } + + final boolean queuesDrained = componentLifecycle.waitForConnectionQueuesEmpty(requestUri, candidateConnectionIds, drainPause); + if (queuesDrained) { + if (cancellationHandle.isCancelled()) { + return restoreAfterCancellation(componentLifecycle, requestUri, groupId, candidateConnectionIds, drainStoppedComponents); + } + + logger.info("Completed draining removed connections {}", orderedCandidateConnectionIds); + return DrainResult.success(candidateConnectionIds, drainStoppedComponents); + } + + if (cancellationHandle.isCancelled()) { + return restoreAfterCancellation(componentLifecycle, requestUri, groupId, candidateConnectionIds, drainStoppedComponents); + } + + throw new LifecycleManagementException(buildQueueTimeoutMessage(candidateConnectionIds)); + } catch (final LifecycleManagementException e) { + final Set<AffectedComponentEntity> stoppedComponents = getStoppedComponentsToRestore(queueAwareContext, componentsToStop, drainStoppedComponents); + if (cancellationHandle.isCancelled()) { + return restoreAfterCancellation(componentLifecycle, requestUri, groupId, candidateConnectionIds, stoppedComponents); + } + + final LifecycleManagementException failure = decorateFailure(e, componentsToStop, candidateConnectionIds); + logger.warn("Removed connection drain failed for connections {}", orderedCandidateConnectionIds, failure); + restoreOrSuppress(componentLifecycle, requestUri, groupId, stoppedComponents, failure); + throw failure; + } catch (final RuntimeException e) { + final Set<AffectedComponentEntity> stoppedComponents = getStoppedComponentsToRestore(queueAwareContext, componentsToStop, drainStoppedComponents); + if (cancellationHandle.isCancelled()) { + return restoreAfterCancellation(componentLifecycle, requestUri, groupId, candidateConnectionIds, stoppedComponents); + } + + final LifecycleManagementException failure = new LifecycleManagementException( + "Removed connection drain failed for connections " + candidateConnectionIds.stream().sorted().toList(), e); + logger.warn("Removed connection drain failed for connections {}", orderedCandidateConnectionIds, failure); + restoreOrSuppress(componentLifecycle, requestUri, groupId, stoppedComponents, failure); + throw failure; + } finally { + cancellationHandle.setCancelCallback(null); + } + } + + private DrainResult restoreAfterCancellation(final ComponentLifecycle componentLifecycle, final URI requestUri, final String groupId, + final Set<String> candidateConnectionIds, + final Set<AffectedComponentEntity> drainStoppedComponents) { + LifecycleManagementException restorationFailure = null; + try { + restoreStoppedComponents(componentLifecycle, requestUri, groupId, drainStoppedComponents); + } catch (final LifecycleManagementException e) { Review Comment: Agreed. Unchecked scheduling failures during restoration are wrapped as lifecycle failures, logged, and either returned with cancellation or attached as suppressed exceptions to the initiating failure. -- 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]
