From 0bfc8f5a8e18c34acccf097f6e892cd4fa05c2bd Mon Sep 17 00:00:00 2001 From: yunhong <337361684@qq.com> Date: Wed, 11 Nov 2026 15:12:07 +0800 Subject: [PATCH] [server] Store rebalance tasks in remote storage --- .../org/apache/fluss/utils/FlussPaths.java | 19 + .../CoordinatorEventProcessor.java | 108 +++-- .../server/coordinator/CoordinatorServer.java | 9 +- .../RebalancePersistenceCompleteEvent.java | 34 ++ .../rebalance/RebalanceManager.java | 406 +++++++++++++----- .../rebalance/RebalanceTaskStore.java | 274 ++++++++++++ .../fluss/server/zk/ZooKeeperClient.java | 34 ++ .../server/zk/data/CoordinatorAddress.java | 42 +- .../zk/data/CoordinatorAddressJsonSerde.java | 22 +- .../server/zk/data/RebalanceTaskHandle.java | 74 ++++ .../zk/data/RebalanceTaskZNodeData.java | 64 +++ .../zk/data/RebalanceTaskZNodeJsonSerde.java | 75 ++++ .../apache/fluss/server/zk/data/ZkData.java | 12 +- .../CoordinatorEventProcessorTestBase.java | 17 + .../coordinator/CoordinatorRebalanceTest.java | 58 ++- .../rebalance/RebalanceManagerTest.java | 273 ++++++++++-- .../rebalance/RebalanceTaskStoreTest.java | 221 ++++++++++ .../data/CoordinatorAddressJsonSerdeTest.java | 27 +- .../data/RebalanceTaskZNodeJsonSerdeTest.java | 52 +++ .../docs/maintenance/operations/rebalance.md | 2 + 20 files changed, 1623 insertions(+), 200 deletions(-) create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/RebalancePersistenceCompleteEvent.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStore.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskHandle.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeData.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerde.java create mode 100644 fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStoreTest.java create mode 100644 fluss-server/src/test/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerdeTest.java diff --git a/fluss-common/src/main/java/org/apache/fluss/utils/FlussPaths.java b/fluss-common/src/main/java/org/apache/fluss/utils/FlussPaths.java index 988e6780b35..94f9c02a274 100644 --- a/fluss-common/src/main/java/org/apache/fluss/utils/FlussPaths.java +++ b/fluss-common/src/main/java/org/apache/fluss/utils/FlussPaths.java @@ -103,6 +103,12 @@ public class FlussPaths { /** Suffix of a producer offsets file. */ private static final String PRODUCER_OFFSETS_FILE_SUFFIX = ".offsets"; + /** The directory name for storing rebalance task snapshots. */ + private static final String REMOTE_REBALANCE_DIR_NAME = "rebalance"; + + /** Suffix of a rebalance task snapshot file. */ + private static final String REBALANCE_TASK_FILE_SUFFIX = ".task"; + private static final String REMOTE_LEASE_DIR_NAME = "lease"; // ---------------------------------------------------------------------------------------- @@ -909,6 +915,19 @@ public static FsPath remoteProducerOffsetsPath( uuid + PRODUCER_OFFSETS_FILE_SUFFIX); } + /** Returns a unique remote file path for a rebalance task snapshot. */ + public static FsPath remoteRebalanceTaskPath( + String remoteDataDir, String rebalanceId, UUID fileId) { + return new FsPath( + new FsPath(remoteRebalanceDir(remoteDataDir), rebalanceId), + fileId + REBALANCE_TASK_FILE_SUFFIX); + } + + /** Returns the remote directory containing all rebalance task snapshots. */ + public static FsPath remoteRebalanceDir(String remoteDataDir) { + return new FsPath(remoteDataDir, REMOTE_REBALANCE_DIR_NAME); + } + // ---------------------------------------------------------------------------------------- // Remote Paths for common use // ---------------------------------------------------------------------------------------- diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java index cc8bbf17c6a..12c73bb49eb 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessor.java @@ -63,7 +63,6 @@ import org.apache.fluss.rpc.messages.ControlledShutdownResponse; import org.apache.fluss.rpc.messages.ListRebalanceProgressResponse; import org.apache.fluss.rpc.messages.PbCommitLakeTableSnapshotRespForTable; -import org.apache.fluss.rpc.messages.RebalanceResponse; import org.apache.fluss.rpc.messages.RemoveServerTagByRackResponse; import org.apache.fluss.rpc.messages.RemoveServerTagResponse; import org.apache.fluss.rpc.protocol.ApiError; @@ -101,6 +100,7 @@ import org.apache.fluss.server.coordinator.event.NotifyLeaderAndIsrRequestContext; import org.apache.fluss.server.coordinator.event.NotifyLeaderAndIsrResponseReceivedEvent; import org.apache.fluss.server.coordinator.event.RebalanceEvent; +import org.apache.fluss.server.coordinator.event.RebalancePersistenceCompleteEvent; import org.apache.fluss.server.coordinator.event.ReclaimTableBulkLoadMetadataEvent; import org.apache.fluss.server.coordinator.event.ReconcileRebalanceTaskEvent; import org.apache.fluss.server.coordinator.event.RecoverRebalanceEvent; @@ -253,7 +253,13 @@ public CoordinatorEventProcessor( this.coordinatorEventManager = new CoordinatorEventManager(this, coordinatorMetricGroup); this.rebalanceManager = new RebalanceManager( - this, zooKeeperClient, coordinatorEventManager, clock, conf, scheduler); + this, + zooKeeperClient, + coordinatorEventManager, + clock, + conf, + scheduler, + ioExecutor); CoordinatorRequestBatch replicaRequestBatch = new CoordinatorRequestBatch( coordinatorChannelManager, @@ -664,8 +670,14 @@ public void startup() { scheduler, coordinatorEventManager, bulkLoadResultRetentionMs); } + /** Starts loading the persisted rebalance task without blocking coordinator startup. */ + public void startRebalanceRecovery() { + rebalanceManager.startRecovery(); + } + public void shutdown() { bulkLoadManager.stopMetadataReclamation(); + rebalanceManager.stopRecovery(); clearOfflineLeaderRetryTask(); // Cancel periodic event producers before stopping the event loop. rebalanceManager.stopTimeoutChecker(); @@ -1126,27 +1138,36 @@ public void process(CoordinatorEvent event) { () -> processRemoveServerTagByRack(removeServerTagByRackEvent)); } else if (event instanceof RebalanceEvent) { RebalanceEvent rebalanceEvent = (RebalanceEvent) event; - completeFromCallable( - rebalanceEvent.getRespCallback(), () -> processRebalance(rebalanceEvent)); + try { + processRebalance(rebalanceEvent); + } catch (Throwable t) { + rebalanceEvent.getRespCallback().completeExceptionally(t); + } } else if (event instanceof RecoverRebalanceEvent) { RebalanceTask rebalanceTask = ((RecoverRebalanceEvent) event).getRebalanceTask(); assignmentPersistenceByBucket.clear(); - rebalanceManager.recoverRebalance(rebalanceTask); + boolean recovered = rebalanceManager.recoverRebalance(rebalanceTask); // The coordinator context was rebuilt from ZooKeeper before recovery was submitted, // so its current assignments are already confirmed without another per-bucket read. - for (TableBucket tableBucket : rebalanceTask.getExecutePlan().keySet()) { - if (rebalanceManager.getRebalancePlanForBucket(tableBucket) != null - && !coordinatorContext.getAssignment(tableBucket).isEmpty()) { - assignmentPersistenceByBucket.put( - tableBucket, - new ArrayList<>(coordinatorContext.getAssignment(tableBucket))); + if (recovered) { + for (TableBucket tableBucket : rebalanceTask.getExecutePlan().keySet()) { + if (rebalanceManager.getRebalancePlanForBucket(tableBucket) != null + && !coordinatorContext.getAssignment(tableBucket).isEmpty()) { + assignmentPersistenceByBucket.put( + tableBucket, + new ArrayList<>(coordinatorContext.getAssignment(tableBucket))); + } } } } else if (event instanceof CancelRebalanceEvent) { CancelRebalanceEvent cancelRebalanceEvent = (CancelRebalanceEvent) event; - completeFromCallable( - cancelRebalanceEvent.getRespCallback(), - () -> processCancelRebalance(cancelRebalanceEvent)); + try { + processCancelRebalance(cancelRebalanceEvent); + } catch (Throwable t) { + cancelRebalanceEvent.getRespCallback().completeExceptionally(t); + } + } else if (event instanceof RebalancePersistenceCompleteEvent) { + ((RebalancePersistenceCompleteEvent) event).complete(); } else if (event instanceof CheckRebalanceTimeoutEvent) { rebalanceManager.checkTimeout(); } else if (event instanceof ReconcileRebalanceTaskEvent) { @@ -2004,7 +2025,7 @@ private void removeServerTags(List serverIds, ServerTag serverTag) { coordinatorContext.getServerTags()); } - private RebalanceResponse processRebalance(RebalanceEvent rebalanceEvent) { + private void processRebalance(RebalanceEvent rebalanceEvent) { // Recovery may still be loading or queued behind this request. Persisting a new task before // the recovered task is applied would let the delayed recovery overwrite the local state. checkRebalanceRecoveryComplete(); @@ -2022,12 +2043,6 @@ private RebalanceResponse processRebalance(RebalanceEvent rebalanceEvent) { // 1. generate rebalance plan. rebalanceTask = rebalanceManager.generateRebalanceTask(rebalanceEvent.getGoalsByPriority()); - - // 2. execute rebalance plan. - Map executePlan = rebalanceTask.getExecutePlan(); - assignmentPersistenceByBucket.clear(); - zooKeeperClient.registerRebalanceTask(rebalanceTask); - rebalanceManager.registerRebalance(rebalanceTask.getRebalanceId(), executePlan); } catch (Exception e) { throw new RebalanceFailureException( String.format( @@ -2036,19 +2051,50 @@ private RebalanceResponse processRebalance(RebalanceEvent rebalanceEvent) { e); } - LOG.info( - "Generate Rebalance plan rebalance id {} with {} ms.", - rebalanceTask.getRebalanceId(), - System.currentTimeMillis() - startTime); - return makeRebalanceResponse(rebalanceTask.getRebalanceId()); + // Persist before exposing the task locally. Remote storage and ZooKeeper I/O run on the + // coordinator I/O executor; the completion is applied by the event thread. + rebalanceManager.persistRebalanceTask( + rebalanceTask, + failure -> { + if (failure != null) { + rebalanceEvent + .getRespCallback() + .completeExceptionally( + new RebalanceFailureException( + "Failed to persist and execute rebalance plan.", + failure)); + return; + } + try { + assignmentPersistenceByBucket.clear(); + rebalanceManager.registerRebalance( + rebalanceTask.getRebalanceId(), rebalanceTask.getExecutePlan()); + LOG.info( + "Generate Rebalance plan rebalance id {} with {} ms.", + rebalanceTask.getRebalanceId(), + System.currentTimeMillis() - startTime); + rebalanceEvent + .getRespCallback() + .complete(makeRebalanceResponse(rebalanceTask.getRebalanceId())); + } catch (Throwable t) { + rebalanceEvent.getRespCallback().completeExceptionally(t); + } + }); } - private CancelRebalanceResponse processCancelRebalance( - CancelRebalanceEvent cancelRebalanceEvent) { + private void processCancelRebalance(CancelRebalanceEvent cancelRebalanceEvent) { checkRebalanceRecoveryComplete(); - CancelRebalanceResponse response = new CancelRebalanceResponse(); - rebalanceManager.cancelRebalance(cancelRebalanceEvent.getRabalanceId()); - return response; + rebalanceManager.cancelRebalance( + cancelRebalanceEvent.getRabalanceId(), + failure -> { + if (failure == null) { + cancelRebalanceEvent + .getRespCallback() + .complete(new CancelRebalanceResponse()); + } else { + cancelRebalanceEvent.getRespCallback().completeExceptionally(failure); + } + }); } private ListRebalanceProgressResponse processListRebalanceProgress( diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorServer.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorServer.java index 282f17bac77..9397211a3b6 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorServer.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorServer.java @@ -64,6 +64,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -378,6 +379,10 @@ protected void initCoordinatorLeader() throws Exception { dynamicConfigManager.pauseListening(); createDefaultDatabase(); + + // Rebalance plans can be large and may live in remote storage. Recover them only + // after the leader's base services are ready, and never block leader startup on I/O. + coordinatorEventProcessor.startRebalanceRecovery(); } } @@ -496,7 +501,9 @@ private void unregisterCoordinatorLeader() throws Exception { private CoordinatorAddress buildCoordinatorAddress() { List bindEndpoints = rpcServer.getBindEndpoints(); return new CoordinatorAddress( - this.serverId, Endpoint.loadAdvertisedEndpoints(bindEndpoints, conf)); + this.serverId, + Endpoint.loadAdvertisedEndpoints(bindEndpoints, conf), + Collections.singleton(CoordinatorAddress.REMOTE_REBALANCE_TASK_FEATURE)); } /** diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/RebalancePersistenceCompleteEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/RebalancePersistenceCompleteEvent.java new file mode 100644 index 00000000000..35ab4c060cf --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/RebalancePersistenceCompleteEvent.java @@ -0,0 +1,34 @@ +/* + * 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.fluss.server.coordinator.event; + +/** Returns completion of asynchronous rebalance persistence to the coordinator event thread. */ +public final class RebalancePersistenceCompleteEvent implements CoordinatorEvent { + + private final Runnable completion; + + /** Creates an event for an internally supplied persistence completion. */ + public RebalancePersistenceCompleteEvent(Runnable completion) { + this.completion = completion; + } + + /** Applies the persistence result on the coordinator event thread. */ + public void complete() { + completion.run(); + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManager.java index 678b3c60add..cfb460afcf1 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManager.java @@ -35,6 +35,7 @@ import org.apache.fluss.server.coordinator.CoordinatorContext; import org.apache.fluss.server.coordinator.event.CheckRebalanceTimeoutEvent; import org.apache.fluss.server.coordinator.event.EventManager; +import org.apache.fluss.server.coordinator.event.RebalancePersistenceCompleteEvent; import org.apache.fluss.server.coordinator.event.ReconcileRebalanceTaskEvent; import org.apache.fluss.server.coordinator.event.RecoverRebalanceEvent; import org.apache.fluss.server.coordinator.rebalance.RebalanceExecutor.ExecutionResult; @@ -45,6 +46,7 @@ import org.apache.fluss.server.coordinator.rebalance.model.ServerModel; import org.apache.fluss.server.metadata.ServerInfo; import org.apache.fluss.server.zk.ZooKeeperClient; +import org.apache.fluss.server.zk.data.CoordinatorAddress; import org.apache.fluss.server.zk.data.LeaderAndIsr; import org.apache.fluss.server.zk.data.RebalanceTask; import org.apache.fluss.utils.clock.Clock; @@ -66,13 +68,17 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.UUID; +import java.util.concurrent.Executor; import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; import static org.apache.fluss.cluster.rebalance.RebalanceStatus.CANCELED; import static org.apache.fluss.cluster.rebalance.RebalanceStatus.COMPLETED; @@ -82,6 +88,7 @@ import static org.apache.fluss.cluster.rebalance.RebalanceStatus.REBALANCING; import static org.apache.fluss.cluster.rebalance.RebalanceStatus.TIMEOUT; import static org.apache.fluss.server.coordinator.rebalance.goal.GoalOptimizerUtils.getDiff; +import static org.apache.fluss.server.zk.data.CoordinatorAddress.REMOTE_REBALANCE_TASK_FEATURE; import static org.apache.fluss.utils.Preconditions.checkArgument; import static org.apache.fluss.utils.Preconditions.checkState; @@ -119,9 +126,11 @@ *

All rebalance state is confined to the coordinator event thread. The shared scheduler only * reads {@link #hasActiveRebalance} and enqueues a timeout-check event; the event thread performs * the actual timeout and reconciliation work. The dynamic concurrency setting may be updated by a - * configuration callback, so that scalar is independently volatile. Startup recovery is tracked by - * {@link #recoveryPending}, which fences new rebalance requests until recovery has finished - * regardless of when the event loop starts. + * configuration callback, so that scalar is independently volatile. Recovery I/O runs on the + * coordinator I/O executor, but only enqueues a recovered task or clears the volatile empty-task + * gate; it never mutates event-confined task state. Startup recovery is tracked by {@link + * #recoveryPending}, which fences new rebalance requests until recovery has finished regardless of + * when the event loop starts. */ @NotThreadSafe public class RebalanceManager implements ServerReconfigurable { @@ -136,14 +145,19 @@ public class RebalanceManager implements ServerReconfigurable { /** Hardcoded upper bound for the exponential reconciliation backoff: 5 minutes. */ private static final long MAX_RECONCILE_BACKOFF_MS = 5 * 60 * 1000L; - private final ZooKeeperClient zkClient; + private static final long INITIAL_RECOVERY_RETRY_DELAY_MS = 5000L; + private static final long MAX_RECOVERY_RETRY_DELAY_MS = 5 * 60 * 1000L; + + private final RebalanceTaskStore rebalanceTaskStore; private final RebalanceExecutor rebalanceExecutor; private final EventManager eventManager; + private final Executor ioExecutor; private final Clock clock; private final Scheduler scheduler; private final long targetUnavailableTimeoutMs; private final long noProgressTimeoutMs; private final int maxTrackedTimedOutTasks; + private final AtomicInteger recoveryFailures = new AtomicInteger(); /** Tasks awaiting admission. */ private final Queue pendingRebalanceTasks = new ArrayDeque<>(); @@ -185,21 +199,26 @@ public class RebalanceManager implements ServerReconfigurable { * replaced locally when the delayed recovery event runs. Keep the flag set until ZooKeeper is * confirmed empty or the recovered task has been fully applied to the in-memory state. * - *

Recovery may complete on the startup thread when no task exists, or on the coordinator - * event thread when a recovery event is applied, hence volatile. + *

Recovery with a persisted task completes on the coordinator event thread. Empty recovery + * completes on the I/O thread, hence volatile. */ private volatile boolean recoveryPending = true; + private volatile @Nullable ScheduledFuture recoveryRetryTask; + private volatile boolean recoveryStopped; + private @Nullable ScheduledFuture timeoutCheckTask; private long registerTime; private @Nullable RebalanceStatus rebalanceStatus; private @Nullable String currentRebalanceId; + private @Nullable String pendingPersistenceRebalanceId; /** Pending tasks loaded from ZooKeeper may have started before the coordinator restarted. */ private boolean recoveredRebalance; private boolean cancelRequested; private boolean finalizationPending; + private boolean persistenceInProgress; private boolean isClosed = false; /** Creates a manager with validated coordinator rebalance settings. */ @@ -209,7 +228,8 @@ public RebalanceManager( EventManager eventManager, Clock clock, Configuration conf, - Scheduler scheduler) { + Scheduler scheduler, + Executor ioExecutor) { this.targetUnavailableTimeoutMs = getTimeoutMillis( conf, ConfigOptions.COORDINATOR_REBALANCE_TARGET_UNAVAILABLE_TIMEOUT); @@ -223,8 +243,10 @@ public RebalanceManager( ConfigOptions.COORDINATOR_REBALANCE_MAX_TRACKED_TIMED_OUT_TASKS.key(), maxTrackedTimedOutTasks); this.rebalanceExecutor = rebalanceExecutor; - this.zkClient = zkClient; + this.rebalanceTaskStore = + new RebalanceTaskStore(zkClient, zkClient.getDefaultRemoteDataDir()); this.eventManager = eventManager; + this.ioExecutor = ioExecutor; this.clock = clock == null ? SystemClock.getInstance() : clock; this.scheduler = scheduler; this.goalOptimizer = new GoalOptimizer(); @@ -245,11 +267,12 @@ public void startup() { "RebalanceManager timeout checker started: timeoutMs={}, checkIntervalMs={}", REBALANCE_TASK_TIMEOUT_MS, TIMEOUT_CHECK_INTERVAL_MS); - initialize(); } public @Nullable String getRebalanceId() { - return currentRebalanceId; + return pendingPersistenceRebalanceId == null + ? currentRebalanceId + : pendingPersistenceRebalanceId; } @Override @@ -286,26 +309,132 @@ public void reconfigure(Configuration newConfig) { newMaxInflightRebalanceTasks); } - private void initialize() { + /** Starts loading the persisted task without blocking coordinator startup. */ + public void startRecovery() { + if (recoveryStopped) { + return; + } + clearRecoveryRetryTask(); + try { - Optional rebalanceTask = zkClient.getRebalanceTask(); - if (rebalanceTask.isPresent()) { - eventManager.put(new RecoverRebalanceEvent(rebalanceTask.get())); - } else { - completeEmptyRecovery(); + ioExecutor.execute(this::loadPersistedTask); + } catch (Throwable t) { + scheduleRecoveryRetry("load the persisted rebalance task", this::startRecovery, t); + } + } + + /** Stops asynchronous recovery before the coordinator event loop is shut down. */ + public void stopRecovery() { + recoveryStopped = true; + clearRecoveryRetryTask(); + } + + Optional loadPersistedRebalanceTask() throws Exception { + return rebalanceTaskStore.load(); + } + + /** Persists a task off the event thread and completes on the event thread. */ + public void persistRebalanceTask(RebalanceTask task, Consumer completion) { + checkNotClosed(); + checkState(!persistenceInProgress, "Another rebalance persistence is already in progress."); + CoordinatorContext context = rebalanceExecutor.getCoordinatorContext(); + int coordinatorZkVersion = context.getCoordinatorZkVersion(); + boolean storeRemotely = allLiveCoordinatorsSupportRemoteTasks(context); + persistenceInProgress = true; + pendingPersistenceRebalanceId = task.getRebalanceId(); + try { + ioExecutor.execute( + () -> { + Throwable failure = null; + try { + rebalanceTaskStore.persist(task, coordinatorZkVersion, storeRemotely); + } catch (Throwable t) { + failure = t; + } + Throwable persistenceFailure = failure; + try { + eventManager.put( + new RebalancePersistenceCompleteEvent( + () -> { + persistenceInProgress = false; + pendingPersistenceRebalanceId = null; + completion.accept(persistenceFailure); + })); + } catch (Throwable t) { + LOG.warn( + "Failed to enqueue persistence completion for rebalance {}.", + task.getRebalanceId(), + t); + } + }); + } catch (Throwable t) { + persistenceInProgress = false; + pendingPersistenceRebalanceId = null; + completion.accept(t); + } + } + + private boolean allLiveCoordinatorsSupportRemoteTasks(CoordinatorContext context) { + List standbys = context.getCoordinatorStandbys(); + if (context.getLiveCoordinatorServers().size() != standbys.size() + 1) { + return false; + } + for (CoordinatorAddress standby : standbys) { + if (!standby.supportsFeature(REMOTE_REBALANCE_TASK_FEATURE)) { + return false; } - } catch (Exception e) { - // TODO: Retry loading the persisted rebalance task instead of skipping recovery. - recoveryPending = false; - LOG.error( - "Failed to get rebalance plan from zookeeper. Skipping recovery and allowing " - + "new rebalance requests; any unfinished task will not be resumed.", - e); + } + return true; + } + + private void loadPersistedTask() { + try { + Optional rebalanceTask = loadPersistedRebalanceTask(); + if (!recoveryStopped) { + if (rebalanceTask.isPresent()) { + eventManager.put(new RecoverRebalanceEvent(rebalanceTask.get())); + } else { + completeEmptyRecovery(); + } + } + } catch (Throwable t) { + scheduleRecoveryRetry("load the persisted rebalance task", this::startRecovery, t); + } + // Do not delay recovery completion on the best-effort directory scan. + rebalanceTaskStore.cleanupOrphanFiles(); + } + + private void scheduleRecoveryRetry(String action, Runnable retryAction, Throwable failure) { + if (recoveryStopped) { + return; + } + long retryDelayMs = nextRecoveryRetryDelayMs(); + LOG.warn("Failed to {}. Retrying after {} ms.", action, retryDelayMs, failure); + try { + recoveryRetryTask = + scheduler.scheduleOnce("rebalance-recovery-retry", retryAction, retryDelayMs); + } catch (Throwable schedulingFailure) { + LOG.warn("Failed to schedule rebalance recovery retry.", schedulingFailure); + } + } + + private long nextRecoveryRetryDelayMs() { + int failureCount = recoveryFailures.getAndIncrement(); + int shift = Math.min(failureCount, 16); + return Math.min(INITIAL_RECOVERY_RETRY_DELAY_MS << shift, MAX_RECOVERY_RETRY_DELAY_MS); + } + + private void clearRecoveryRetryTask() { + ScheduledFuture retryTask = recoveryRetryTask; + recoveryRetryTask = null; + if (retryTask != null) { + retryTask.cancel(false); } } /** Marks startup recovery complete when ZooKeeper contains no persisted rebalance task. */ public void completeEmptyRecovery() { + recoveryFailures.set(0); recoveryPending = false; } @@ -322,6 +451,7 @@ public void registerRebalance( !recoveryPending, "Cannot register a rebalance before startup recovery has completed."); resetRebalance(rebalanceId, false); + rebalanceStatus = REBALANCING; if (rebalancePlan.isEmpty()) { finalizeRebalance(); return; @@ -331,12 +461,44 @@ public void registerRebalance( addPendingTask(entry.getKey(), entry.getValue()); } - rebalanceStatus = REBALANCING; processNewRebalanceTasks(); } /** Recovers a persisted task by comparing every bucket plan with current coordinator state. */ - public void recoverRebalance(RebalanceTask rebalanceTask) { + public boolean recoverRebalance(RebalanceTask rebalanceTask) { + try { + recoverRebalanceInternal(rebalanceTask); + recoveryFailures.set(0); + clearRecoveryRetryTask(); + recoveryPending = false; + return true; + } catch (Throwable t) { + clearFailedRecoveryState(); + scheduleRecoveryRetry( + "apply persisted rebalance task " + rebalanceTask.getRebalanceId(), + () -> eventManager.put(new RecoverRebalanceEvent(rebalanceTask)), + t); + return false; + } + } + + private void clearFailedRecoveryState() { + currentRebalanceId = null; + rebalanceStatus = null; + recoveredRebalance = false; + cancelRequested = false; + finalizationPending = false; + inProgressRebalanceTasks.clear(); + pendingRebalanceTasks.clear(); + pendingRecoveredTasks.clear(); + runningRebalanceTasks.clear(); + timedOutRebalanceTasks.clear(); + finishedRebalanceTasks.clear(); + queuedReconcileEvents.clear(); + hasActiveRebalance = false; + } + + private void recoverRebalanceInternal(RebalanceTask rebalanceTask) { checkNotClosed(); resetRebalance(rebalanceTask.getRebalanceId(), rebalanceTask.isCancelRequested()); recoveredRebalance = true; @@ -350,7 +512,6 @@ public void recoverRebalance(RebalanceTask rebalanceTask) { } rebalanceStatus = rebalanceTask.getRebalanceStatus(); hasActiveRebalance = false; - recoveryPending = false; return; } @@ -384,7 +545,6 @@ public void recoverRebalance(RebalanceTask rebalanceTask) { rebalanceStatus = REBALANCING; processNewRebalanceTasks(); } - recoveryPending = false; } public void finishRebalanceTask(TableBucket tableBucket, RebalanceStatus statusForBucket) { @@ -440,6 +600,10 @@ private boolean completeRebalanceTaskState( public @Nullable RebalanceProgress listRebalanceProgress(@Nullable String rebalanceId) { checkNotClosed(); + if (isNewRebalancePersistenceInProgress()) { + throw new RebalanceFailureException( + "Rebalance persistence is still in progress. Please retry later."); + } if (rebalanceId != null && currentRebalanceId != null && !rebalanceId.equals(currentRebalanceId)) { @@ -464,10 +628,19 @@ private boolean completeRebalanceTaskState( currentRebalanceId, rebalanceStatus, 0.0, progressForBucketMap); } - public void cancelRebalance(@Nullable String rebalanceId) { + public void cancelRebalance(@Nullable String rebalanceId, Consumer completion) { checkNotClosed(); + if (isNewRebalancePersistenceInProgress()) { + completion.accept( + new RebalanceFailureException( + "Rebalance persistence is still in progress. Please retry " + + "cancellation later.")); + return; + } + if (currentRebalanceId == null) { + completion.accept(null); return; } @@ -486,10 +659,19 @@ public void cancelRebalance(@Nullable String rebalanceId) { if (rebalanceStatus != null && FINAL_STATUSES.contains(rebalanceStatus)) { // do nothing for the final state rebalance task. + completion.accept(null); return; } - if (cancelRequested) { + if (cancelRequested || finalizationPending) { + completion.accept(null); + return; + } + if (persistenceInProgress) { + completion.accept( + new RebalanceFailureException( + "Another rebalance state update is still being persisted. Please " + + "retry cancellation later.")); return; } @@ -503,57 +685,52 @@ public void cancelRebalance(@Nullable String rebalanceId) { allRebalancePlans(), true, canceledBuckets); - try { - zkClient.registerRebalanceTask(cancellationTask); - } catch (Exception e) { - boolean persisted; - try { - persisted = isCancellationPersisted(cancellationTask); - } catch (Exception verificationFailure) { - e.addSuppressed(verificationFailure); - throw new RebalanceFailureException( - "Failed to persist rebalance cancellation request.", e); - } - if (!persisted) { - throw new RebalanceFailureException( - "Failed to persist rebalance cancellation request.", e); - } - LOG.warn( - "Cancellation for rebalance {} was persisted despite the write error. " - + "Continue applying it locally.", - currentRebalanceId, - e); - } - - cancelRequested = true; - cancelPendingTasks(tasksToCancel); - - // Admitted tasks that have not changed anything yet can be given up on right away: there - // is no half-applied assignment to drain, so cancellation does not have to wait for them. - for (RebalanceTaskAttempt attempt : activeAttempts()) { - if (tasksToCancel.contains(attempt.executionKey.getTableBucket())) { - finishRebalanceTask(attempt.executionKey, CANCELED); - } - } - - if (inProgressRebalanceTasks.isEmpty() && !FINAL_STATUSES.contains(rebalanceStatus)) { - finalizeRebalance(); - } - LOG.info( - "Accepted cancellation for rebalance {}. Running and timed-out tasks will be " - + "drained before the rebalance becomes canceled.", - currentRebalanceId); + persistRebalanceTask( + cancellationTask, + failure -> { + if (failure != null) { + completion.accept( + new RebalanceFailureException( + "Failed to persist rebalance cancellation request.", + failure)); + return; + } + + try { + cancelRequested = true; + cancelPendingTasks(tasksToCancel); + + // An admitted task still at its origin has no intermediate assignment to + // drain, so cancellation can finish it immediately. + for (RebalanceTaskAttempt attempt : activeAttempts()) { + TableBucket bucket = attempt.executionKey.getTableBucket(); + RebalanceResultForBucket result = inProgressRebalanceTasks.get(bucket); + if (tasksToCancel.contains(bucket) + && result != null + && rebalanceExecutor.isRebalanceTaskAtOrigin(result.plan())) { + finishRebalanceTask(attempt.executionKey, CANCELED); + } + } + + if (inProgressRebalanceTasks.isEmpty() + && !FINAL_STATUSES.contains(rebalanceStatus)) { + finalizeRebalance(); + } + LOG.info( + "Accepted cancellation for rebalance {}. Running and timed-out " + + "tasks will be drained before the rebalance becomes " + + "canceled.", + currentRebalanceId); + completion.accept(null); + } catch (Throwable t) { + completion.accept(t); + } + }); } - private boolean isCancellationPersisted(RebalanceTask expected) throws Exception { - Optional persisted = zkClient.getRebalanceTask(); - if (!persisted.isPresent()) { - return false; - } - RebalanceTask persistedTask = persisted.get(); - return persistedTask.getRebalanceId().equals(expected.getRebalanceId()) - && persistedTask.isCancelRequested() - && persistedTask.getCanceledBuckets().containsAll(expected.getCanceledBuckets()); + private boolean isNewRebalancePersistenceInProgress() { + return persistenceInProgress + && !Objects.equals(pendingPersistenceRebalanceId, currentRebalanceId); } private Set findTasksToCancel() { @@ -596,7 +773,10 @@ private void cancelPendingTasks(Set tasksToCancel) { */ public boolean hasInProgressRebalance() { checkNotClosed(); - return recoveryPending || finalizationPending || !inProgressRebalanceTasks.isEmpty(); + return recoveryPending + || persistenceInProgress + || finalizationPending + || !inProgressRebalanceTasks.isEmpty(); } public RebalanceTask generateRebalanceTask(List goalsByPriority) { @@ -820,40 +1000,45 @@ private void finalizeRebalance() { private void persistFinalStatus() { checkNotClosed(); + if (persistenceInProgress) { + return; + } RebalanceStatus finalStatus = aggregateFinalStatus(); - try { - zkClient.registerRebalanceTask( - new RebalanceTask( + persistRebalanceTask( + new RebalanceTask( + currentRebalanceId, + finalStatus, + allRebalancePlans(), + cancelRequested, + canceledBuckets()), + failure -> { + if (failure != null) { + rebalanceStatus = REBALANCING; + finalizationPending = true; + LOG.error( + "Failed to persist final state for rebalance {}. It will be " + + "retried.", + currentRebalanceId, + failure); + return; + } + + rebalanceStatus = finalStatus; + finalizationPending = false; + inProgressRebalanceTasks.clear(); + pendingRebalanceTasks.clear(); + pendingRecoveredTasks.clear(); + runningRebalanceTasks.clear(); + timedOutRebalanceTasks.clear(); + queuedReconcileEvents.clear(); + hasActiveRebalance = false; + + LOG.info( + "Rebalance {} reached final status {} in {} ms.", currentRebalanceId, finalStatus, - allRebalancePlans(), - cancelRequested, - canceledBuckets())); - } catch (Exception e) { - rebalanceStatus = REBALANCING; - finalizationPending = true; - LOG.error( - "Failed to persist final state for rebalance {}. It will be retried.", - currentRebalanceId, - e); - return; - } - - rebalanceStatus = finalStatus; - finalizationPending = false; - inProgressRebalanceTasks.clear(); - pendingRebalanceTasks.clear(); - pendingRecoveredTasks.clear(); - runningRebalanceTasks.clear(); - timedOutRebalanceTasks.clear(); - queuedReconcileEvents.clear(); - hasActiveRebalance = false; - - LOG.info( - "Rebalance {} reached final status {} in {} ms.", - currentRebalanceId, - finalStatus, - System.currentTimeMillis() - registerTime); + System.currentTimeMillis() - registerTime); + }); } private void resetRebalance(String rebalanceId, boolean cancelRequested) { @@ -1157,6 +1342,7 @@ public void stopTimeoutChecker() { } public void close() { + stopRecovery(); stopTimeoutChecker(); isClosed = true; } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStore.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStore.java new file mode 100644 index 00000000000..cb4c0b776af --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStore.java @@ -0,0 +1,274 @@ +/* + * 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.fluss.server.coordinator.rebalance; + +import org.apache.fluss.fs.FSDataInputStream; +import org.apache.fluss.fs.FSDataOutputStream; +import org.apache.fluss.fs.FileStatus; +import org.apache.fluss.fs.FileSystem; +import org.apache.fluss.fs.FsPath; +import org.apache.fluss.server.zk.ZooKeeperClient; +import org.apache.fluss.server.zk.ZooKeeperClient.VersionedData; +import org.apache.fluss.server.zk.data.RebalanceTask; +import org.apache.fluss.server.zk.data.RebalanceTaskHandle; +import org.apache.fluss.server.zk.data.RebalanceTaskJsonSerde; +import org.apache.fluss.server.zk.data.RebalanceTaskZNodeData; +import org.apache.fluss.server.zk.data.ZkVersion; +import org.apache.fluss.utils.FlussPaths; +import org.apache.fluss.utils.IOUtils; +import org.apache.fluss.utils.RetryUtils; +import org.apache.fluss.utils.json.JsonSerdeUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import static org.apache.fluss.utils.Preconditions.checkState; + +/** Persists rebalance tasks inline in ZooKeeper or as remote files referenced by ZooKeeper. */ +public final class RebalanceTaskStore { + + private static final Logger LOG = LoggerFactory.getLogger(RebalanceTaskStore.class); + + private static final int MAX_RETRIES = 3; + private static final long INITIAL_BACKOFF_MS = 100L; + private static final long MAX_BACKOFF_MS = 1000L; + private static final long ORPHAN_FILE_RETENTION_MS = 60 * 60 * 1000L; + + private final ZooKeeperClient zkClient; + private final String remoteDataDir; + + public RebalanceTaskStore(ZooKeeperClient zkClient, String remoteDataDir) { + this.zkClient = zkClient; + this.remoteDataDir = remoteDataDir; + } + + /** Loads the currently committed rebalance task, resolving a remote handle when necessary. */ + public Optional load() throws Exception { + Optional> stored = + zkClient.getRebalanceTaskDataWithVersion(); + if (!stored.isPresent()) { + return Optional.empty(); + } + + RebalanceTaskZNodeData data = stored.get().data(); + if (data.isInline()) { + return Optional.of(data.getInlineTask()); + } + + RebalanceTaskHandle handle = data.getRemoteTaskHandle(); + RebalanceTask task = readTask(handle.getTaskPath()); + checkState( + handle.getRebalanceId().equals(task.getRebalanceId()), + "Rebalance id %s in %s does not match handle id %s.", + task.getRebalanceId(), + handle.getTaskPath(), + handle.getRebalanceId()); + return Optional.of(task); + } + + /** + * Persists a task and atomically changes the rebalance znode to the new representation. Remote + * files become immutable once their handle is committed. + */ + public void persist( + RebalanceTask task, int expectedCoordinatorEpochZkVersion, boolean storeRemotely) + throws Exception { + Optional> previous = + zkClient.getRebalanceTaskDataWithVersion(); + int expectedRebalanceZkVersion = + previous.map(VersionedData::zkVersion) + .orElse(ZkVersion.UNKNOWN_VERSION.getVersion()); + + FsPath createdFile = null; + RebalanceTaskZNodeData newData; + if (storeRemotely) { + byte[] serializedTask = + JsonSerdeUtils.writeValueAsBytes(task, RebalanceTaskJsonSerde.INSTANCE); + createdFile = + FlussPaths.remoteRebalanceTaskPath( + remoteDataDir, task.getRebalanceId(), UUID.randomUUID()); + writeTask(createdFile, serializedTask, task.getRebalanceId()); + newData = + RebalanceTaskZNodeData.remote( + new RebalanceTaskHandle(task.getRebalanceId(), createdFile)); + } else { + newData = RebalanceTaskZNodeData.inline(task); + } + + boolean committed = false; + try { + zkClient.upsertRebalanceTaskData( + newData, expectedRebalanceZkVersion, expectedCoordinatorEpochZkVersion); + committed = true; + } catch (Exception writeFailure) { + try { + committed = isCommitted(newData); + } catch (Exception verificationFailure) { + writeFailure.addSuppressed(verificationFailure); + // The pointer may have committed. Keep the file until recovery or orphan cleanup + // can determine whether it is referenced. + throw writeFailure; + } + if (!committed) { + deleteFile(createdFile); + throw writeFailure; + } + LOG.warn( + "Rebalance task {} was persisted despite the ZooKeeper write error.", + task.getRebalanceId(), + writeFailure); + } + + if (committed && previous.isPresent()) { + deletePreviousRemoteFile(previous.get().data(), createdFile); + } + } + + private boolean isCommitted(RebalanceTaskZNodeData expected) throws Exception { + Optional> current = + zkClient.getRebalanceTaskDataWithVersion(); + if (!current.isPresent()) { + return false; + } + RebalanceTaskZNodeData actual = current.get().data(); + if (expected.isInline() != actual.isInline()) { + return false; + } + return expected.isInline() + ? expected.getInlineTask().equals(actual.getInlineTask()) + : expected.getRemoteTaskHandle().equals(actual.getRemoteTaskHandle()); + } + + private void writeTask(FsPath path, byte[] bytes, String rebalanceId) throws IOException { + RetryUtils.executeIOWithRetry( + () -> { + FileSystem fileSystem = path.getFileSystem(); + FsPath parent = path.getParent(); + if (parent != null && !fileSystem.exists(parent)) { + fileSystem.mkdirs(parent); + } + try (FSDataOutputStream output = + fileSystem.create(path, FileSystem.WriteMode.OVERWRITE)) { + output.write(bytes); + } + return null; + }, + "write rebalance task " + rebalanceId, + MAX_RETRIES, + INITIAL_BACKOFF_MS, + MAX_BACKOFF_MS); + } + + private RebalanceTask readTask(FsPath path) throws IOException { + return RetryUtils.executeIOWithRetry( + () -> { + try (FSDataInputStream input = path.getFileSystem().open(path); + ByteArrayOutputStream output = new ByteArrayOutputStream()) { + IOUtils.copyBytes(input, output, false); + return JsonSerdeUtils.readValue( + output.toByteArray(), RebalanceTaskJsonSerde.INSTANCE); + } + }, + "read rebalance task " + path, + MAX_RETRIES, + INITIAL_BACKOFF_MS, + MAX_BACKOFF_MS); + } + + private void deletePreviousRemoteFile(RebalanceTaskZNodeData previous, FsPath currentFile) { + if (previous.isInline()) { + return; + } + FsPath previousFile = previous.getRemoteTaskHandle().getTaskPath(); + if (!previousFile.equals(currentFile)) { + deleteFile(previousFile); + } + } + + private void deleteFile(FsPath path) { + if (path == null) { + return; + } + try { + FileSystem fileSystem = path.getFileSystem(); + if (fileSystem.exists(path)) { + fileSystem.delete(path, false); + } + } catch (Exception e) { + LOG.warn("Failed to delete rebalance task file {}.", path, e); + } + } + + void cleanupOrphanFiles() { + FsPath rebalanceDir = FlussPaths.remoteRebalanceDir(remoteDataDir); + try { + FileSystem fileSystem = rebalanceDir.getFileSystem(); + if (!fileSystem.exists(rebalanceDir)) { + return; + } + + // Re-read the pointer so cleanup cannot remove a concurrently committed task. The age + // guard also protects a new leader's file before its pointer is visible in ZooKeeper. + Set retainedFiles = new HashSet<>(); + Optional> current = + zkClient.getRebalanceTaskDataWithVersion(); + if (current.isPresent() && !current.get().data().isInline()) { + FsPath taskPath = current.get().data().getRemoteTaskHandle().getTaskPath(); + retainedFiles.add(fileSystem.getFileStatus(taskPath).getPath()); + } + + long cutoffMillis = System.currentTimeMillis() - ORPHAN_FILE_RETENTION_MS; + FileStatus[] rebalanceDirectories = fileSystem.listStatus(rebalanceDir); + if (rebalanceDirectories == null) { + return; + } + for (FileStatus rebalanceStatus : rebalanceDirectories) { + if (!rebalanceStatus.isDir()) { + continue; + } + + FsPath rebalancePath = rebalanceStatus.getPath(); + FileStatus[] taskFiles = fileSystem.listStatus(rebalancePath); + if (taskFiles == null) { + continue; + } + for (FileStatus taskStatus : taskFiles) { + if (!taskStatus.isDir() + && !retainedFiles.contains(taskStatus.getPath()) + && taskStatus.getModificationTime() < cutoffMillis) { + fileSystem.delete(taskStatus.getPath(), false); + } + } + + FileStatus[] remainingFiles = fileSystem.listStatus(rebalancePath); + if (remainingFiles != null && remainingFiles.length == 0) { + fileSystem.delete(rebalancePath, false); + } + } + } catch (Exception e) { + LOG.warn("Failed to clean orphan rebalance task files under {}.", rebalanceDir, e); + } + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java index 1fce6aae013..cb10d036819 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/ZooKeeperClient.java @@ -59,6 +59,7 @@ import org.apache.fluss.server.zk.data.PartitionAssignment; import org.apache.fluss.server.zk.data.PartitionRegistration; import org.apache.fluss.server.zk.data.RebalanceTask; +import org.apache.fluss.server.zk.data.RebalanceTaskZNodeData; import org.apache.fluss.server.zk.data.RemoteLogManifestHandle; import org.apache.fluss.server.zk.data.ResourceAcl; import org.apache.fluss.server.zk.data.ServerTags; @@ -2254,6 +2255,39 @@ public Optional getRebalanceTask() throws Exception { return getOrEmpty(path).map(RebalanceZNode::decode); } + /** Gets the rebalance znode data together with the ZK version captured by the same read. */ + public Optional> getRebalanceTaskDataWithVersion() + throws Exception { + Stat stat = new Stat(); + Optional bytes = getDataWithStat(RebalanceZNode.path(), stat); + return bytes.map(RebalanceZNode::decodeData) + .map(data -> new VersionedData<>(data, stat.getVersion())); + } + + /** + * Creates or updates the rebalance znode using both coordinator-epoch fencing and znode CAS. + */ + public void upsertRebalanceTaskData( + RebalanceTaskZNodeData data, + int expectedRebalanceZkVersion, + int expectedCoordinatorEpochZkVersion) + throws Exception { + String path = RebalanceZNode.path(); + byte[] encoded = RebalanceZNode.encode(data); + if (expectedRebalanceZkVersion == ZkVersion.UNKNOWN_VERSION.getVersion()) { + createRecursiveWithEpochCheck(path, encoded, expectedCoordinatorEpochZkVersion, true); + return; + } + CuratorOp operation = + zkClient.transactionOp() + .setData() + .withVersion(expectedRebalanceZkVersion) + .forPath(path, encoded); + zkClient.transaction() + .forOperations( + wrapRequestWithEpochCheck(operation, expectedCoordinatorEpochZkVersion)); + } + /** Deletes the rebalance task from ZooKeeper. Only for testing propose now */ @VisibleForTesting public void deleteRebalanceTask() throws Exception { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddress.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddress.java index 7759e66b89b..afa1ea12b71 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddress.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddress.java @@ -19,8 +19,13 @@ import org.apache.fluss.cluster.Endpoint; +import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import java.util.Set; + +import static java.util.Collections.emptySet; /** * The address information of an active coordinator stored in {@link ZkData.CoordinatorLeaderZNode}. @@ -28,12 +33,23 @@ * @see CoordinatorAddressJsonSerde for json serialization and deserialization. */ public class CoordinatorAddress { + + /** Capability indicating that a coordinator can recover remote rebalance task handles. */ + public static final String REMOTE_REBALANCE_TASK_FEATURE = "remote_rebalance_task"; + private final String id; private final List endpoints; + private final Set supportedFeatures; public CoordinatorAddress(String id, List endpoints) { + this(id, endpoints, emptySet()); + } + + /** Creates a coordinator address with the features supported by this server binary. */ + public CoordinatorAddress(String id, List endpoints, Set supportedFeatures) { this.id = id; this.endpoints = endpoints; + this.supportedFeatures = Collections.unmodifiableSet(new HashSet<>(supportedFeatures)); } public String getId() { @@ -44,22 +60,42 @@ public List getEndpoints() { return endpoints; } + /** Returns the coordinator capabilities used to gate rolling-upgrade-sensitive formats. */ + public Set getSupportedFeatures() { + return supportedFeatures; + } + + /** Returns whether this coordinator advertises the given capability. */ + public boolean supportsFeature(String feature) { + return supportedFeatures.contains(feature); + } + @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } CoordinatorAddress that = (CoordinatorAddress) o; - return Objects.equals(id, that.id) && Objects.equals(endpoints, that.endpoints); + return Objects.equals(id, that.id) + && Objects.equals(endpoints, that.endpoints) + && Objects.equals(supportedFeatures, that.supportedFeatures); } @Override public int hashCode() { - return Objects.hash(id, endpoints); + return Objects.hash(id, endpoints, supportedFeatures); } @Override public String toString() { - return "CoordinatorAddress{" + "id='" + id + '\'' + ", endpoints=" + endpoints + '}'; + return "CoordinatorAddress{" + + "id='" + + id + + '\'' + + ", endpoints=" + + endpoints + + ", supportedFeatures=" + + supportedFeatures + + '}'; } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerde.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerde.java index 9b577df5a28..a26cdd19600 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerde.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerde.java @@ -26,7 +26,11 @@ import java.io.IOException; import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; import java.util.List; +import java.util.Set; +import java.util.TreeSet; /** Json serializer and deserializer for {@link CoordinatorAddress}. */ @Internal @@ -35,12 +39,13 @@ public class CoordinatorAddressJsonSerde public static final CoordinatorAddressJsonSerde INSTANCE = new CoordinatorAddressJsonSerde(); private static final String VERSION_KEY = "version"; - private static final int VERSION = 2; + private static final int VERSION = 3; private static final String ID = "id"; private static final String HOST = "host"; private static final String PORT = "port"; private static final String LISTENERS = "listeners"; + private static final String SUPPORTED_FEATURES = "supported_features"; private static void writeVersion(JsonGenerator generator) throws IOException { generator.writeNumberField(VERSION_KEY, VERSION); @@ -54,6 +59,11 @@ public void serialize(CoordinatorAddress coordinatorAddress, JsonGenerator gener generator.writeStringField(ID, coordinatorAddress.getId()); generator.writeStringField( LISTENERS, Endpoint.toListenersString(coordinatorAddress.getEndpoints())); + generator.writeArrayFieldStart(SUPPORTED_FEATURES); + for (String feature : new TreeSet<>(coordinatorAddress.getSupportedFeatures())) { + generator.writeString(feature); + } + generator.writeEndArray(); generator.writeEndObject(); } @@ -62,13 +72,21 @@ public CoordinatorAddress deserialize(JsonNode node) { int version = node.get(VERSION_KEY).asInt(); String id = node.get(ID).asText(); List endpoints; + Set supportedFeatures = new HashSet<>(); if (version == 1) { String host = node.get(HOST).asText(); int port = node.get(PORT).asInt(); endpoints = Collections.singletonList(new Endpoint(host, port, "CLIENT")); } else { endpoints = Endpoint.fromListenersString(node.get(LISTENERS).asText()); + JsonNode features = node.get(SUPPORTED_FEATURES); + if (features != null) { + Iterator elements = features.elements(); + while (elements.hasNext()) { + supportedFeatures.add(elements.next().asText()); + } + } } - return new CoordinatorAddress(id, endpoints); + return new CoordinatorAddress(id, endpoints, supportedFeatures); } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskHandle.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskHandle.java new file mode 100644 index 00000000000..43dc5f99d6c --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskHandle.java @@ -0,0 +1,74 @@ +/* + * 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.fluss.server.zk.data; + +import org.apache.fluss.fs.FsPath; + +import java.util.Objects; + +/** A ZooKeeper handle for a rebalance task stored in remote storage. */ +public final class RebalanceTaskHandle { + + private final String rebalanceId; + private final FsPath taskPath; + + /** Creates a handle for the immutable task file referenced by ZooKeeper. */ + public RebalanceTaskHandle(String rebalanceId, FsPath taskPath) { + this.rebalanceId = rebalanceId; + this.taskPath = taskPath; + } + + /** Returns the rebalance identifier stored in both the handle and task file. */ + public String getRebalanceId() { + return rebalanceId; + } + + /** Returns the remote path of the serialized task. */ + public FsPath getTaskPath() { + return taskPath; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RebalanceTaskHandle that = (RebalanceTaskHandle) o; + return Objects.equals(rebalanceId, that.rebalanceId) + && Objects.equals(taskPath, that.taskPath); + } + + @Override + public int hashCode() { + return Objects.hash(rebalanceId, taskPath); + } + + @Override + public String toString() { + return "RebalanceTaskHandle{" + + "rebalanceId='" + + rebalanceId + + '\'' + + ", taskPath=" + + taskPath + + '}'; + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeData.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeData.java new file mode 100644 index 00000000000..158d1d8c472 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeData.java @@ -0,0 +1,64 @@ +/* + * 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.fluss.server.zk.data; + +import javax.annotation.Nullable; + +import static org.apache.fluss.utils.Preconditions.checkArgument; +import static org.apache.fluss.utils.Preconditions.checkNotNull; + +/** Data stored in the rebalance znode, either an inline task or a remote task handle. */ +public final class RebalanceTaskZNodeData { + + private final @Nullable RebalanceTask inlineTask; + private final @Nullable RebalanceTaskHandle remoteTaskHandle; + + private RebalanceTaskZNodeData( + @Nullable RebalanceTask inlineTask, @Nullable RebalanceTaskHandle remoteTaskHandle) { + checkArgument( + (inlineTask == null) != (remoteTaskHandle == null), + "Exactly one rebalance task representation must be set."); + this.inlineTask = inlineTask; + this.remoteTaskHandle = remoteTaskHandle; + } + + /** Creates znode data containing a legacy inline task. */ + public static RebalanceTaskZNodeData inline(RebalanceTask task) { + return new RebalanceTaskZNodeData(checkNotNull(task), null); + } + + /** Creates znode data pointing to a task in remote storage. */ + public static RebalanceTaskZNodeData remote(RebalanceTaskHandle handle) { + return new RebalanceTaskZNodeData(null, checkNotNull(handle)); + } + + /** Returns whether this znode embeds the task rather than referencing remote storage. */ + public boolean isInline() { + return inlineTask != null; + } + + /** Returns the inline task. */ + public RebalanceTask getInlineTask() { + return checkNotNull(inlineTask, "The rebalance task is stored remotely."); + } + + /** Returns the remote task handle. */ + public RebalanceTaskHandle getRemoteTaskHandle() { + return checkNotNull(remoteTaskHandle, "The rebalance task is stored inline."); + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerde.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerde.java new file mode 100644 index 00000000000..912c3af3cfe --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerde.java @@ -0,0 +1,75 @@ +/* + * 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.fluss.server.zk.data; + +import org.apache.fluss.fs.FsPath; +import org.apache.fluss.shaded.jackson2.com.fasterxml.jackson.core.JsonGenerator; +import org.apache.fluss.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode; +import org.apache.fluss.utils.json.JsonDeserializer; +import org.apache.fluss.utils.json.JsonSerializer; + +import java.io.IOException; + +/** JSON serde for inline and remote rebalance task znode formats. */ +public final class RebalanceTaskZNodeJsonSerde + implements JsonSerializer, + JsonDeserializer { + + public static final RebalanceTaskZNodeJsonSerde INSTANCE = new RebalanceTaskZNodeJsonSerde(); + + private static final String VERSION_KEY = "version"; + private static final String REBALANCE_ID = "rebalance_id"; + private static final String REBALANCE_TASK_PATH = "rebalance_task_path"; + + private static final int INLINE_VERSION_1 = 1; + private static final int INLINE_VERSION_2 = 2; + private static final int REMOTE_VERSION = 3; + + @Override + public void serialize(RebalanceTaskZNodeData data, JsonGenerator generator) throws IOException { + if (data.isInline()) { + RebalanceTaskJsonSerde.INSTANCE.serialize(data.getInlineTask(), generator); + return; + } + + RebalanceTaskHandle handle = data.getRemoteTaskHandle(); + generator.writeStartObject(); + generator.writeNumberField(VERSION_KEY, REMOTE_VERSION); + generator.writeStringField(REBALANCE_ID, handle.getRebalanceId()); + generator.writeStringField(REBALANCE_TASK_PATH, handle.getTaskPath().toString()); + generator.writeEndObject(); + } + + @Override + public RebalanceTaskZNodeData deserialize(JsonNode node) { + int version = node.get(VERSION_KEY).asInt(); + if (version == INLINE_VERSION_1 || version == INLINE_VERSION_2) { + return RebalanceTaskZNodeData.inline(RebalanceTaskJsonSerde.INSTANCE.deserialize(node)); + } + if (version == REMOTE_VERSION) { + JsonNode rebalanceId = node.get(REBALANCE_ID); + JsonNode taskPath = node.get(REBALANCE_TASK_PATH); + if (rebalanceId == null || taskPath == null) { + throw new IllegalArgumentException("Invalid remote rebalance task handle."); + } + return RebalanceTaskZNodeData.remote( + new RebalanceTaskHandle(rebalanceId.asText(), new FsPath(taskPath.asText()))); + } + throw new IllegalArgumentException("Unsupported rebalance task version: " + version); + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/ZkData.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/ZkData.java index e5bdfce9531..2bc04bb5647 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/ZkData.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/ZkData.java @@ -1031,11 +1031,19 @@ public static String path() { } public static byte[] encode(RebalanceTask rebalanceTask) { - return JsonSerdeUtils.writeValueAsBytes(rebalanceTask, RebalanceTaskJsonSerde.INSTANCE); + return encode(RebalanceTaskZNodeData.inline(rebalanceTask)); + } + + public static byte[] encode(RebalanceTaskZNodeData data) { + return JsonSerdeUtils.writeValueAsBytes(data, RebalanceTaskZNodeJsonSerde.INSTANCE); } public static RebalanceTask decode(byte[] json) { - return JsonSerdeUtils.readValue(json, RebalanceTaskJsonSerde.INSTANCE); + return decodeData(json).getInlineTask(); + } + + public static RebalanceTaskZNodeData decodeData(byte[] json) { + return JsonSerdeUtils.readValue(json, RebalanceTaskZNodeJsonSerde.INSTANCE); } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessorTestBase.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessorTestBase.java index 8397282f4aa..084854d135f 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessorTestBase.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorEventProcessorTestBase.java @@ -171,6 +171,8 @@ void beforeEach() { eventProcessor.startup(); metadataManager.createDatabase( defaultDatabase, DatabaseDescriptor.builder().build(), false); + eventProcessor.startRebalanceRecovery(); + waitUntilRebalanceRecoveryCompletes(); completedSnapshotStoreManager = eventProcessor.completedSnapshotStoreManager(); } @@ -280,6 +282,21 @@ protected T fromCtx(Function retrieveFunction) throws return event.getResultFuture().get(30, TimeUnit.SECONDS); } + /** Waits until the asynchronously loaded rebalance state has been applied by the event loop. */ + protected void waitUntilRebalanceRecoveryCompletes() { + retry( + Duration.ofMinutes(1), + () -> { + boolean recoveryPending = + fromCtx( + ctx -> + eventProcessor + .getRebalanceManager() + .isRecoveryPending()); + assertThat(recoveryPending).isFalse(); + }); + } + /** Submits an ISR update through the coordinator event loop. */ protected AdjustIsrResultForBucket submitAdjustIsr( TableBucket tableBucket, LeaderAndIsr newLeaderAndIsr) throws Exception { diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorRebalanceTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorRebalanceTest.java index 95cd7d70c0c..14653178f85 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorRebalanceTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorRebalanceTest.java @@ -553,6 +553,8 @@ void testNewRebalanceConvergesAfterFailureAndRestart(boolean targetUnavailable) zookeeperClient.deleteRebalanceTask(); eventProcessor = buildCoordinatorEventProcessor(clock); eventProcessor.startup(); + eventProcessor.startRebalanceRecovery(); + waitUntilRebalanceRecoveryCompletes(); registerTabletServer(3); initCoordinatorChannel(); List origin = Arrays.asList(0, 1, 2); @@ -583,9 +585,13 @@ void testNewRebalanceConvergesAfterFailureAndRestart(boolean targetUnavailable) retry( Duration.ofMinutes(1), () -> assertThat(rebalanceStatus(bucket)).isEqualTo(RebalanceStatus.FAILED)); - assertThat(hasInProgressRebalance()).isFalse(); - assertThat(zookeeperClient.getRebalanceTask().get().getRebalanceStatus()) - .isEqualTo(RebalanceStatus.FAILED); + retry( + Duration.ofMinutes(1), + () -> { + assertThat(hasInProgressRebalance()).isFalse(); + assertThat(zookeeperClient.getRebalanceTask().get().getRebalanceStatus()) + .isEqualTo(RebalanceStatus.FAILED); + }); assertThat( zookeeperClient .getTableAssignment(tableId) @@ -648,11 +654,7 @@ void testRestartAfterCancellationDoesNotStartPendingBucketAfterLeaderChange(bool : new RebalancePlanForBucket(pending, 0, 0, origin, target)); String rebalanceId = "cancel-before-restart"; registerRebalance(rebalanceId, plan); - fromCtx( - ctx -> { - eventProcessor.getRebalanceManager().cancelRebalance(rebalanceId); - return null; - }); + cancelRebalance(rebalanceId); assertThat(rebalanceStatus(pending)).isEqualTo(RebalanceStatus.CANCELED); assertThat(zookeeperClient.getRebalanceTask().get().isCancelRequested()).isTrue(); assertThat(hasInProgressRebalance()).isTrue(); @@ -740,15 +742,13 @@ void testCancelAfterRestartDrainsEveryIntermediateBucket() throws Exception { .get() .getBucketAssignment(recoveredIntermediate.getBucket())) .isEqualTo(new BucketAssignment(union)); - fromCtx( - ctx -> { - assertThat( - eventProcessor.isRebalanceTaskAtOrigin( - plans.get(recoveredIntermediate))) - .isFalse(); - eventProcessor.getRebalanceManager().cancelRebalance(rebalanceId); - return null; - }); + boolean intermediateAtOrigin = + fromCtx( + ctx -> + eventProcessor.isRebalanceTaskAtOrigin( + plans.get(recoveredIntermediate))); + assertThat(intermediateAtOrigin).isFalse(); + cancelRebalance(rebalanceId); assertThat(rebalanceStatus(recoveredIntermediate)) .as("A previously started migration still needs draining after recovery") .isNotEqualTo(RebalanceStatus.CANCELED); @@ -1056,6 +1056,7 @@ void testRestartCombinedMoveAtPhaseBBoundary(String boundary) throws Exception { installBlockingNotifyGateways(recoveredResponses); eventProcessor = buildCoordinatorEventProcessor(testClock); eventProcessor.startup(); + eventProcessor.startRebalanceRecovery(); retry( Duration.ofMinutes(1), () -> { @@ -1350,6 +1351,26 @@ private void registerRebalance(String id, Map completion = new CompletableFuture<>(); + fromCtx( + ctx -> { + eventProcessor + .getRebalanceManager() + .cancelRebalance( + rebalanceId, + failure -> { + if (failure == null) { + completion.complete(null); + } else { + completion.completeExceptionally(failure); + } + }); + return null; + }); + completion.get(); + } + private void restartCoordinator(@Nullable ConcurrentLinkedDeque responses) throws Exception { eventProcessor.shutdown(); @@ -1363,6 +1384,7 @@ private void restartCoordinator(@Nullable ConcurrentLinkedDeque r } eventProcessor = buildCoordinatorEventProcessor(testClock); eventProcessor.startup(); - fromCtx(ctx -> null); + eventProcessor.startRebalanceRecovery(); + waitUntilRebalanceRecoveryCompletes(); } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManagerTest.java index 8551328e29d..f50ea7152de 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManagerTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceManagerTest.java @@ -27,6 +27,7 @@ import org.apache.fluss.config.ConfigOptions; import org.apache.fluss.config.Configuration; import org.apache.fluss.exception.ConfigException; +import org.apache.fluss.exception.RebalanceFailureException; import org.apache.fluss.metadata.TableBucket; import org.apache.fluss.metadata.TableDescriptor; import org.apache.fluss.metadata.TableInfo; @@ -35,6 +36,7 @@ import org.apache.fluss.server.coordinator.event.CheckRebalanceTimeoutEvent; import org.apache.fluss.server.coordinator.event.CoordinatorEvent; import org.apache.fluss.server.coordinator.event.EventManager; +import org.apache.fluss.server.coordinator.event.RebalancePersistenceCompleteEvent; import org.apache.fluss.server.coordinator.event.ReconcileRebalanceTaskEvent; import org.apache.fluss.server.coordinator.event.RecoverRebalanceEvent; import org.apache.fluss.server.coordinator.rebalance.goal.ReplicaDistributionGoal; @@ -46,7 +48,9 @@ import org.apache.fluss.server.zk.ZooKeeperExtension; import org.apache.fluss.server.zk.data.LeaderAndIsr; import org.apache.fluss.server.zk.data.RebalanceTask; +import org.apache.fluss.server.zk.data.RebalanceTaskZNodeData; import org.apache.fluss.shaded.curator5.org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.fluss.shaded.zookeeper3.org.apache.zookeeper.KeeperException; import org.apache.fluss.testutils.common.AllCallbackWrapper; import org.apache.fluss.testutils.common.ManuallyTriggeredScheduledExecutorService; import org.apache.fluss.utils.clock.ManualClock; @@ -72,8 +76,11 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.Executor; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -157,6 +164,25 @@ void testRebalanceWithoutTask() throws Exception { .hasValue(new RebalanceTask(rebalanceId, COMPLETED, new HashMap<>())); } + @Test + void testEmptyRebalanceReportsProgressWhileFinalStatusIsPersisted() throws Exception { + rebalanceManager.close(); + ManuallyTriggeredScheduledExecutorService ioExecutor = + new ManuallyTriggeredScheduledExecutorService(); + rebalanceManager = createManager(new Configuration(), zookeeperClient, ioExecutor); + String rebalanceId = "empty-rebalance"; + + rebalanceManager.registerRebalance(rebalanceId, new HashMap<>()); + + assertThat(rebalanceManager.listRebalanceProgress(rebalanceId).status()) + .isEqualTo(REBALANCING); + + ioExecutor.triggerAll(); + + assertThat(rebalanceManager.listRebalanceProgress(rebalanceId).status()) + .isEqualTo(COMPLETED); + } + @Test void testScheduledTimeoutCheckRunsOnEventThread() throws Exception { TableBucket tb1 = new TableBucket(1L, 0); @@ -425,7 +451,7 @@ void testCancelPersistsIntentAndDrainsOnlyAdmittedTasks() throws Exception { rebalanceManager.registerRebalance("cancel-test", plans(tb1, tb2)); RebalanceExecutionKey runningAttempt = rebalanceManager.getExecutionKey(tb1); - rebalanceManager.cancelRebalance("cancel-test"); + cancelRebalance("cancel-test"); RebalanceTask storedTask = zookeeperClient.getRebalanceTask().get(); assertThat(storedTask.getRebalanceStatus()).isEqualTo(REBALANCING); @@ -452,7 +478,7 @@ void testCancelPersistsIntentAndDrainsOnlyAdmittedTasks() throws Exception { } @Test - void testCancelAcceptsCommittedWriteWhenClientReportsFailure() throws Exception { + void testCancelAcceptsCommittedWriteWhenRetryReportsBadVersion() throws Exception { rebalanceManager.close(); try (TestingZooKeeperClient testingClient = new TestingZooKeeperClient()) { rebalanceManager = createManager(new Configuration(), testingClient); @@ -462,9 +488,9 @@ void testCancelAcceptsCommittedWriteWhenClientReportsFailure() throws Exception String rebalanceId = "ambiguous-cancellation-write"; testingClient.registerRebalanceTask(new RebalanceTask(rebalanceId, NOT_STARTED, plan)); rebalanceManager.registerRebalance(rebalanceId, plan); - testingClient.failNextCancellationAfterCommit(); + testingClient.failNextCancellationAfterCommitWithBadVersion(); - rebalanceManager.cancelRebalance(rebalanceId); + cancelRebalance(rebalanceId); assertThat(testingClient.getRebalanceTask().get().isCancelRequested()).isTrue(); assertThat(rebalanceManager.isCancelRequested()).isTrue(); @@ -475,6 +501,75 @@ void testCancelAcceptsCommittedWriteWhenClientReportsFailure() throws Exception } } + @Test + void testCancelRechecksOriginAfterAsyncPersistence() throws Exception { + rebalanceManager.close(); + ManuallyTriggeredScheduledExecutorService ioExecutor = + new ManuallyTriggeredScheduledExecutorService(); + rebalanceManager = createManager(new Configuration(), zookeeperClient, ioExecutor); + TableBucket running = new TableBucket(1L, 0); + TableBucket pending = new TableBucket(1L, 1); + String rebalanceId = "cancel-origin-recheck"; + rebalanceManager.registerRebalance(rebalanceId, plans(running, pending)); + RebalanceExecutionKey runningAttempt = rebalanceManager.getExecutionKey(running); + AtomicBoolean cancellationCompleted = new AtomicBoolean(); + AtomicReference cancellationFailure = new AtomicReference<>(); + + rebalanceManager.cancelRebalance( + rebalanceId, + failure -> { + cancellationFailure.set(failure); + cancellationCompleted.set(true); + }); + rebalanceManager.finishRebalanceTask(runningAttempt, COMPLETED); + RebalanceExecutionKey newlyAdmittedAttempt = rebalanceManager.getExecutionKey(pending); + + assertThat(newlyAdmittedAttempt).isNotNull(); + assertThat(statuses(rebalanceManager).get(pending)).isEqualTo(REBALANCING); + + ioExecutor.triggerAll(); + + assertThat(cancellationCompleted).isTrue(); + assertThat(cancellationFailure).hasNullValue(); + assertThat(rebalanceManager.isCancelRequested()).isTrue(); + assertThat(statuses(rebalanceManager).get(pending)).isEqualTo(REBALANCING); + assertThat(rebalanceManager.getExecutionKey(pending)).isEqualTo(newlyAdmittedAttempt); + + rebalanceManager.finishRebalanceTask(newlyAdmittedAttempt, COMPLETED); + ioExecutor.triggerAll(); + assertThat(rebalanceManager.getRebalanceStatus()).isEqualTo(CANCELED); + } + + @Test + void testSecondCancelWhilePersistenceIsInProgressReturnsRebalanceFailure() throws Exception { + rebalanceManager.close(); + ManuallyTriggeredScheduledExecutorService ioExecutor = + new ManuallyTriggeredScheduledExecutorService(); + rebalanceManager = createManager(new Configuration(), zookeeperClient, ioExecutor); + String rebalanceId = "concurrent-cancel"; + rebalanceManager.registerRebalance(rebalanceId, plans(new TableBucket(1L, 0))); + AtomicBoolean firstCancellationCompleted = new AtomicBoolean(); + AtomicReference firstCancellationFailure = new AtomicReference<>(); + AtomicReference secondCancellationFailure = new AtomicReference<>(); + + rebalanceManager.cancelRebalance( + rebalanceId, + failure -> { + firstCancellationFailure.set(failure); + firstCancellationCompleted.set(true); + }); + rebalanceManager.cancelRebalance(rebalanceId, secondCancellationFailure::set); + + assertThat(firstCancellationCompleted).isFalse(); + assertThat(secondCancellationFailure.get()) + .isInstanceOf(RebalanceFailureException.class) + .hasMessageContaining("still being persisted"); + + ioExecutor.triggerAll(); + assertThat(firstCancellationCompleted).isTrue(); + assertThat(firstCancellationFailure).hasNullValue(); + } + @Test void testRecoverCancellationKeepsIntermediateBucketTracked() throws Exception { TableBucket originBucket = new TableBucket(1L, 0); @@ -504,7 +599,7 @@ void testCanceledRebalanceReportsFailedWhenDrainFails() throws Exception { RebalanceExecutionKey attempt = rebalanceManager.getExecutionKey(tableBucket); assertThat(rebalanceManager.timeoutRebalanceTask(attempt)).isTrue(); - rebalanceManager.cancelRebalance("cancel-drain-failure"); + cancelRebalance("cancel-drain-failure"); assertThat(rebalanceManager.prepareReconciliation(attempt)).isNotNull(); clock.advanceTime(Duration.ofMillis(2)); assertThat(rebalanceManager.prepareReconciliation(attempt)).isNull(); @@ -960,7 +1055,7 @@ void testCancelGivesUpImmediatelyOnAdmittedTaskStillAtOrigin() throws Exception rebalanceExecutor.originBuckets.add(tb1); rebalanceManager.registerRebalance("cancel-at-origin-test", plans(tb1, tb2)); - rebalanceManager.cancelRebalance("cancel-at-origin-test"); + cancelRebalance("cancel-at-origin-test"); assertThat(rebalanceManager.getRebalanceStatus()).isEqualTo(CANCELED); assertThat(rebalanceManager.hasInProgressRebalance()).isFalse(); @@ -988,7 +1083,7 @@ void testScheduledRetryPersistsFinalStatusAfterTransientFailure() throws Excepti .isEqualTo(NOT_STARTED); timeoutChecker.triggerPeriodicScheduledTasks(); - assertThat(eventManager.events.get(0)).isInstanceOf(CheckRebalanceTimeoutEvent.class); + assertThat(eventManager.events).anyMatch(CheckRebalanceTimeoutEvent.class::isInstance); rebalanceManager.checkTimeout(); assertThat(testingClient.getRebalanceTask().get().getRebalanceStatus()) @@ -1002,11 +1097,94 @@ void testScheduledRetryPersistsFinalStatusAfterTransientFailure() throws Excepti } } + @Test + void testPersistenceRunsAsynchronouslyAndFencesRequests() throws Exception { + rebalanceManager.close(); + ManuallyTriggeredScheduledExecutorService ioExecutor = + new ManuallyTriggeredScheduledExecutorService(); + rebalanceManager = createManager(new Configuration(), zookeeperClient, ioExecutor); + RebalanceTask task = + new RebalanceTask("async-persistence", NOT_STARTED, plans(new TableBucket(1L, 0))); + AtomicBoolean completed = new AtomicBoolean(); + AtomicReference failure = new AtomicReference<>(); + + rebalanceManager.persistRebalanceTask( + task, + persistenceFailure -> { + failure.set(persistenceFailure); + completed.set(true); + }); + + assertThat(completed).isFalse(); + assertThat(rebalanceManager.hasInProgressRebalance()).isTrue(); + assertThat(rebalanceManager.getRebalanceId()).isEqualTo("async-persistence"); + assertThat(zookeeperClient.getRebalanceTask()).isEmpty(); + assertThatThrownBy(() -> rebalanceManager.listRebalanceProgress(null)) + .isInstanceOf(RebalanceFailureException.class) + .hasMessageContaining("persistence is still in progress"); + AtomicReference cancellationFailure = new AtomicReference<>(); + rebalanceManager.cancelRebalance(null, cancellationFailure::set); + assertThat(cancellationFailure.get()).isInstanceOf(RebalanceFailureException.class); + + ioExecutor.triggerAll(); + + assertThat(completed).isTrue(); + assertThat(failure).hasNullValue(); + assertThat(zookeeperClient.getRebalanceTask()).contains(task); + assertThat(rebalanceManager.hasInProgressRebalance()).isFalse(); + } + + @Test + void testNewPersistenceFencesRequestsAfterFinalRecovery() throws Exception { + rebalanceManager.close(); + ManuallyTriggeredScheduledExecutorService ioExecutor = + new ManuallyTriggeredScheduledExecutorService(); + rebalanceManager = createManager(new Configuration(), zookeeperClient, ioExecutor); + TableBucket completedBucket = new TableBucket(1L, 0); + assertThat( + rebalanceManager.recoverRebalance( + new RebalanceTask( + "completed-rebalance", COMPLETED, plans(completedBucket)))) + .isTrue(); + + String newRebalanceId = "pending-rebalance"; + Map newPlan = plans(new TableBucket(2L, 0)); + RebalanceTask newTask = new RebalanceTask(newRebalanceId, NOT_STARTED, newPlan); + AtomicReference persistenceFailure = new AtomicReference<>(); + rebalanceManager.persistRebalanceTask( + newTask, + failure -> { + persistenceFailure.set(failure); + if (failure == null) { + rebalanceManager.registerRebalance(newRebalanceId, newPlan); + } + }); + + assertThat(rebalanceManager.getRebalanceId()).isEqualTo(newRebalanceId); + assertThatThrownBy(() -> rebalanceManager.listRebalanceProgress(null)) + .isInstanceOf(RebalanceFailureException.class) + .hasMessageContaining("persistence is still in progress"); + AtomicReference cancellationFailure = new AtomicReference<>(); + rebalanceManager.cancelRebalance(null, cancellationFailure::set); + assertThat(cancellationFailure.get()).isInstanceOf(RebalanceFailureException.class); + + ioExecutor.triggerAll(); + + assertThat(persistenceFailure).hasNullValue(); + assertThat(rebalanceManager.getRebalanceId()).isEqualTo(newRebalanceId); + assertThat(rebalanceManager.getRebalanceStatus()).isEqualTo(REBALANCING); + } + private RebalanceManager createManager(Configuration conf) { return createManager(conf, zookeeperClient); } private RebalanceManager createManager(Configuration conf, ZooKeeperClient client) { + return createManager(conf, client, Runnable::run); + } + + private RebalanceManager createManager( + Configuration conf, ZooKeeperClient client, Executor ioExecutor) { timeoutChecker = new ManuallyTriggeredScheduledExecutorService(); RebalanceManager manager = new RebalanceManager( @@ -1015,8 +1193,16 @@ private RebalanceManager createManager(Configuration conf, ZooKeeperClient clien eventManager, clock, conf, - new TestingScheduler(timeoutChecker)); + new TestingScheduler(timeoutChecker), + ioExecutor); manager.startup(); + try { + if (!manager.loadPersistedRebalanceTask().isPresent()) { + manager.completeEmptyRecovery(); + } + } catch (Exception e) { + throw new RuntimeException("Failed to initialize rebalance recovery for test.", e); + } return manager; } @@ -1025,6 +1211,16 @@ private void configureManager(Configuration conf) { rebalanceManager = createManager(conf); } + private void cancelRebalance(String rebalanceId) { + rebalanceManager.cancelRebalance( + rebalanceId, + failure -> { + if (failure != null) { + throw new RuntimeException(failure); + } + }); + } + private void reconfigureMaxInflightTasks(int maxInflightTasks) { rebalanceManager.reconfigure( new Configuration() @@ -1054,7 +1250,7 @@ private static ServerInfo tabletServer(int serverId) { } @Test - void testStartupFencesNewRebalanceUntilRecoveryEventRuns() throws Exception { + void testStartupFencesNewRebalanceUntilExplicitRecovery() throws Exception { TableBucket tableBucket = new TableBucket(1L, 0); RebalanceTask storedTask = new RebalanceTask("startup-recovery-test", REBALANCING, plans(tableBucket)); @@ -1071,12 +1267,11 @@ void testStartupFencesNewRebalanceUntilRecoveryEventRuns() throws Exception { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("startup recovery"); assertThat(timeoutChecker.getActivePeriodicScheduledTask()).hasSize(1); - assertThat(eventManager.events).hasSize(1); - RecoverRebalanceEvent recoveryEvent = (RecoverRebalanceEvent) eventManager.events.get(0); - assertThat(recoveryEvent.getRebalanceTask()).isEqualTo(storedTask); + assertThat(eventManager.events).isEmpty(); rebalanceExecutor.originBuckets.add(tableBucket); - rebalanceManager.recoverRebalance(recoveryEvent.getRebalanceTask()); + RebalanceTask loadedTask = rebalanceManager.loadPersistedRebalanceTask().get(); + rebalanceManager.recoverRebalance(loadedTask); assertThat(rebalanceManager.isRecoveryPending()).isFalse(); assertThat(rebalanceManager.getRebalanceId()).isEqualTo("startup-recovery-test"); assertThat(rebalanceExecutor.executedPlans).hasSize(1); @@ -1097,8 +1292,8 @@ void testNewRebalanceIsAdmittedAfterRecoveryCompletes() throws Exception { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("startup recovery"); - RecoverRebalanceEvent recoveryEvent = (RecoverRebalanceEvent) eventManager.events.get(0); - rebalanceManager.recoverRebalance(recoveryEvent.getRebalanceTask()); + RebalanceTask loadedTask = rebalanceManager.loadPersistedRebalanceTask().get(); + rebalanceManager.recoverRebalance(loadedTask); assertThat(rebalanceManager.isRecoveryPending()).isFalse(); assertThat(rebalanceManager.hasInProgressRebalance()).isFalse(); @@ -1109,18 +1304,15 @@ void testNewRebalanceIsAdmittedAfterRecoveryCompletes() throws Exception { } @Test - void testRecoveryFailureKeepsNewRebalanceFenced() throws Exception { + void testRecoveryFailureIsRetriedWhileNewRebalanceRemainsFenced() throws Exception { TableBucket recoveredBucket = new TableBucket(1L, 0); zookeeperClient.registerRebalanceTask( new RebalanceTask("failed-recovery", REBALANCING, plans(recoveredBucket))); configureManager(new Configuration()); rebalanceExecutor.failOriginCheck = true; - RecoverRebalanceEvent recoveryEvent = (RecoverRebalanceEvent) eventManager.events.get(0); - assertThatThrownBy( - () -> rebalanceManager.recoverRebalance(recoveryEvent.getRebalanceTask())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("origin check failed"); + RebalanceTask loadedTask = rebalanceManager.loadPersistedRebalanceTask().get(); + assertThat(rebalanceManager.recoverRebalance(loadedTask)).isFalse(); assertThat(rebalanceManager.isRecoveryPending()).isTrue(); assertThat(rebalanceManager.hasInProgressRebalance()).isTrue(); @@ -1130,6 +1322,17 @@ void testRecoveryFailureKeepsNewRebalanceFenced() throws Exception { "too-early", plans(new TableBucket(2L, 0)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("startup recovery"); + + rebalanceExecutor.failOriginCheck = false; + timeoutChecker.triggerNonPeriodicScheduledTask(); + RecoverRebalanceEvent retryEvent = + (RecoverRebalanceEvent) + eventManager.events.stream() + .filter(RecoverRebalanceEvent.class::isInstance) + .findFirst() + .get(); + assertThat(rebalanceManager.recoverRebalance(retryEvent.getRebalanceTask())).isTrue(); + assertThat(rebalanceManager.isRecoveryPending()).isFalse(); } private static Map plans(TableBucket... tableBuckets) { @@ -1217,7 +1420,7 @@ public boolean isRebalanceTaskDeleted(TableBucket tableBucket) { private static final class TestingZooKeeperClient extends ZooKeeperClient { private boolean failNextFinalWrite; - private boolean failNextCancellationAfterCommit; + private boolean failNextCancellationAfterCommitWithBadVersion; private TestingZooKeeperClient() { super(createCuratorFrameworkWrapper(), createConfiguration()); @@ -1227,26 +1430,33 @@ private void failNextFinalWrite() { failNextFinalWrite = true; } - private void failNextCancellationAfterCommit() { - failNextCancellationAfterCommit = true; + private void failNextCancellationAfterCommitWithBadVersion() { + failNextCancellationAfterCommitWithBadVersion = true; } @Override - public void registerRebalanceTask(RebalanceTask rebalanceTask) throws Exception { + public void upsertRebalanceTaskData( + RebalanceTaskZNodeData data, + int expectedRebalanceZkVersion, + int expectedCoordinatorEpochZkVersion) + throws Exception { + RebalanceTask rebalanceTask = data.getInlineTask(); if (failNextFinalWrite && RebalanceStatus.FINAL_STATUSES.contains( rebalanceTask.getRebalanceStatus())) { failNextFinalWrite = false; throw new RuntimeException("Expected finalization failure"); } - if (failNextCancellationAfterCommit + if (failNextCancellationAfterCommitWithBadVersion && rebalanceTask.getRebalanceStatus() == REBALANCING && rebalanceTask.isCancelRequested()) { - failNextCancellationAfterCommit = false; - super.registerRebalanceTask(rebalanceTask); - throw new RuntimeException("Expected ambiguous cancellation write"); + failNextCancellationAfterCommitWithBadVersion = false; + super.upsertRebalanceTaskData( + data, expectedRebalanceZkVersion, expectedCoordinatorEpochZkVersion); + throw new KeeperException.BadVersionException(); } - super.registerRebalanceTask(rebalanceTask); + super.upsertRebalanceTaskData( + data, expectedRebalanceZkVersion, expectedCoordinatorEpochZkVersion); } private static CuratorFrameworkWithUnhandledErrorListener createCuratorFrameworkWrapper() { @@ -1277,6 +1487,9 @@ private static final class RecordingEventManager implements EventManager { @Override public void put(CoordinatorEvent event) { events.add(event); + if (event instanceof RebalancePersistenceCompleteEvent) { + ((RebalancePersistenceCompleteEvent) event).complete(); + } } } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStoreTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStoreTest.java new file mode 100644 index 00000000000..7d339cee697 --- /dev/null +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/rebalance/RebalanceTaskStoreTest.java @@ -0,0 +1,221 @@ +/* + * 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.fluss.server.coordinator.rebalance; + +import org.apache.fluss.cluster.rebalance.RebalancePlanForBucket; +import org.apache.fluss.fs.FSDataOutputStream; +import org.apache.fluss.fs.FileSystem; +import org.apache.fluss.fs.FsPath; +import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.server.zk.NOPErrorHandler; +import org.apache.fluss.server.zk.ZkEpoch; +import org.apache.fluss.server.zk.ZooKeeperClient; +import org.apache.fluss.server.zk.ZooKeeperExtension; +import org.apache.fluss.server.zk.data.RebalanceTask; +import org.apache.fluss.server.zk.data.RebalanceTaskHandle; +import org.apache.fluss.server.zk.data.RebalanceTaskZNodeData; +import org.apache.fluss.shaded.zookeeper3.org.apache.zookeeper.KeeperException; +import org.apache.fluss.testutils.common.AllCallbackWrapper; +import org.apache.fluss.utils.FlussPaths; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.attribute.FileTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +import static org.apache.fluss.cluster.rebalance.RebalanceStatus.COMPLETED; +import static org.apache.fluss.cluster.rebalance.RebalanceStatus.REBALANCING; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Tests for {@link RebalanceTaskStore}. */ +class RebalanceTaskStoreTest { + + @RegisterExtension + public static final AllCallbackWrapper ZOOKEEPER = + new AllCallbackWrapper<>(new ZooKeeperExtension()); + + private static ZooKeeperClient zkClient; + + private ZkEpoch zkEpoch; + private RebalanceTaskStore store; + + @BeforeAll + static void beforeAll() { + zkClient = ZOOKEEPER.getCustomExtension().getZooKeeperClient(NOPErrorHandler.INSTANCE); + } + + @BeforeEach + void beforeEach() throws Exception { + zkEpoch = zkClient.fenceBecomeCoordinatorLeader("leader"); + store = new RebalanceTaskStore(zkClient, zkClient.getDefaultRemoteDataDir()); + } + + @AfterEach + void afterEach() throws Exception { + ZOOKEEPER.getCustomExtension().cleanupRoot(); + FsPath rebalanceDir = new FsPath(zkClient.getDefaultRemoteDataDir(), "rebalance"); + if (rebalanceDir.getFileSystem().exists(rebalanceDir)) { + rebalanceDir.getFileSystem().delete(rebalanceDir, true); + } + } + + @AfterAll + static void afterAll() { + zkClient.close(); + } + + @Test + void testPersistAndLoadRemoteTask() throws Exception { + RebalanceTask initialTask = task("rebalance-1", REBALANCING); + store.persist(initialTask, zkEpoch.getCoordinatorEpochZkVersion(), true); + + RebalanceTaskHandle initialHandle = getRemoteHandle(); + assertThat(initialHandle.getTaskPath().toString()) + .contains("/rebalance/rebalance-1/") + .endsWith(".task"); + assertThat(initialHandle.getTaskPath().getFileSystem().exists(initialHandle.getTaskPath())) + .isTrue(); + FsPath orphanFile = new FsPath(initialHandle.getTaskPath().getParent(), "orphan.task"); + try (FSDataOutputStream output = + orphanFile.getFileSystem().create(orphanFile, FileSystem.WriteMode.NO_OVERWRITE)) { + output.write(1); + } + markAsOld(orphanFile); + assertThat(store.load()).contains(initialTask); + store.cleanupOrphanFiles(); + assertThat(orphanFile.getFileSystem().exists(orphanFile)).isFalse(); + + RebalanceTask completedTask = task("rebalance-1", COMPLETED); + store.persist(completedTask, zkEpoch.getCoordinatorEpochZkVersion(), true); + + RebalanceTaskHandle completedHandle = getRemoteHandle(); + assertThat(completedHandle).isNotEqualTo(initialHandle); + assertThat(initialHandle.getTaskPath().getFileSystem().exists(initialHandle.getTaskPath())) + .isFalse(); + assertThat(store.load()).contains(completedTask); + } + + @Test + void testPersistInlineTaskWhenRemoteStorageIsDisabled() throws Exception { + RebalanceTask task = task("rebalance-2", REBALANCING); + + store.persist(task, zkEpoch.getCoordinatorEpochZkVersion(), false); + + RebalanceTaskZNodeData data = zkClient.getRebalanceTaskDataWithVersion().get().data(); + assertThat(data.isInline()).isTrue(); + assertThat(data.getInlineTask()).isEqualTo(task); + assertThat(store.load()).contains(task); + } + + @Test + void testCoordinatorEpochFencesRemoteHandleCommit() throws Exception { + assertThatThrownBy( + () -> + store.persist( + task("fenced-rebalance", REBALANCING), + zkEpoch.getCoordinatorEpochZkVersion() + 1, + true)) + .isInstanceOf(KeeperException.BadVersionException.class); + + assertThat(zkClient.getRebalanceTaskDataWithVersion()).isEmpty(); + } + + @Test + void testCleanupOrphanFileWithoutZookeeperHandle() throws Exception { + FsPath orphan = + FlussPaths.remoteRebalanceTaskPath( + zkClient.getDefaultRemoteDataDir(), "orphan-rebalance", UUID.randomUUID()); + orphan.getFileSystem().mkdirs(orphan.getParent()); + try (FSDataOutputStream output = + orphan.getFileSystem().create(orphan, FileSystem.WriteMode.NO_OVERWRITE)) { + output.write(1); + } + markAsOld(orphan); + + store.cleanupOrphanFiles(); + assertThat(orphan.getFileSystem().exists(orphan)).isFalse(); + } + + @Test + void testCleanupRetainsRecentUnreferencedFile() throws Exception { + FsPath recentFile = + FlussPaths.remoteRebalanceTaskPath( + zkClient.getDefaultRemoteDataDir(), + "upload-in-progress", + UUID.randomUUID()); + recentFile.getFileSystem().mkdirs(recentFile.getParent()); + try (FSDataOutputStream output = + recentFile.getFileSystem().create(recentFile, FileSystem.WriteMode.NO_OVERWRITE)) { + output.write(1); + } + + store.cleanupOrphanFiles(); + assertThat(recentFile.getFileSystem().exists(recentFile)).isTrue(); + } + + @Test + void testCleanupRetainsReferencedFileWithSchemeLessPath() throws Exception { + String schemeLessRemoteDataDir = + new FsPath(zkClient.getDefaultRemoteDataDir()).toUri().getPath(); + store = new RebalanceTaskStore(zkClient, schemeLessRemoteDataDir); + RebalanceTask task = task("scheme-less-rebalance", REBALANCING); + store.persist(task, zkEpoch.getCoordinatorEpochZkVersion(), true); + + RebalanceTaskHandle handle = getRemoteHandle(); + assertThat(handle.getTaskPath().toUri().getScheme()).isNull(); + markAsOld(handle.getTaskPath()); + + store.cleanupOrphanFiles(); + + assertThat(handle.getTaskPath().getFileSystem().exists(handle.getTaskPath())).isTrue(); + assertThat(store.load()).contains(task); + } + + private RebalanceTaskHandle getRemoteHandle() throws Exception { + RebalanceTaskZNodeData data = zkClient.getRebalanceTaskDataWithVersion().get().data(); + assertThat(data.isInline()).isFalse(); + return data.getRemoteTaskHandle(); + } + + private static void markAsOld(FsPath path) throws Exception { + Files.setLastModifiedTime(Paths.get(path.toUri().getPath()), FileTime.fromMillis(0L)); + } + + private static RebalanceTask task( + String rebalanceId, + org.apache.fluss.cluster.rebalance.RebalanceStatus rebalanceStatus) { + TableBucket tableBucket = new TableBucket(1L, 0); + Map plans = new LinkedHashMap<>(); + plans.put( + tableBucket, + new RebalancePlanForBucket( + tableBucket, 0, 1, Arrays.asList(0, 1, 2), Arrays.asList(1, 2, 3))); + return new RebalanceTask(rebalanceId, rebalanceStatus, plans); + } +} diff --git a/fluss-server/src/test/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerdeTest.java b/fluss-server/src/test/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerdeTest.java index d90151d838f..1338ee00654 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerdeTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/zk/data/CoordinatorAddressJsonSerdeTest.java @@ -27,6 +27,10 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Collections; + +import static org.apache.fluss.server.zk.data.CoordinatorAddress.REMOTE_REBALANCE_TASK_FEATURE; +import static org.assertj.core.api.Assertions.assertThat; /** Test for {@link org.apache.fluss.server.zk.data.CoordinatorAddressJsonSerde}. */ public class CoordinatorAddressJsonSerdeTest extends JsonSerdeTestBase { @@ -42,14 +46,15 @@ protected CoordinatorAddress[] createObjects() { "1", Arrays.asList( new Endpoint("localhost", 1001, "CLIENT"), - new Endpoint("127.0.0.1", 9124, "FLUSS"))); + new Endpoint("127.0.0.1", 9124, "FLUSS")), + Collections.singleton(REMOTE_REBALANCE_TASK_FEATURE)); return new CoordinatorAddress[] {coordinatorAddress}; } @Override protected String[] expectedJsons() { return new String[] { - "{\"version\":2,\"id\":\"1\",\"listeners\":\"CLIENT://localhost:1001,FLUSS://127.0.0.1:9124\"}" + "{\"version\":3,\"id\":\"1\",\"listeners\":\"CLIENT://localhost:1001,FLUSS://127.0.0.1:9124\",\"supported_features\":[\"remote_rebalance_task\"]}" }; } @@ -66,6 +71,22 @@ void testCompatibility() throws IOException { CoordinatorAddress expectedCoordinator = new CoordinatorAddress( "1", Endpoint.fromListenersString("CLIENT://localhost:1001")); - assertEquals(coordinatorAddress, expectedCoordinator); + assertThat(coordinatorAddress).isEqualTo(expectedCoordinator); + } + + @Test + void testCompatibilityWithVersion2WithoutFeatures() throws IOException { + JsonNode jsonInVersion2 = + new ObjectMapper() + .readTree( + "{\"version\":2,\"id\":\"1\",\"listeners\":\"CLIENT://localhost:1001\"}" + .getBytes(StandardCharsets.UTF_8)); + + CoordinatorAddress coordinatorAddress = + CoordinatorAddressJsonSerde.INSTANCE.deserialize(jsonInVersion2); + + assertThat(coordinatorAddress.getSupportedFeatures()).isEmpty(); + assertThat(coordinatorAddress.getEndpoints()) + .isEqualTo(Endpoint.fromListenersString("CLIENT://localhost:1001")); } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerdeTest.java b/fluss-server/src/test/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerdeTest.java new file mode 100644 index 00000000000..44092e894fc --- /dev/null +++ b/fluss-server/src/test/java/org/apache/fluss/server/zk/data/RebalanceTaskZNodeJsonSerdeTest.java @@ -0,0 +1,52 @@ +/* + * 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.fluss.server.zk.data; + +import org.apache.fluss.fs.FsPath; +import org.apache.fluss.utils.json.JsonSerdeUtils; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Tests for {@link RebalanceTaskZNodeJsonSerde}. */ +class RebalanceTaskZNodeJsonSerdeTest { + + @Test + void testRemoteHandleRoundTrip() throws Exception { + RebalanceTaskHandle handle = + new RebalanceTaskHandle( + "rebalance-1", new FsPath("file:///remote/rebalance/rebalance-1/id.task")); + + byte[] bytes = + JsonSerdeUtils.writeValueAsBytes( + RebalanceTaskZNodeData.remote(handle), + RebalanceTaskZNodeJsonSerde.INSTANCE); + RebalanceTaskZNodeData decoded = + JsonSerdeUtils.readValue(bytes, RebalanceTaskZNodeJsonSerde.INSTANCE); + + assertThat(new String(bytes, StandardCharsets.UTF_8)) + .isEqualTo( + "{\"version\":3,\"rebalance_id\":\"rebalance-1\"," + + "\"rebalance_task_path\":\"file:/remote/rebalance/rebalance-1/id.task\"}"); + assertThat(decoded.isInline()).isFalse(); + assertThat(decoded.getRemoteTaskHandle()).isEqualTo(handle); + } +} diff --git a/website/docs/maintenance/operations/rebalance.md b/website/docs/maintenance/operations/rebalance.md index 1d5b9c5f6eb..9ab626a4e78 100644 --- a/website/docs/maintenance/operations/rebalance.md +++ b/website/docs/maintenance/operations/rebalance.md @@ -157,6 +157,8 @@ Only target-relevant assignment, leader, and ISR changes count as observed progr Both durations must be at least `1 ms` and fit in a signed 64-bit millisecond value; the task limit must be at least `1`. Invalid values prevent coordinator initialization. Timeouts are evaluated during periodic reconciliation, so the transition to `FAILED` can occur after the configured duration has elapsed. +Large rebalance tasks are stored in remote storage after every live coordinator advertises support for the remote task format; otherwise the task remains inline in ZooKeeper. This makes rolling coordinator upgrades safe, and TabletServer versions are unaffected. After a remote task handle has been written, do not roll a coordinator back to a version that cannot read the remote format. Complete or cancel the active rebalance before such a rollback. + ### 4. Control Rebalance Speed The coordinator controls rebalance parallelism with `coordinator.rebalance.max-inflight-tasks`, which limits how many bucket-level rebalance tasks can run at the same time. The default value is `1`, which keeps rebalance conservative.