From d1877d920c781fd9e9060038748ad9ec40ac3ef7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E9=B5=BA?= Date: Wed, 25 Nov 2026 15:05:43 +0800 Subject: [PATCH 1/5] [server] Complete the BulkLoad transaction lifecycle Add Coordinator operations to begin and replay transactions, query progress, and commit or abort imports. Retain terminal results for replay and reclaim expired transaction metadata. Read progress on the I/O executor and record withdrawn targets during transaction finalization. --- .../apache/fluss/config/ConfigOptions.java | 14 + .../apache/fluss/config/FlussConfigUtils.java | 2 + .../BulkLoadIncompleteException.java | 30 ++ .../fluss/rpc/gateway/AdminGateway.java | 31 ++ .../apache/fluss/rpc/protocol/ApiKeys.java | 7 +- .../org/apache/fluss/rpc/protocol/Errors.java | 5 +- fluss-rpc/src/main/proto/FlussApi.proto | 65 +++ fluss-rust/crates/fluss/src/proto/fluss.rs | 101 ++++ .../coordinator/CoordinatorContext.java | 10 +- .../CoordinatorEventProcessor.java | 128 ++++- .../coordinator/CoordinatorService.java | 245 ++++++--- .../coordinator/bulkload/BulkLoadManager.java | 505 +++++++++++++++++- .../coordinator/event/AbortBulkLoadEvent.java | 43 ++ .../coordinator/event/BeginBulkLoadEvent.java | 45 ++ .../event/CommitBulkLoadEvent.java | 36 ++ .../event/CoordinatorEventManager.java | 27 +- .../ReclaimTableBulkLoadMetadataEvent.java | 32 ++ .../server/zk/BulkLoadTransactionStore.java | 440 +++++++++++++++ .../fluss/server/zk/ZooKeeperClient.java | 4 +- .../apache/fluss/server/zk/data/ZkData.java | 74 ++- .../zk/data/bulkload/BulkLoadTarget.java | 5 + .../zk/data/bulkload/BulkLoadTransaction.java | 15 + .../coordinator/BulkLoadBucketCommitTest.java | 307 ++++++++++- .../coordinator/CoordinatorContextTest.java | 17 + .../coordinator/TestCoordinatorGateway.java | 37 ++ .../bulkload/BulkLoadAuthorizationITCase.java | 152 ++++++ .../event/CoordinatorEventManagerTest.java | 28 + website/docs/maintenance/configuration.md | 2 + 28 files changed, 2279 insertions(+), 128 deletions(-) create mode 100644 fluss-common/src/main/java/org/apache/fluss/exception/BulkLoadIncompleteException.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/zk/BulkLoadTransactionStore.java create mode 100644 fluss-server/src/test/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadAuthorizationITCase.java diff --git a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java index c61db2da46d..44b4b6f8105 100644 --- a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java +++ b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java @@ -212,6 +212,20 @@ public class ConfigOptions { + PLUGIN_ALWAYS_PARENT_FIRST_LOADER_PATTERNS.key() + "\"."); + public static final ConfigOption COORDINATOR_BULKLOAD_MAX_TARGETS = + key("coordinator.bulkload.max-targets") + .intType() + .defaultValue(1000) + .withDescription( + "Maximum physical targets selected by one BulkLoad transaction."); + + public static final ConfigOption COORDINATOR_BULKLOAD_RESULT_RETENTION = + key("coordinator.bulkload.result-retention") + .durationType() + .defaultValue(Duration.ofDays(7)) + .withDescription( + "Minimum retention of terminal BulkLoad results while the table exists."); + public static final ConfigOption AUTO_PARTITION_CHECK_INTERVAL = key("auto-partition.check.interval") .durationType() diff --git a/fluss-common/src/main/java/org/apache/fluss/config/FlussConfigUtils.java b/fluss-common/src/main/java/org/apache/fluss/config/FlussConfigUtils.java index 415103c46ea..58637c56bbc 100644 --- a/fluss-common/src/main/java/org/apache/fluss/config/FlussConfigUtils.java +++ b/fluss-common/src/main/java/org/apache/fluss/config/FlussConfigUtils.java @@ -131,6 +131,8 @@ public static void validateCoordinatorConfigs(Configuration conf) { validateServerConfigs(conf); validMinDuration(conf, ConfigOptions.COORDINATOR_CONTROL_REQUEST_RETRY_BACKOFF, 1); validMinDuration(conf, ConfigOptions.COORDINATOR_CONTROL_REQUEST_TIMEOUT, 1); + validMinValue(conf, ConfigOptions.COORDINATOR_BULKLOAD_MAX_TARGETS, 1); + validMinDuration(conf, ConfigOptions.COORDINATOR_BULKLOAD_RESULT_RETENTION, 1); } public static void validateTabletConfigs(Configuration conf) { diff --git a/fluss-common/src/main/java/org/apache/fluss/exception/BulkLoadIncompleteException.java b/fluss-common/src/main/java/org/apache/fluss/exception/BulkLoadIncompleteException.java new file mode 100644 index 00000000000..b0fa70e3919 --- /dev/null +++ b/fluss-common/src/main/java/org/apache/fluss/exception/BulkLoadIncompleteException.java @@ -0,0 +1,30 @@ +/* + * 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.exception; + +import org.apache.fluss.annotation.PublicEvolving; + +/** BulkLoad transaction has incomplete buckets. */ +@PublicEvolving +public class BulkLoadIncompleteException extends ApiException { + private static final long serialVersionUID = 1L; + + public BulkLoadIncompleteException(String message) { + super(message); + } +} diff --git a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/AdminGateway.java b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/AdminGateway.java index 7d49f080cbe..4723e458eff 100644 --- a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/AdminGateway.java +++ b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/AdminGateway.java @@ -17,6 +17,8 @@ package org.apache.fluss.rpc.gateway; +import org.apache.fluss.rpc.messages.AbortBulkLoadRequest; +import org.apache.fluss.rpc.messages.AbortBulkLoadResponse; import org.apache.fluss.rpc.messages.AcquireKvSnapshotLeaseRequest; import org.apache.fluss.rpc.messages.AcquireKvSnapshotLeaseResponse; import org.apache.fluss.rpc.messages.AddServerTagByRackRequest; @@ -31,10 +33,14 @@ import org.apache.fluss.rpc.messages.AlterDatabaseResponse; import org.apache.fluss.rpc.messages.AlterTableRequest; import org.apache.fluss.rpc.messages.AlterTableResponse; +import org.apache.fluss.rpc.messages.BeginBulkLoadRequest; +import org.apache.fluss.rpc.messages.BeginBulkLoadResponse; import org.apache.fluss.rpc.messages.CancelRebalanceRequest; import org.apache.fluss.rpc.messages.CancelRebalanceResponse; import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotRequest; import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotResponse; +import org.apache.fluss.rpc.messages.CommitBulkLoadRequest; +import org.apache.fluss.rpc.messages.CommitBulkLoadResponse; import org.apache.fluss.rpc.messages.CreateAclsRequest; import org.apache.fluss.rpc.messages.CreateAclsResponse; import org.apache.fluss.rpc.messages.CreateDatabaseRequest; @@ -59,8 +65,12 @@ import org.apache.fluss.rpc.messages.DropPartitionResponse; import org.apache.fluss.rpc.messages.DropTableRequest; import org.apache.fluss.rpc.messages.DropTableResponse; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoRequest; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoResponse; import org.apache.fluss.rpc.messages.GetProducerOffsetsRequest; import org.apache.fluss.rpc.messages.GetProducerOffsetsResponse; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsRequest; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsResponse; import org.apache.fluss.rpc.messages.ListKvSnapshotsRequest; import org.apache.fluss.rpc.messages.ListKvSnapshotsResponse; import org.apache.fluss.rpc.messages.ListRebalanceProgressRequest; @@ -287,4 +297,25 @@ CompletableFuture listRemoteLogManifests( */ @RPC(api = ApiKeys.LIST_KV_SNAPSHOTS) CompletableFuture listKvSnapshots(ListKvSnapshotsRequest request); + + /** Starts a bulk load or returns the retained transaction for the same ID. */ + @RPC(api = ApiKeys.BEGIN_BULK_LOAD) + CompletableFuture beginBulkLoad(BeginBulkLoadRequest request); + + /** Completes a bulk load once its effective targets have committed. */ + @RPC(api = ApiKeys.COMMIT_BULK_LOAD) + CompletableFuture commitBulkLoad(CommitBulkLoadRequest request); + + /** Ends a bulk load while preserving its committed buckets. */ + @RPC(api = ApiKeys.ABORT_BULK_LOAD) + CompletableFuture abortBulkLoad(AbortBulkLoadRequest request); + + /** Returns retained progress for a BulkLoad transaction. */ + @RPC(api = ApiKeys.GET_BULK_LOAD_INFO) + CompletableFuture getBulkLoadInfo(GetBulkLoadInfoRequest request); + + /** Lists RUNNING transactions matching the selected physical targets. */ + @RPC(api = ApiKeys.LIST_IN_PROGRESS_BULK_LOADS) + CompletableFuture listInProgressBulkLoads( + ListInProgressBulkLoadsRequest request); } diff --git a/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/ApiKeys.java b/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/ApiKeys.java index b0a97fe4c21..b444b263420 100644 --- a/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/ApiKeys.java +++ b/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/ApiKeys.java @@ -133,7 +133,12 @@ public enum ApiKeys { CREATE_TABLE_FROM_LAKE(1074, 0, 0, PUBLIC), DESCRIBE_CLUSTER(1075, 0, 0, PUBLIC), ALLOCATE_BULK_LOAD_BUCKET_SNAPSHOT(1076, 0, 0, PUBLIC), - COMMIT_BULK_LOAD_BUCKET_SNAPSHOT(1077, 0, 0, PUBLIC); + COMMIT_BULK_LOAD_BUCKET_SNAPSHOT(1077, 0, 0, PUBLIC), + BEGIN_BULK_LOAD(1078, 0, 0, PUBLIC), + COMMIT_BULK_LOAD(1079, 0, 0, PUBLIC), + ABORT_BULK_LOAD(1080, 0, 0, PUBLIC), + GET_BULK_LOAD_INFO(1081, 0, 0, PUBLIC), + LIST_IN_PROGRESS_BULK_LOADS(1082, 0, 0, PUBLIC); private static final Map ID_TO_TYPE = Arrays.stream(ApiKeys.values()) diff --git a/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/Errors.java b/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/Errors.java index cf9e84b8317..1cb1250a2a3 100644 --- a/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/Errors.java +++ b/fluss-rpc/src/main/java/org/apache/fluss/rpc/protocol/Errors.java @@ -21,6 +21,7 @@ import org.apache.fluss.exception.AuthenticationException; import org.apache.fluss.exception.AuthorizationException; import org.apache.fluss.exception.BulkLoadConflictException; +import org.apache.fluss.exception.BulkLoadIncompleteException; import org.apache.fluss.exception.BulkLoadNotFoundException; import org.apache.fluss.exception.BulkLoadStateException; import org.apache.fluss.exception.BulkLoadTargetWithdrawnException; @@ -340,7 +341,9 @@ public enum Errors { INVALID_BULK_LOAD_SNAPSHOT( 85, "BulkLoad snapshot input is invalid.", InvalidBulkLoadSnapshotException::new), BULK_LOAD_TARGET_WITHDRAWN( - 86, "BulkLoad target has been withdrawn.", BulkLoadTargetWithdrawnException::new); + 86, "BulkLoad target has been withdrawn.", BulkLoadTargetWithdrawnException::new), + BULK_LOAD_INCOMPLETE( + 87, "BulkLoad transaction is incomplete.", BulkLoadIncompleteException::new); private static final Logger LOG = LoggerFactory.getLogger(Errors.class); diff --git a/fluss-rpc/src/main/proto/FlussApi.proto b/fluss-rpc/src/main/proto/FlussApi.proto index 58b61f44bca..b712509a209 100644 --- a/fluss-rpc/src/main/proto/FlussApi.proto +++ b/fluss-rpc/src/main/proto/FlussApi.proto @@ -981,6 +981,31 @@ message PbBulkLoadHandle { required string bulk_load_id = 2; } +message PbBulkLoadStatus { + required PbBulkLoadHandle handle = 1; + required int32 state = 2; + required int64 created_time = 3; + optional int64 finished_time = 4; + optional string abort_message = 5; +} + +message PbBulkLoadTargetInfo { + optional int64 partition_id = 1; + optional string partition_name = 2; + required int32 bucket_count = 3; + required string remote_data_dir = 4; +} +message BeginBulkLoadRequest { + required PbTablePath table_path = 1; + repeated string partition_names = 2; + optional string bulk_load_id = 3; +} + +message BeginBulkLoadResponse { + required PbBulkLoadStatus status = 1; + required PbTableInfo table_info = 2; + repeated PbBulkLoadTargetInfo targets = 3; +} message AllocateBulkLoadBucketSnapshotRequest { required PbBulkLoadHandle handle = 1; optional int64 partition_id = 2; @@ -1000,6 +1025,46 @@ message CommitBulkLoadBucketSnapshotRequest { } message CommitBulkLoadBucketSnapshotResponse {} +message CommitBulkLoadRequest { + required PbBulkLoadHandle handle = 1; +} + +message CommitBulkLoadResponse { + required PbBulkLoadStatus status = 1; +} +message AbortBulkLoadRequest { + required PbBulkLoadHandle handle = 1; + optional string abort_message = 2; +} + +message AbortBulkLoadResponse { + required PbBulkLoadStatus status = 1; +} +message GetBulkLoadInfoRequest { + required PbBulkLoadHandle handle = 1; +} + +message PbBulkLoadTargetProgress { + optional int64 partition_id = 1; + required int32 bucket_count = 2; + required int64 allocated_bucket_count = 3; + required int64 committed_bucket_count = 4; + required bool withdrawn = 5; +} + +message GetBulkLoadInfoResponse { + required PbBulkLoadStatus status = 1; + repeated PbBulkLoadTargetProgress targets = 2; +} +message ListInProgressBulkLoadsRequest { + required PbTablePath table_path = 1; + repeated string partition_names = 2; +} + +message ListInProgressBulkLoadsResponse { + repeated PbBulkLoadStatus transactions = 1; +} + // --------------- Inner classes ---------------- message PbTabletServerLoad { required int32 server_id = 1; diff --git a/fluss-rust/crates/fluss/src/proto/fluss.rs b/fluss-rust/crates/fluss/src/proto/fluss.rs index 723d66d1803..cf8d3faa2ac 100644 --- a/fluss-rust/crates/fluss/src/proto/fluss.rs +++ b/fluss-rust/crates/fluss/src/proto/fluss.rs @@ -1277,6 +1277,48 @@ pub struct PbBulkLoadHandle { pub bulk_load_id: ::prost::alloc::string::String, } #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct PbBulkLoadStatus { + #[prost(message, required, tag = "1")] + pub handle: PbBulkLoadHandle, + #[prost(int32, required, tag = "2")] + pub state: i32, + #[prost(int64, required, tag = "3")] + pub created_time: i64, + #[prost(int64, optional, tag = "4")] + pub finished_time: ::core::option::Option, + #[prost(string, optional, tag = "5")] + pub abort_message: ::core::option::Option<::prost::alloc::string::String>, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct PbBulkLoadTargetInfo { + #[prost(int64, optional, tag = "1")] + pub partition_id: ::core::option::Option, + #[prost(string, optional, tag = "2")] + pub partition_name: ::core::option::Option<::prost::alloc::string::String>, + #[prost(int32, required, tag = "3")] + pub bucket_count: i32, + #[prost(string, required, tag = "4")] + pub remote_data_dir: ::prost::alloc::string::String, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct BeginBulkLoadRequest { + #[prost(message, required, tag = "1")] + pub table_path: PbTablePath, + #[prost(string, repeated, tag = "2")] + pub partition_names: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, + #[prost(string, optional, tag = "3")] + pub bulk_load_id: ::core::option::Option<::prost::alloc::string::String>, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct BeginBulkLoadResponse { + #[prost(message, required, tag = "1")] + pub status: PbBulkLoadStatus, + #[prost(message, required, tag = "2")] + pub table_info: PbTableInfo, + #[prost(message, repeated, tag = "3")] + pub targets: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct AllocateBulkLoadBucketSnapshotRequest { #[prost(message, required, tag = "1")] pub handle: PbBulkLoadHandle, @@ -1306,6 +1348,65 @@ pub struct CommitBulkLoadBucketSnapshotRequest { } #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct CommitBulkLoadBucketSnapshotResponse {} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct CommitBulkLoadRequest { + #[prost(message, required, tag = "1")] + pub handle: PbBulkLoadHandle, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct CommitBulkLoadResponse { + #[prost(message, required, tag = "1")] + pub status: PbBulkLoadStatus, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct AbortBulkLoadRequest { + #[prost(message, required, tag = "1")] + pub handle: PbBulkLoadHandle, + #[prost(string, optional, tag = "2")] + pub abort_message: ::core::option::Option<::prost::alloc::string::String>, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct AbortBulkLoadResponse { + #[prost(message, required, tag = "1")] + pub status: PbBulkLoadStatus, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct GetBulkLoadInfoRequest { + #[prost(message, required, tag = "1")] + pub handle: PbBulkLoadHandle, +} +#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] +pub struct PbBulkLoadTargetProgress { + #[prost(int64, optional, tag = "1")] + pub partition_id: ::core::option::Option, + #[prost(int32, required, tag = "2")] + pub bucket_count: i32, + #[prost(int64, required, tag = "3")] + pub allocated_bucket_count: i64, + #[prost(int64, required, tag = "4")] + pub committed_bucket_count: i64, + #[prost(bool, required, tag = "5")] + pub withdrawn: bool, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct GetBulkLoadInfoResponse { + #[prost(message, required, tag = "1")] + pub status: PbBulkLoadStatus, + #[prost(message, repeated, tag = "2")] + pub targets: ::prost::alloc::vec::Vec, +} +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ListInProgressBulkLoadsRequest { + #[prost(message, required, tag = "1")] + pub table_path: PbTablePath, + #[prost(string, repeated, tag = "2")] + pub partition_names: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, +} +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct ListInProgressBulkLoadsResponse { + #[prost(message, repeated, tag = "1")] + pub transactions: ::prost::alloc::vec::Vec, +} /// --------------- Inner classes ---------------- #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct PbTabletServerLoad { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorContext.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorContext.java index 3611050e0f4..25c3f0fbcd0 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorContext.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorContext.java @@ -745,6 +745,12 @@ public boolean isBulkLoadPublicationPending(TableBucket bucket) { return unverifiedBulkLoadBuckets.contains(bucket); } + /** Returns whether publication verification still needs bucket records for this table. */ + public boolean hasPendingBulkLoadPublication(long tableId) { + return unverifiedBulkLoadBuckets.stream() + .anyMatch(bucket -> bucket.getTableId() == tableId); + } + void setBulkLoadPublicationPending(TableBucket bucket, boolean pending) { if (pending) { unverifiedBulkLoadBuckets.add(bucket); @@ -832,7 +838,7 @@ public void removeTable(long tableId) { TablePath tablePath = tablePathById.remove(tableId); if (tablePath != null) { - tableIdByPath.remove(tablePath); + tableIdByPath.remove(tablePath, tableId); } tableInfoById.remove(tableId); } @@ -861,7 +867,7 @@ public void removePartition(TablePartition tablePartition) { PhysicalTablePath physicalTablePath = pathByPartitionId.remove(tablePartition.getPartitionId()); if (physicalTablePath != null) { - partitionIdByPath.remove(physicalTablePath); + partitionIdByPath.remove(physicalTablePath, tablePartition.getPartitionId()); } partitionInfoById.remove(tablePartition.getPartitionId()); 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 87773fd2cf1..284054159e8 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 @@ -50,10 +50,13 @@ import org.apache.fluss.metadata.TableInfo; import org.apache.fluss.metadata.TablePartition; import org.apache.fluss.metadata.TablePath; +import org.apache.fluss.rpc.messages.AbortBulkLoadResponse; import org.apache.fluss.rpc.messages.AddServerTagByRackResponse; import org.apache.fluss.rpc.messages.AddServerTagResponse; import org.apache.fluss.rpc.messages.AdjustIsrResponse; +import org.apache.fluss.rpc.messages.BeginBulkLoadResponse; import org.apache.fluss.rpc.messages.CancelRebalanceResponse; +import org.apache.fluss.rpc.messages.CommitBulkLoadResponse; import org.apache.fluss.rpc.messages.CommitKvSnapshotResponse; import org.apache.fluss.rpc.messages.CommitLakeTableSnapshotResponse; import org.apache.fluss.rpc.messages.CommitRemoteLogManifestResponse; @@ -64,13 +67,17 @@ import org.apache.fluss.rpc.messages.RemoveServerTagByRackResponse; import org.apache.fluss.rpc.messages.RemoveServerTagResponse; import org.apache.fluss.rpc.protocol.ApiError; +import org.apache.fluss.server.coordinator.bulkload.BulkLoadManager; +import org.apache.fluss.server.coordinator.event.AbortBulkLoadEvent; import org.apache.fluss.server.coordinator.event.AccessContextEvent; import org.apache.fluss.server.coordinator.event.AddServerTagByRackEvent; import org.apache.fluss.server.coordinator.event.AddServerTagEvent; import org.apache.fluss.server.coordinator.event.AdjustIsrReceivedEvent; +import org.apache.fluss.server.coordinator.event.BeginBulkLoadEvent; import org.apache.fluss.server.coordinator.event.CancelRebalanceEvent; import org.apache.fluss.server.coordinator.event.CheckRebalanceTimeoutEvent; import org.apache.fluss.server.coordinator.event.CommitBulkLoadBucketEvent; +import org.apache.fluss.server.coordinator.event.CommitBulkLoadEvent; import org.apache.fluss.server.coordinator.event.CommitKvSnapshotEvent; import org.apache.fluss.server.coordinator.event.CommitLakeTableSnapshotEvent; import org.apache.fluss.server.coordinator.event.CommitRemoteLogManifestEvent; @@ -94,6 +101,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.ReclaimTableBulkLoadMetadataEvent; import org.apache.fluss.server.coordinator.event.ReconcileRebalanceTaskEvent; import org.apache.fluss.server.coordinator.event.RecoverRebalanceEvent; import org.apache.fluss.server.coordinator.event.RemoveServerTagByRackEvent; @@ -138,6 +146,8 @@ import org.apache.fluss.server.zk.data.TabletServerRegistration; import org.apache.fluss.server.zk.data.ZkData.PartitionIdsZNode; import org.apache.fluss.server.zk.data.ZkData.TableIdsZNode; +import org.apache.fluss.server.zk.data.bulkload.BulkLoadTarget; +import org.apache.fluss.server.zk.data.bulkload.BulkLoadTransaction; import org.apache.fluss.server.zk.data.lake.LakeTableHelper; import org.apache.fluss.server.zk.data.lake.LakeTableSnapshot; import org.apache.fluss.utils.AutoPartitionStrategy; @@ -216,6 +226,9 @@ public class CoordinatorEventProcessor implements EventProcessor, RebalanceExecu // write attempt invalidates the entry before it starts. private final Map> assignmentPersistenceByBucket = new HashMap<>(); private ScheduledFuture offlineLeaderRetryTask; + private final BulkLoadManager bulkLoadManager; + private final int bulkLoadMaxTargets; + private final long bulkLoadResultRetentionMs; public CoordinatorEventProcessor( ZooKeeperClient zooKeeperClient, @@ -306,6 +319,12 @@ public CoordinatorEventProcessor( offlineLeaderRetryDelayMs)); } this.scheduler = scheduler; + this.bulkLoadManager = + new BulkLoadManager( + zooKeeperClient, coordinatorContext.getCoordinatorZkVersion(), ioExecutor); + this.bulkLoadMaxTargets = conf.get(ConfigOptions.COORDINATOR_BULKLOAD_MAX_TARGETS); + this.bulkLoadResultRetentionMs = + conf.get(ConfigOptions.COORDINATOR_BULKLOAD_RESULT_RETENTION).toMillis(); this.zkRetryDelayMs = conf.get(ConfigOptions.ZOOKEEPER_RETRY_WAIT).toMillis(); this.ioExecutor = ioExecutor; this.lakeTableHelper = new LakeTableHelper(zooKeeperClient); @@ -323,6 +342,88 @@ public CoordinatorContext getCoordinatorContext() { return coordinatorContext; } + private BeginBulkLoadResponse processBeginBulkLoad(BeginBulkLoadEvent event) throws Exception { + long tableId = coordinatorContext.getTableIdByPath(event.tablePath); + TableInfo table = getActiveBulkLoadTable(tableId); + if (table == null) { + throw new TableNotExistException("Table " + event.tablePath + " does not exist."); + } + return bulkLoadManager.begin( + table, + event.bulkLoadId, + event.partitionNames, + bulkLoadMaxTargets, + name -> getBulkLoadPartitionTarget(table, name)); + } + + private @Nullable BulkLoadTarget getBulkLoadPartitionTarget(TableInfo table, String name) { + Long partitionId = + coordinatorContext + .getPartitionId(PhysicalTablePath.of(table.getTablePath(), name)) + .orElse(null); + if (partitionId == null) { + return null; + } + TablePartition tablePartition = new TablePartition(table.getTableId(), partitionId); + Integer bucketCount = coordinatorContext.getPartitionBucketCount(tablePartition); + if (bucketCount == null + || coordinatorContext.isPartitionQueuedForDeletion(tablePartition)) { + return null; + } + PartitionInfo partition = coordinatorContext.getPartitionInfoById(partitionId); + return new BulkLoadTarget( + partitionId, name, bucketCount, partition.getRemoteDataDir(), false); + } + + private CommitBulkLoadResponse processCommitBulkLoad(CommitBulkLoadEvent event) + throws Exception { + return new CommitBulkLoadResponse() + .setStatus( + bulkLoadManager.finishTransaction( + event.tableId, + event.bulkLoadId, + BulkLoadTransaction.COMMITTED, + null, + getActiveBulkLoadTable(event.tableId), + this::isBulkLoadPartitionActive)); + } + + private AbortBulkLoadResponse processAbortBulkLoad(AbortBulkLoadEvent event) throws Exception { + return new AbortBulkLoadResponse() + .setStatus( + bulkLoadManager.finishTransaction( + event.tableId, + event.bulkLoadId, + BulkLoadTransaction.ABORTED, + event.abortMessage, + getActiveBulkLoadTable(event.tableId), + this::isBulkLoadPartitionActive)); + } + + private void processReclaimTableBulkLoadMetadata(ReclaimTableBulkLoadMetadataEvent event) { + try { + bulkLoadManager.reclaimTableBulkLoadMetadata( + event.tableId, + event.retentionCutoff, + getActiveBulkLoadTable(event.tableId) == null, + coordinatorContext.hasPendingBulkLoadPublication(event.tableId)); + event.result.complete(null); + } catch (Exception e) { + event.result.completeExceptionally(e); + } + } + + private @Nullable TableInfo getActiveBulkLoadTable(long tableId) { + return coordinatorContext.isTableQueuedForDeletion(tableId) + ? null + : coordinatorContext.getTableInfoById(tableId); + } + + private boolean isBulkLoadPartitionActive(TablePartition partition) { + return coordinatorContext.containsPartitionId(partition.getPartitionId()) + && !coordinatorContext.isPartitionQueuedForDeletion(partition); + } + private void processCommitBulkLoadBucket(CommitBulkLoadBucketEvent event) { CompletedSnapshot snapshot = event.snapshot; TableBucket bucket = snapshot.getTableBucket(); @@ -558,9 +659,12 @@ public void startup() { // start rebalance manager. rebalanceManager.startup(); + bulkLoadManager.startMetadataReclamation( + scheduler, coordinatorEventManager, bulkLoadResultRetentionMs); } public void shutdown() { + bulkLoadManager.stopMetadataReclamation(); clearOfflineLeaderRetryTask(); // Cancel periodic event producers before stopping the event loop. rebalanceManager.stopTimeoutChecker(); @@ -915,7 +1019,21 @@ private void enqueueRetryOfflineLeaderEventSafely() { @Override public void process(CoordinatorEvent event) { - if (event instanceof CommitBulkLoadBucketEvent) { + if (event instanceof BeginBulkLoadEvent) { + BeginBulkLoadEvent beginBulkLoadEvent = (BeginBulkLoadEvent) event; + completeFromCallable( + beginBulkLoadEvent.result, () -> processBeginBulkLoad(beginBulkLoadEvent)); + } else if (event instanceof CommitBulkLoadEvent) { + CommitBulkLoadEvent commitBulkLoadEvent = (CommitBulkLoadEvent) event; + completeFromCallable( + commitBulkLoadEvent.result, () -> processCommitBulkLoad(commitBulkLoadEvent)); + } else if (event instanceof AbortBulkLoadEvent) { + AbortBulkLoadEvent abortBulkLoadEvent = (AbortBulkLoadEvent) event; + completeFromCallable( + abortBulkLoadEvent.result, () -> processAbortBulkLoad(abortBulkLoadEvent)); + } else if (event instanceof ReclaimTableBulkLoadMetadataEvent) { + processReclaimTableBulkLoadMetadata((ReclaimTableBulkLoadMetadataEvent) event); + } else if (event instanceof CommitBulkLoadBucketEvent) { processCommitBulkLoadBucket((CommitBulkLoadBucketEvent) event); } else if (event instanceof BulkLoadVerificationResult) { processBulkLoadVerification((BulkLoadVerificationResult) event); @@ -1418,6 +1536,10 @@ private void processDropTable(DropTableEvent dropTableEvent) { if (dropTableInfo.isPartitioned()) { tableManager.resumeDeletions(); } + if (dropTableInfo.hasPrimaryKey()) { + bulkLoadManager.onTableDropped( + tableId, bulkLoadResultRetentionMs, coordinatorEventManager); + } } private void processDropPartition(DropPartitionEvent dropPartitionEvent) { @@ -3217,6 +3339,10 @@ CompletedSnapshotStoreManager completedSnapshotStoreManager() { return completedSnapshotStoreManager; } + BulkLoadManager bulkLoadManager() { + return bulkLoadManager; + } + private static final class ReplicaReassignment { private final List replicas; private final List addingReplicas; diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java index 427a11a627c..9c6bd258a11 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.java @@ -29,7 +29,6 @@ import org.apache.fluss.config.cluster.AlterConfig; import org.apache.fluss.config.cluster.AlterConfigOpType; import org.apache.fluss.exception.ApiException; -import org.apache.fluss.exception.BulkLoadNotFoundException; import org.apache.fluss.exception.FlussRuntimeException; import org.apache.fluss.exception.InvalidAlterTableException; import org.apache.fluss.exception.InvalidCoordinatorException; @@ -68,6 +67,8 @@ import org.apache.fluss.metadata.TablePath; import org.apache.fluss.row.encode.KvValueLayout; import org.apache.fluss.rpc.gateway.CoordinatorGateway; +import org.apache.fluss.rpc.messages.AbortBulkLoadRequest; +import org.apache.fluss.rpc.messages.AbortBulkLoadResponse; import org.apache.fluss.rpc.messages.AcquireKvSnapshotLeaseRequest; import org.apache.fluss.rpc.messages.AcquireKvSnapshotLeaseResponse; import org.apache.fluss.rpc.messages.AddServerTagByRackRequest; @@ -84,10 +85,14 @@ import org.apache.fluss.rpc.messages.AlterDatabaseResponse; import org.apache.fluss.rpc.messages.AlterTableRequest; import org.apache.fluss.rpc.messages.AlterTableResponse; +import org.apache.fluss.rpc.messages.BeginBulkLoadRequest; +import org.apache.fluss.rpc.messages.BeginBulkLoadResponse; import org.apache.fluss.rpc.messages.CancelRebalanceRequest; import org.apache.fluss.rpc.messages.CancelRebalanceResponse; import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotRequest; import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotResponse; +import org.apache.fluss.rpc.messages.CommitBulkLoadRequest; +import org.apache.fluss.rpc.messages.CommitBulkLoadResponse; import org.apache.fluss.rpc.messages.CommitKvSnapshotRequest; import org.apache.fluss.rpc.messages.CommitKvSnapshotResponse; import org.apache.fluss.rpc.messages.CommitLakeTableSnapshotRequest; @@ -120,12 +125,16 @@ import org.apache.fluss.rpc.messages.DropPartitionResponse; import org.apache.fluss.rpc.messages.DropTableRequest; import org.apache.fluss.rpc.messages.DropTableResponse; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoRequest; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoResponse; import org.apache.fluss.rpc.messages.GetClusterHealthRequest; import org.apache.fluss.rpc.messages.GetClusterHealthResponse; import org.apache.fluss.rpc.messages.GetProducerOffsetsRequest; import org.apache.fluss.rpc.messages.GetProducerOffsetsResponse; import org.apache.fluss.rpc.messages.LakeTieringHeartbeatRequest; import org.apache.fluss.rpc.messages.LakeTieringHeartbeatResponse; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsRequest; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsResponse; import org.apache.fluss.rpc.messages.ListKvSnapshotsRequest; import org.apache.fluss.rpc.messages.ListKvSnapshotsResponse; import org.apache.fluss.rpc.messages.ListRebalanceProgressRequest; @@ -173,11 +182,14 @@ import org.apache.fluss.server.authorizer.AclDeleteResult; import org.apache.fluss.server.authorizer.Authorizer; import org.apache.fluss.server.coordinator.bulkload.BulkLoadManager; +import org.apache.fluss.server.coordinator.event.AbortBulkLoadEvent; import org.apache.fluss.server.coordinator.event.AccessContextEvent; import org.apache.fluss.server.coordinator.event.AddServerTagByRackEvent; import org.apache.fluss.server.coordinator.event.AddServerTagEvent; import org.apache.fluss.server.coordinator.event.AdjustIsrReceivedEvent; +import org.apache.fluss.server.coordinator.event.BeginBulkLoadEvent; import org.apache.fluss.server.coordinator.event.CancelRebalanceEvent; +import org.apache.fluss.server.coordinator.event.CommitBulkLoadEvent; import org.apache.fluss.server.coordinator.event.CommitKvSnapshotEvent; import org.apache.fluss.server.coordinator.event.CommitLakeTableSnapshotEvent; import org.apache.fluss.server.coordinator.event.CommitRemoteLogManifestEvent; @@ -219,7 +231,6 @@ import org.apache.fluss.utils.ExceptionUtils; import org.apache.fluss.utils.IOUtils; import org.apache.fluss.utils.concurrent.FutureUtils; -import org.apache.fluss.utils.function.FunctionWithException; import org.apache.fluss.utils.json.TableBucketOffsets; import org.slf4j.Logger; @@ -276,6 +287,7 @@ import static org.apache.fluss.utils.PartitionUtils.validateAutoPartitionTime; import static org.apache.fluss.utils.PartitionUtils.validatePartitionSpec; import static org.apache.fluss.utils.Preconditions.checkNotNull; +import static org.apache.fluss.utils.concurrent.FutureUtils.completeFromCallable; /** An RPC Gateway service for coordinator server. */ public final class CoordinatorService extends RpcServiceBase implements CoordinatorGateway { @@ -371,92 +383,183 @@ public String name() { return "coordinator"; } + @Override + public CompletableFuture beginBulkLoad(BeginBulkLoadRequest request) { + TablePath path = toTablePath(request.getTablePath()); + path.validate(); + authorizeTable(OperationType.WRITE, path); + CompletableFuture response = new CompletableFuture<>(); + requireLeaderEventProcessor() + .getCoordinatorEventManager() + .put( + new BeginBulkLoadEvent( + path, + request.hasBulkLoadId() ? request.getBulkLoadId() : null, + request.getPartitionNamesList(), + response)); + return translateBulkLoadZooKeeperFailures(response); + } + + @Override + public CompletableFuture getBulkLoadInfo( + GetBulkLoadInfoRequest request) { + PbBulkLoadHandle handle = request.getHandle(); + authorizeTable(OperationType.DESCRIBE, handle.getTableId()); + CompletableFuture response = new CompletableFuture<>(); + ioExecutor.execute( + () -> + completeFromCallable( + response, + () -> { + BulkLoadManager manager = + requireLeaderEventProcessor().bulkLoadManager(); + return manager.getBulkLoadInfo( + handle.getTableId(), handle.getBulkLoadId()); + })); + return translateBulkLoadZooKeeperFailures(response); + } + + @Override + public CompletableFuture listInProgressBulkLoads( + ListInProgressBulkLoadsRequest request) { + TablePath path = toTablePath(request.getTablePath()); + path.validate(); + authorizeTable(OperationType.DESCRIBE, path); + CompletableFuture response = new CompletableFuture<>(); + ioExecutor.execute( + () -> + completeFromCallable( + response, + () -> { + BulkLoadManager manager = + requireLeaderEventProcessor().bulkLoadManager(); + return manager.listInProgressBulkLoads( + path, request.getPartitionNamesList()); + })); + return translateBulkLoadZooKeeperFailures(response); + } + + @Override + public CompletableFuture commitBulkLoad(CommitBulkLoadRequest request) { + PbBulkLoadHandle handle = request.getHandle(); + authorizeTable(OperationType.WRITE, handle.getTableId()); + CompletableFuture response = new CompletableFuture<>(); + requireLeaderEventProcessor() + .getCoordinatorEventManager() + .put( + new CommitBulkLoadEvent( + handle.getTableId(), handle.getBulkLoadId(), response)); + return translateBulkLoadZooKeeperFailures(response); + } + + @Override + public CompletableFuture abortBulkLoad(AbortBulkLoadRequest request) { + PbBulkLoadHandle handle = request.getHandle(); + authorizeTable(OperationType.WRITE, handle.getTableId()); + CompletableFuture response = new CompletableFuture<>(); + requireLeaderEventProcessor() + .getCoordinatorEventManager() + .put( + new AbortBulkLoadEvent( + handle.getTableId(), + handle.getBulkLoadId(), + request.hasAbortMessage() ? request.getAbortMessage() : null, + response)); + return translateBulkLoadZooKeeperFailures(response); + } + @Override public CompletableFuture allocateBulkLoadBucketSnapshot( AllocateBulkLoadBucketSnapshotRequest request) { PbBulkLoadHandle handle = request.getHandle(); - authorizeBulkLoad(handle.getTableId()); - return submitBulkLoadOperation( - manager -> { - TableBucket bucket = - new TableBucket( - handle.getTableId(), - request.hasPartitionId() ? request.getPartitionId() : null, - request.getBucketId()); - BulkLoadBucket allocation = - manager.allocateBucketSnapshot(handle.getBulkLoadId(), bucket); - return CompletableFuture.completedFuture( - new AllocateBulkLoadBucketSnapshotResponse() - .setSnapshotId(allocation.snapshotId) - .setLogOffset(allocation.logOffset) - .setState(allocation.state)); - }); + authorizeTable(OperationType.WRITE, handle.getTableId()); + TableBucket bucket = + new TableBucket( + handle.getTableId(), + request.hasPartitionId() ? request.getPartitionId() : null, + request.getBucketId()); + CoordinatorEventProcessor coordinator = requireLeaderEventProcessor(); + CompletableFuture response = + new CompletableFuture<>(); + ioExecutor.execute( + () -> + completeFromCallable( + response, + () -> { + checkCoordinatorLeadership(coordinator); + BulkLoadManager manager = coordinator.bulkLoadManager(); + BulkLoadBucket allocation = + manager.allocateBucketSnapshot( + handle.getBulkLoadId(), bucket); + return new AllocateBulkLoadBucketSnapshotResponse() + .setSnapshotId(allocation.snapshotId) + .setLogOffset(allocation.logOffset) + .setState(allocation.state); + })); + return translateBulkLoadZooKeeperFailures(response); } @Override public CompletableFuture commitBulkLoadBucketSnapshot( CommitBulkLoadBucketSnapshotRequest request) { PbBulkLoadHandle handle = request.getHandle(); - authorizeBulkLoad(handle.getTableId()); - return submitBulkLoadOperation( - manager -> { - TableBucket bucket = - new TableBucket( - handle.getTableId(), - request.hasPartitionId() - ? request.getPartitionId() - : null, - request.getBucketId()); - CoordinatorEventProcessor processor = - coordinatorEventProcessorSupplier.get(); - return manager.commitBucketSnapshot( - handle.getBulkLoadId(), - bucket, - processor.completedSnapshotStoreManager(), - processor.getCoordinatorEventManager()); - }) + authorizeTable(OperationType.WRITE, handle.getTableId()); + TableBucket bucket = + new TableBucket( + handle.getTableId(), + request.hasPartitionId() ? request.getPartitionId() : null, + request.getBucketId()); + CoordinatorEventProcessor coordinator = requireLeaderEventProcessor(); + CompletableFuture> prepared = new CompletableFuture<>(); + ioExecutor.execute( + () -> + completeFromCallable( + prepared, + () -> { + checkCoordinatorLeadership(coordinator); + BulkLoadManager manager = coordinator.bulkLoadManager(); + return manager.commitBucketSnapshot( + handle.getBulkLoadId(), + bucket, + coordinator.completedSnapshotStoreManager(), + coordinator.getCoordinatorEventManager()); + })); + return translateBulkLoadZooKeeperFailures(prepared.thenCompose(publication -> publication)) .thenApply(ignored -> new CommitBulkLoadBucketSnapshotResponse()); } - private void authorizeBulkLoad(long tableId) { + private CoordinatorEventProcessor requireLeaderEventProcessor() { try { - authorizeTable(OperationType.WRITE, tableId); - } catch (UnknownTableOrBucketException e) { - throw new BulkLoadNotFoundException("The original BulkLoad table no longer exists."); + CoordinatorEventProcessor processor = coordinatorEventProcessorSupplier.get(); + checkCoordinatorLeadership(processor); + return processor; + } catch (IllegalStateException e) { + throw new NotCoordinatorLeaderException( + "BulkLoad requires the current Coordinator leader.", e); } } - private CompletableFuture submitBulkLoadOperation( - FunctionWithException, Exception> action) { - final int epochVersion = coordinatorZkVersionSupplier.get(); - return CompletableFuture.supplyAsync( - () -> { - if (!isLeader() || epochVersion < 0) { - throw new NotCoordinatorLeaderException( - "BulkLoad requires the current Coordinator leader."); - } - try { - return action.apply( - new BulkLoadManager(zkClient, epochVersion, ioExecutor)); - } catch (Exception e) { - throw new CompletionException(e); - } - }, - ioExecutor) - .thenCompose(result -> result) - .exceptionally( - failure -> { - Throwable cause = ExceptionUtils.stripCompletionException(failure); - if (cause instanceof KeeperException.ConnectionLossException) { - throw new NetworkException( - "Connection to BulkLoad metadata store was lost.", cause); - } - if (cause instanceof KeeperException.OperationTimeoutException) { - throw new TimeoutException( - "BulkLoad metadata operation timed out.", cause); - } - throw new CompletionException(cause); - }); + private void checkCoordinatorLeadership(CoordinatorEventProcessor coordinator) { + if (!isLeader() || coordinator.getCoordinatorZkVersion() < 0) { + throw new NotCoordinatorLeaderException( + "BulkLoad requires the current Coordinator leader."); + } + } + + private static CompletableFuture translateBulkLoadZooKeeperFailures( + CompletableFuture result) { + return result.exceptionally( + failure -> { + Throwable cause = ExceptionUtils.stripCompletionException(failure); + if (cause instanceof KeeperException.ConnectionLossException) { + throw new NetworkException( + "Connection to BulkLoad metadata store was lost.", cause); + } + if (cause instanceof KeeperException.OperationTimeoutException) { + throw new TimeoutException("BulkLoad metadata operation timed out.", cause); + } + throw new CompletionException(cause); + }); } @Override diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java index 63aa4fee13f..248e2846116 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java @@ -21,12 +21,29 @@ import org.apache.fluss.exception.BulkLoadStateException; import org.apache.fluss.exception.BulkLoadTargetWithdrawnException; import org.apache.fluss.exception.InvalidRequestException; +import org.apache.fluss.exception.NotCoordinatorLeaderException; +import org.apache.fluss.exception.PartitionNotExistException; +import org.apache.fluss.exception.SchemaNotExistException; +import org.apache.fluss.exception.TableNotExistException; +import org.apache.fluss.metadata.SchemaInfo; import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.metadata.TableDescriptor; +import org.apache.fluss.metadata.TableInfo; +import org.apache.fluss.metadata.TablePartition; import org.apache.fluss.metadata.TablePath; +import org.apache.fluss.rpc.messages.BeginBulkLoadResponse; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoResponse; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsResponse; +import org.apache.fluss.rpc.messages.PbBulkLoadStatus; +import org.apache.fluss.rpc.messages.PbBulkLoadTargetInfo; +import org.apache.fluss.rpc.messages.PbBulkLoadTargetProgress; import org.apache.fluss.server.coordinator.CompletedSnapshotStoreManager; import org.apache.fluss.server.coordinator.event.CommitBulkLoadBucketEvent; import org.apache.fluss.server.coordinator.event.EventManager; +import org.apache.fluss.server.coordinator.event.ReclaimTableBulkLoadMetadataEvent; import org.apache.fluss.server.kv.snapshot.CompletedSnapshot; +import org.apache.fluss.server.zk.BulkLoadTransactionStore; +import org.apache.fluss.server.zk.BulkLoadTransactionStore.BucketProgress; import org.apache.fluss.server.zk.ZooKeeperClient; import org.apache.fluss.server.zk.ZooKeeperClient.VersionedData; import org.apache.fluss.server.zk.data.BucketSnapshot; @@ -36,28 +53,321 @@ import org.apache.fluss.server.zk.data.bulkload.BulkLoadTarget; import org.apache.fluss.server.zk.data.bulkload.BulkLoadTransaction; import org.apache.fluss.shaded.zookeeper3.org.apache.zookeeper.KeeperException; +import org.apache.fluss.utils.ExceptionUtils; +import org.apache.fluss.utils.concurrent.Scheduler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nullable; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.function.Predicate; +import static org.apache.fluss.utils.PartitionUtils.HISTORICAL_PARTITION_VALUE; import static org.apache.fluss.utils.concurrent.FutureUtils.runAsync; -/** Allocates and commits snapshots for individual BulkLoad buckets. */ +/** + * Coordinates BulkLoad transactions and bucket snapshot imports. Transaction mutations run on the + * Coordinator event thread. Reading transaction progress and preparing bucket operations run on I/O + * threads. + */ public final class BulkLoadManager { + private static final Logger LOG = LoggerFactory.getLogger(BulkLoadManager.class); + private final ZooKeeperClient zooKeeperClient; - private final int epochVersion; + private final BulkLoadTransactionStore transactionStore; + private final int coordinatorEpochZkVersion; private final Executor ioExecutor; + private @Nullable ScheduledFuture metadataReclamationTask; - public BulkLoadManager(ZooKeeperClient zooKeeperClient, int epochVersion, Executor ioExecutor) { + public BulkLoadManager( + ZooKeeperClient zooKeeperClient, int coordinatorEpochZkVersion, Executor ioExecutor) { this.zooKeeperClient = zooKeeperClient; - this.epochVersion = epochVersion; + this.transactionStore = new BulkLoadTransactionStore(zooKeeperClient); + this.coordinatorEpochZkVersion = coordinatorEpochZkVersion; this.ioExecutor = ioExecutor; } + /** Establishes ownership of the selected physical targets and fixes their build context. */ + public BeginBulkLoadResponse begin( + TableInfo table, + @Nullable String bulkLoadId, + List names, + int maxTargets, + Function resolvePartitionTarget) + throws Exception { + requireDistinctPartitions(names); + String id = bulkLoadId == null ? UUID.randomUUID().toString() : bulkLoadId; + long tableId = table.getTableId(); + if (bulkLoadId != null) { + Optional> previous = + zooKeeperClient.getBulkLoadTransaction(tableId, id); + if (previous.isPresent()) { + return replayBegin(previous.get().data(), names, table); + } + } + + if (!table.hasPrimaryKey()) { + throw new InvalidRequestException("BulkLoad requires a primary key table."); + } + if (!table.getSchema().getAutoIncrementColumnNames().isEmpty()) { + throw new InvalidRequestException("BulkLoad does not support auto-increment columns."); + } + if (table.getTableConfig().getMergeEngineType().isPresent()) { + throw new InvalidRequestException( + "BulkLoad does not support tables with a merge engine."); + } + if (table.isPartitioned() == names.isEmpty()) { + throw new InvalidRequestException("Invalid partition selection for this table."); + } + if (Math.max(1, names.size()) > maxTargets) { + throw new InvalidRequestException("BulkLoad exceeds max-targets."); + } + + if (names.contains(HISTORICAL_PARTITION_VALUE)) { + throw new InvalidRequestException("Historical partitions are unsupported."); + } + List targets = resolveBeginTargets(table, names, resolvePartitionTarget); + BulkLoadTransaction transaction = + new BulkLoadTransaction( + tableId, + id, + table.getTablePath(), + table.getSchemaId(), + table.getRemoteDataDir(), + BulkLoadTransaction.RUNNING, + System.currentTimeMillis(), + null, + null); + try { + transactionStore.begin(transaction, targets, coordinatorEpochZkVersion); + } catch (KeeperException.NodeExistsException e) { + // Curator may retry a Begin whose first write succeeded without a response. + Optional> current = + zooKeeperClient.getBulkLoadTransaction(tableId, id); + if (current.isPresent()) { + BulkLoadTransaction existing = current.get().data(); + return replayBegin(existing, names, table); + } + throw e; + } + return beginResponse(transaction, targets, table, table.toTableDescriptor()); + } + + /** Returns progress for the original targets, including withdrawn partitions. */ + public GetBulkLoadInfoResponse getBulkLoadInfo(long tableId, String bulkLoadId) + throws Exception { + BulkLoadTransaction transaction = getTransaction(tableId, bulkLoadId).data(); + TableRegistration table = getOriginalTableWithVersion(transaction).data(); + List targets = + transactionStore.getTargets(transaction, table.isPartitioned()); + if (targets.isEmpty()) { + // Reclamation may finish between the transaction and target reads. + throw new BulkLoadNotFoundException("BulkLoad transaction does not exist."); + } + boolean running = transaction.state == BulkLoadTransaction.RUNNING; + Map currentPartitions = + running && table.isPartitioned() + ? getCurrentPartitions(transaction, targets) + : Collections.emptyMap(); + GetBulkLoadInfoResponse response = + new GetBulkLoadInfoResponse().setStatus(status(transaction)); + for (BulkLoadTarget target : targets) { + BucketProgress buckets = + transactionStore.getBucketProgress(transaction, target.partitionId); + PbBulkLoadTargetProgress progress = + response.addTarget() + .setBucketCount(target.bucketCount) + .setAllocatedBucketCount(buckets.allocated) + .setCommittedBucketCount(buckets.committed) + .setWithdrawn(target.withdrawn); + if (target.partitionId != null) { + progress.setPartitionId(target.partitionId); + if (running && !target.withdrawn) { + PartitionRegistration partition = currentPartitions.get(target.partitionName); + progress.setWithdrawn( + partition == null || partition.getPartitionId() != target.partitionId); + } + } + } + return response; + } + + /** Lists the running transactions owning any of the selected current physical targets. */ + public ListInProgressBulkLoadsResponse listInProgressBulkLoads( + TablePath path, List names) throws Exception { + requireDistinctPartitions(names); + TableRegistration table = + zooKeeperClient + .getTable(path) + .orElseThrow( + () -> + new TableNotExistException( + "Table " + path + " does not exist.")); + if (!table.isPartitioned() && !names.isEmpty()) { + throw new InvalidRequestException("Non-partitioned target has partition names."); + } + + List ids = new ArrayList<>(); + if (table.isPartitioned()) { + Collection selected = + names.isEmpty() ? zooKeeperClient.getPartitions(path) : names; + Map registrations = + zooKeeperClient.getPartitionRegistrations(path, selected); + for (String name : selected) { + PartitionRegistration partition = registrations.get(name); + if (partition != null && partition.getTableId() == table.tableId) { + ids.add(partition.getPartitionId()); + } else if (!names.isEmpty()) { + throw partitionNotFound(name); + } + } + } else { + ids.add(null); + } + + ListInProgressBulkLoadsResponse response = new ListInProgressBulkLoadsResponse(); + for (BulkLoadTransaction transaction : + transactionStore.listRunningTransactions(table.tableId, ids)) { + response.addTransaction().copyFrom(status(transaction)); + } + return response; + } + + /** Ends the transaction, or returns its existing matching terminal result. */ + public PbBulkLoadStatus finishTransaction( + long tableId, + String bulkLoadId, + int terminalState, + @Nullable String abortMessage, + @Nullable TableInfo table, + Predicate partitionExists) + throws Exception { + VersionedData transaction = getTransaction(tableId, bulkLoadId); + BulkLoadTransaction original = transaction.data(); + if (table == null) { + throw originalTableNotFound(); + } + if (original.state == terminalState) { + return status(original); + } + requireRunning(original); + List targets = transactionStore.getTargets(original, table.isPartitioned()); + List newlyWithdrawnTargets = new ArrayList<>(); + for (int i = 0; i < targets.size(); i++) { + BulkLoadTarget target = targets.get(i); + if (!target.withdrawn + && target.partitionId != null + && !partitionExists.test(new TablePartition(tableId, target.partitionId))) { + BulkLoadTarget withdrawn = target.withdraw(); + targets.set(i, withdrawn); + newlyWithdrawnTargets.add(withdrawn); + } + } + if (!newlyWithdrawnTargets.isEmpty()) { + transactionStore.persistWithdrawnTargets( + original, newlyWithdrawnTargets, coordinatorEpochZkVersion); + } + try { + return status( + transactionStore.finishTransaction( + transaction, + targets, + terminalState, + abortMessage, + coordinatorEpochZkVersion)); + } catch (KeeperException.BadVersionException e) { + BulkLoadTransaction current = + getTransaction(original.tableId, original.bulkLoadId).data(); + if (current.state == terminalState) { + return status(current); + } + throw e; + } + } + + /** Schedules periodic metadata reclamation for the Coordinator leadership term. */ + public void startMetadataReclamation( + Scheduler scheduler, EventManager eventManager, long retentionMillis) { + AtomicBoolean sweepRunning = new AtomicBoolean(); + metadataReclamationTask = + scheduler.schedule( + "expire-bulk-load-results", + () -> + scheduleMetadataReclamation( + eventManager, retentionMillis, sweepRunning), + 0, + Duration.ofMinutes(1).toMillis()); + } + + /** Cancels the periodic trigger before the Coordinator event queue closes. */ + public void stopMetadataReclamation() { + if (metadataReclamationTask != null) { + metadataReclamationTask.cancel(false); + } + } + + /** Enqueues reclamation for a dropped physical table without waiting for the next sweep. */ + public void onTableDropped(long tableId, long retentionMillis, EventManager eventManager) { + enqueueTableMetadataReclamation( + tableId, System.currentTimeMillis() - retentionMillis, eventManager); + } + + /** Discovers tables and enqueues one metadata reclamation event at a time. */ + public CompletableFuture enqueueMetadataReclamation( + long retentionCutoff, EventManager eventManager) throws Exception { + CompletableFuture sweep = CompletableFuture.completedFuture(null); + // Other Coordinator events can run between tables. + for (long tableId : transactionStore.listTableIdsWithBulkLoadMetadata()) { + sweep = + sweep.thenCompose( + ignored -> + enqueueTableMetadataReclamation( + tableId, retentionCutoff, eventManager)); + } + return sweep; + } + + /** Reclaims eligible BulkLoad metadata for one physical table. */ + public void reclaimTableBulkLoadMetadata( + long tableId, long retentionCutoff, boolean tableDropped, boolean hasPendingPublication) + throws Exception { + boolean hasRetainedResults = false; + for (VersionedData storedTransaction : + transactionStore.getTransactionsForTable(tableId)) { + BulkLoadTransaction transaction = storedTransaction.data(); + boolean expired = + transaction.finishedTime != null && transaction.finishedTime <= retentionCutoff; + if (tableDropped || (expired && !hasPendingPublication)) { + transactionStore.reclaimTransaction(storedTransaction, coordinatorEpochZkVersion); + } else { + hasRetainedResults = true; + } + } + if (!hasRetainedResults) { + transactionStore.pruneTableDirectories(tableId, coordinatorEpochZkVersion); + } + } + /** * Allocates a snapshot at the bucket's current recovery offset, or returns its existing * allocation. @@ -67,7 +377,7 @@ public BulkLoadBucket allocateBucketSnapshot(String bulkLoadId, TableBucket buck VersionedData transaction = getTransaction(bucket.getTableId(), bulkLoadId); BulkLoadTransaction original = transaction.data(); - VersionedData table = getOriginalTable(original); + VersionedData table = getOriginalTableWithVersion(original); BulkLoadBucket existing = zooKeeperClient.getBulkLoadBucket(original, bucket).orElse(null); if (existing != null && existing.state == BulkLoadBucket.COMMITTED) { return existing; @@ -95,7 +405,7 @@ public BulkLoadBucket allocateBucketSnapshot(String bulkLoadId, TableBucket buck allocation, table.zkVersion(), partitionVersion, - epochVersion); + coordinatorEpochZkVersion); return allocation; } catch (KeeperException.NodeExistsException e) { // The preceding checks succeeded; only creating the bucket record can report @@ -122,7 +432,8 @@ public CompletableFuture commitBucketSnapshot( VersionedData transaction = getTransaction(bucket.getTableId(), bulkLoadId); BulkLoadTransaction bulkLoadTransaction = transaction.data(); - VersionedData currentTable = getOriginalTable(bulkLoadTransaction); + VersionedData currentTable = + getOriginalTableWithVersion(bulkLoadTransaction); Optional record = zooKeeperClient.getBulkLoadBucket(bulkLoadTransaction, bucket); if (record.isPresent() && record.get().state == BulkLoadBucket.COMMITTED) { @@ -145,7 +456,7 @@ public CompletableFuture commitBucketSnapshot( target, currentTable.zkVersion(), partitionVersion, - epochVersion, + coordinatorEpochZkVersion, snapshotStores.getOrCreateCompletedSnapshotStore(tablePath, bucket)); eventManager.put(event); return event.result @@ -165,6 +476,161 @@ public CompletableFuture commitBucketSnapshot( .thenCompose(result -> result); } + private void scheduleMetadataReclamation( + EventManager eventManager, long retentionMillis, AtomicBoolean sweepRunning) { + if (!sweepRunning.compareAndSet(false, true)) { + return; + } + try { + ioExecutor.execute( + () -> enqueuePeriodicReclamation(eventManager, retentionMillis, sweepRunning)); + } catch (RejectedExecutionException ignored) { + sweepRunning.set(false); + } + } + + private void enqueuePeriodicReclamation( + EventManager eventManager, long retentionMillis, AtomicBoolean sweepRunning) { + try { + enqueueMetadataReclamation(System.currentTimeMillis() - retentionMillis, eventManager) + .whenComplete((ignored, failure) -> sweepRunning.set(false)); + } catch (Exception e) { + sweepRunning.set(false); + LOG.warn("Failed to discover BulkLoad tables for maintenance.", e); + } + } + + private CompletableFuture enqueueTableMetadataReclamation( + long tableId, long retentionCutoff, EventManager eventManager) { + ReclaimTableBulkLoadMetadataEvent event = + new ReclaimTableBulkLoadMetadataEvent(tableId, retentionCutoff); + eventManager.put(event); + return event.result.exceptionally(failure -> handleReclamationFailure(tableId, failure)); + } + + private Void handleReclamationFailure(long tableId, Throwable failure) { + Throwable cause = ExceptionUtils.stripCompletionException(failure); + if (cause instanceof NotCoordinatorLeaderException) { + throw new CompletionException(cause); + } + LOG.warn("Failed to maintain BulkLoad metadata for table {}.", tableId, cause); + return null; + } + + private Map getCurrentPartitions( + BulkLoadTransaction transaction, List targets) throws Exception { + List partitionNames = new ArrayList<>(); + for (BulkLoadTarget target : targets) { + if (!target.withdrawn) { + partitionNames.add(target.partitionName); + } + } + return zooKeeperClient.getPartitionRegistrations(transaction.tablePath, partitionNames); + } + + private BeginBulkLoadResponse replayBegin( + BulkLoadTransaction transaction, List names, TableInfo table) throws Exception { + List targets = + transactionStore.getTargets(transaction, table.isPartitioned()); + Set original = new HashSet<>(); + for (BulkLoadTarget target : targets) { + if (target.partitionName != null) { + original.add(target.partitionName); + } + } + if (!original.equals(new HashSet<>(names))) { + throw new InvalidRequestException("bulk_load_id has different targets."); + } + TableDescriptor descriptor = table.toTableDescriptor(); + if (table.getSchemaId() != transaction.schemaId) { + SchemaInfo schema = + zooKeeperClient + .getSchemaById(transaction.tablePath, transaction.schemaId) + .orElseThrow( + () -> + new SchemaNotExistException( + String.format( + "Schema %d of table %s does not exist.", + transaction.schemaId, + transaction.tablePath))); + descriptor = TableDescriptor.builder(descriptor).schema(schema.getSchema()).build(); + } + return beginResponse(transaction, targets, table, descriptor); + } + + private static List resolveBeginTargets( + TableInfo table, + List names, + Function resolvePartitionTarget) { + if (!table.isPartitioned()) { + return Collections.singletonList( + new BulkLoadTarget( + null, null, table.getNumBuckets(), table.getRemoteDataDir(), false)); + } + List targets = new ArrayList<>(); + for (String name : names) { + BulkLoadTarget target = resolvePartitionTarget.apply(name); + if (target == null) { + throw partitionNotFound(name); + } + targets.add(target); + } + targets.sort(Comparator.comparing(target -> target.partitionId)); + return targets; + } + + private static BeginBulkLoadResponse beginResponse( + BulkLoadTransaction transaction, + List targets, + TableInfo table, + TableDescriptor descriptor) { + BeginBulkLoadResponse response = new BeginBulkLoadResponse(); + response.setStatus(status(transaction)); + response.setTableInfo() + .setTableId(table.getTableId()) + .setSchemaId(transaction.schemaId) + .setTableJson(descriptor.toJsonBytes()) + .setCreatedTime(table.getCreatedTime()) + .setModifiedTime(table.getModifiedTime()) + .setBucketCountEpoch(table.getBucketCountEpoch()) + .setRemoteDataDir(transaction.remoteDataDir); + for (BulkLoadTarget target : targets) { + PbBulkLoadTargetInfo info = + response.addTarget() + .setBucketCount(target.bucketCount) + .setRemoteDataDir(target.remoteDataDir); + if (target.partitionId != null) { + info.setPartitionId(target.partitionId).setPartitionName(target.partitionName); + } + } + return response; + } + + private static PbBulkLoadStatus status(BulkLoadTransaction transaction) { + PbBulkLoadStatus status = + new PbBulkLoadStatus() + .setState(transaction.state) + .setCreatedTime(transaction.createdTime); + status.setHandle().setTableId(transaction.tableId).setBulkLoadId(transaction.bulkLoadId); + if (transaction.finishedTime != null) { + status.setFinishedTime(transaction.finishedTime); + } + if (transaction.abortMessage != null) { + status.setAbortMessage(transaction.abortMessage); + } + return status; + } + + private static void requireDistinctPartitions(List names) { + if (new HashSet<>(names).size() != names.size()) { + throw new InvalidRequestException("Duplicate partition names."); + } + } + + private static PartitionNotExistException partitionNotFound(String name) { + return new PartitionNotExistException("Partition " + name + " does not exist."); + } + private VersionedData getTransaction(long tableId, String bulkLoadId) throws Exception { return zooKeeperClient @@ -175,15 +641,16 @@ private VersionedData getTransaction(long tableId, String b "BulkLoad transaction does not exist.")); } - private VersionedData getOriginalTable(BulkLoadTransaction transaction) - throws Exception { + private VersionedData getOriginalTableWithVersion( + BulkLoadTransaction transaction) throws Exception { return zooKeeperClient .getTableWithVersion(transaction.tablePath) .filter(table -> table.data().tableId == transaction.tableId) - .orElseThrow( - () -> - new BulkLoadNotFoundException( - "The original BulkLoad table no longer exists.")); + .orElseThrow(BulkLoadManager::originalTableNotFound); + } + + private static BulkLoadNotFoundException originalTableNotFound() { + return new BulkLoadNotFoundException("The original BulkLoad table no longer exists."); } private VersionedData resolveTarget( @@ -208,20 +675,22 @@ private VersionedData resolveTarget( if (target.withdrawn) { throw new BulkLoadTargetWithdrawnException("The original physical target was deleted."); } + VersionedData partition = + target.partitionId == null + ? null + : getOriginalPartition(transaction.tablePath, target); // KV encoding, row TTL, and changelog image are immutable through ALTER TABLE. if (zooKeeperClient.getCurrentSchemaId(transaction.tablePath) != transaction.schemaId || !Objects.equals(table.remoteDataDir, transaction.remoteDataDir)) { throw new InvalidRequestException("BulkLoad build context changed."); } - if (target.partitionId == null) { + if (partition == null) { if (table.bucketCount != target.bucketCount) { throw new InvalidRequestException("BulkLoad target bucket count changed."); } return null; } - VersionedData partition = - getOriginalPartition(transaction.tablePath, target); PartitionRegistration registration = partition.data(); int bucketCount = registration.getBucketCountOrDefault(table.bucketCount, table.bucketCountEpoch); @@ -245,7 +714,7 @@ private VersionedData getOriginalPartition( private void checkMutationTarget(BulkLoadTransaction original, BulkLoadTarget target) throws Exception { - getOriginalTable(original); + getOriginalTableWithVersion(original); requireRunning(getTransaction(original.tableId, original.bulkLoadId).data()); if (target.partitionId != null) { getOriginalPartition(original.tablePath, target); diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java new file mode 100644 index 00000000000..c6641b214b3 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java @@ -0,0 +1,43 @@ +/* + * 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; + +import org.apache.fluss.rpc.messages.AbortBulkLoadResponse; + +import javax.annotation.Nullable; + +import java.util.concurrent.CompletableFuture; + +/** Aborts a BulkLoad transaction and releases ownership. */ +public final class AbortBulkLoadEvent implements CoordinatorEvent { + public final long tableId; + public final String bulkLoadId; + public final @Nullable String abortMessage; + public final CompletableFuture result; + + public AbortBulkLoadEvent( + long tableId, + String bulkLoadId, + @Nullable String abortMessage, + CompletableFuture result) { + this.tableId = tableId; + this.bulkLoadId = bulkLoadId; + this.abortMessage = abortMessage; + this.result = result; + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java new file mode 100644 index 00000000000..c7bd9873f15 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java @@ -0,0 +1,45 @@ +/* + * 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; + +import org.apache.fluss.metadata.TablePath; +import org.apache.fluss.rpc.messages.BeginBulkLoadResponse; + +import javax.annotation.Nullable; + +import java.util.List; +import java.util.concurrent.CompletableFuture; + +/** Starts or replays a BulkLoad transaction. */ +public final class BeginBulkLoadEvent implements CoordinatorEvent { + public final TablePath tablePath; + public final @Nullable String bulkLoadId; + public final List partitionNames; + public final CompletableFuture result; + + public BeginBulkLoadEvent( + TablePath tablePath, + @Nullable String bulkLoadId, + List partitionNames, + CompletableFuture result) { + this.tablePath = tablePath; + this.bulkLoadId = bulkLoadId; + this.partitionNames = partitionNames; + this.result = result; + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java new file mode 100644 index 00000000000..dc3d87d13e5 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java @@ -0,0 +1,36 @@ +/* + * 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; + +import org.apache.fluss.rpc.messages.CommitBulkLoadResponse; + +import java.util.concurrent.CompletableFuture; + +/** Commits a BulkLoad transaction after verifying bucket completion. */ +public final class CommitBulkLoadEvent implements CoordinatorEvent { + public final long tableId; + public final String bulkLoadId; + public final CompletableFuture result; + + public CommitBulkLoadEvent( + long tableId, String bulkLoadId, CompletableFuture result) { + this.tableId = tableId; + this.bulkLoadId = bulkLoadId; + this.result = result; + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java index 596b250db19..98feb5183bf 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java @@ -35,6 +35,7 @@ import org.slf4j.LoggerFactory; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; @@ -226,9 +227,7 @@ public void put(CoordinatorEvent event) { inLock( putLock, () -> { - if (thread.isShutdownInitiated() - && event instanceof CommitBulkLoadBucketEvent) { - rejectPendingPublication(event); + if (thread.isShutdownInitiated() && rejectPendingBulkLoadEvent(event)) { return; } try { @@ -244,7 +243,7 @@ public void put(CoordinatorEvent event) { event, event.getClass()); } catch (InterruptedException e) { - rejectPendingPublication(event); + rejectPendingBulkLoadEvent(event); LOG.error("Fail to put coordinator event {}.", event, e); } }); @@ -256,20 +255,36 @@ public void clearAndPut(CoordinatorEvent event) { () -> { QueuedEvent pending; while ((pending = queue.poll()) != null) { - rejectPendingPublication(pending.event); + rejectPendingBulkLoadEvent(pending.event); } put(event); }); } - private static void rejectPendingPublication(CoordinatorEvent event) { + private static boolean rejectPendingBulkLoadEvent(CoordinatorEvent event) { if (event instanceof CommitBulkLoadBucketEvent) { CommitBulkLoadBucketEvent commit = (CommitBulkLoadBucketEvent) event; commit.result.completeExceptionally( new NotCoordinatorLeaderException( "Coordinator stopped before publishing " + commit.snapshot.getTableBucket())); + return true; } + + CompletableFuture response; + if (event instanceof BeginBulkLoadEvent) { + response = ((BeginBulkLoadEvent) event).result; + } else if (event instanceof CommitBulkLoadEvent) { + response = ((CommitBulkLoadEvent) event).result; + } else if (event instanceof AbortBulkLoadEvent) { + response = ((AbortBulkLoadEvent) event).result; + } else { + return false; + } + response.completeExceptionally( + new NotCoordinatorLeaderException( + "Coordinator stopped before processing BulkLoad metadata.")); + return true; } private class CoordinatorEventThread extends ShutdownableThread { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java new file mode 100644 index 00000000000..fc455fe3d30 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java @@ -0,0 +1,32 @@ +/* + * 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; + +import java.util.concurrent.CompletableFuture; + +/** Requests BulkLoad metadata reclamation for one physical table. */ +public final class ReclaimTableBulkLoadMetadataEvent implements CoordinatorEvent { + public final long tableId; + public final long retentionCutoff; + public final CompletableFuture result = new CompletableFuture<>(); + + public ReclaimTableBulkLoadMetadataEvent(long tableId, long retentionCutoff) { + this.tableId = tableId; + this.retentionCutoff = retentionCutoff; + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/BulkLoadTransactionStore.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/BulkLoadTransactionStore.java new file mode 100644 index 00000000000..d9ea3740f3f --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/BulkLoadTransactionStore.java @@ -0,0 +1,440 @@ +/* + * 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; + +import org.apache.fluss.exception.BulkLoadConflictException; +import org.apache.fluss.exception.BulkLoadIncompleteException; +import org.apache.fluss.server.zk.ZkAsyncResponse.ZkGetDataResponse; +import org.apache.fluss.server.zk.ZooKeeperClient.VersionedData; +import org.apache.fluss.server.zk.data.ZkData.BulkLoadBucketZNode; +import org.apache.fluss.server.zk.data.ZkData.BulkLoadOwnerZNode; +import org.apache.fluss.server.zk.data.ZkData.BulkLoadTableZNode; +import org.apache.fluss.server.zk.data.ZkData.BulkLoadTargetZNode; +import org.apache.fluss.server.zk.data.ZkData.BulkLoadTransactionZNode; +import org.apache.fluss.server.zk.data.bulkload.BulkLoadBucket; +import org.apache.fluss.server.zk.data.bulkload.BulkLoadTarget; +import org.apache.fluss.server.zk.data.bulkload.BulkLoadTransaction; +import org.apache.fluss.shaded.curator5.org.apache.curator.framework.api.transaction.CuratorOp; +import org.apache.fluss.shaded.zookeeper3.org.apache.zookeeper.CreateMode; +import org.apache.fluss.shaded.zookeeper3.org.apache.zookeeper.KeeperException; + +import javax.annotation.Nullable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.apache.fluss.server.zk.ZooKeeperClient.processGetDataResponsesOrThrow; +import static org.apache.fluss.utils.Preconditions.checkNotNull; +import static org.apache.fluss.utils.Preconditions.checkState; + +/** Persists BulkLoad transaction lifecycle metadata in ZooKeeper. */ +public final class BulkLoadTransactionStore { + private static final int BUCKET_DELETE_BATCH_SIZE = 128; + + private final ZooKeeperClient zooKeeperClient; + private final ZooKeeperOp zkOp; + + /** Creates a store over the existing ZooKeeper connection. */ + public BulkLoadTransactionStore(ZooKeeperClient zooKeeperClient) { + this.zooKeeperClient = zooKeeperClient; + this.zkOp = new ZooKeeperOp(zooKeeperClient.getCuratorClient()); + } + + /** Atomically fixes the targets and acquires all ownership for a new transaction. */ + public void begin( + BulkLoadTransaction transaction, + List targets, + int coordinatorEpochZkVersion) + throws Exception { + long tableId = transaction.tableId; + String bulkLoadId = transaction.bulkLoadId; + boolean partitioned = targets.get(0).partitionId != null; + ensureBulkLoadDirectory(BulkLoadTableZNode.transactions(tableId)); + ensureBulkLoadDirectory( + partitioned + ? BulkLoadOwnerZNode.partitions(tableId) + : BulkLoadOwnerZNode.root(tableId)); + List operations = new ArrayList<>(); + operations.add( + createPersistent( + BulkLoadTransactionZNode.path(tableId, bulkLoadId), + BulkLoadTransactionZNode.encode(transaction))); + byte[] empty = new byte[0]; + operations.add(createPersistent(BulkLoadTargetZNode.root(tableId, bulkLoadId), empty)); + if (partitioned) { + operations.add( + createPersistent(BulkLoadTargetZNode.partitions(tableId, bulkLoadId), empty)); + } + byte[] ownerBytes = BulkLoadOwnerZNode.encode(bulkLoadId); + for (BulkLoadTarget target : targets) { + Long partitionId = target.partitionId; + operations.add( + createPersistent(BulkLoadOwnerZNode.path(tableId, partitionId), ownerBytes)); + operations.add( + createPersistent( + BulkLoadTargetZNode.path(tableId, bulkLoadId, partitionId), + BulkLoadTargetZNode.encode(target))); + operations.add( + createPersistent(BulkLoadBucketZNode.root(transaction, partitionId), empty)); + } + List fencedOperations = + zooKeeperClient.wrapRequestsWithEpochCheck(operations, coordinatorEpochZkVersion); + try { + zooKeeperClient.writeBulkLoadMetadata(fencedOperations, coordinatorEpochZkVersion); + } catch (KeeperException.NodeExistsException e) { + String ownerRoot = BulkLoadOwnerZNode.root(tableId) + "/"; + for (int i = 0; i < fencedOperations.size(); i++) { + if (ZooKeeperClient.failedMultiOperation(e, i) + && fencedOperations + .get(i) + .getTypeAndPath() + .getForPath() + .startsWith(ownerRoot)) { + throw new BulkLoadConflictException( + "BulkLoad target is already owned. " + + "Use ListInProgressBulkLoads to find the current owner."); + } + } + throw e; + } + } + + /** + * Lists running transactions that own at least one of the selected physical targets. A {@code + * null} entry in {@code partitionIds} selects the whole-table target. + */ + public List listRunningTransactions(long tableId, List partitionIds) + throws Exception { + List ownerPaths = new ArrayList<>(partitionIds.size()); + for (Long partitionId : partitionIds) { + ownerPaths.add(BulkLoadOwnerZNode.path(tableId, partitionId)); + } + Map owners = + processGetDataResponsesOrThrow( + zooKeeperClient.getDataInBackground(ownerPaths), + ZkGetDataResponse::getPath, + BulkLoadOwnerZNode::decode); + Set transactionPaths = new LinkedHashSet<>(); + for (String ownerPath : ownerPaths) { + String owner = owners.get(ownerPath); + if (owner != null) { + transactionPaths.add(BulkLoadTransactionZNode.path(tableId, owner)); + } + } + List runningTransactions = new ArrayList<>(); + for (VersionedData storedTransaction : + readTransactions(transactionPaths)) { + BulkLoadTransaction transaction = storedTransaction.data(); + if (transaction.state == BulkLoadTransaction.RUNNING) { + runningTransactions.add(transaction); + } + } + return runningTransactions; + } + + /** Reads the fixed targets in physical partition ID order. */ + public List getTargets(BulkLoadTransaction transaction, boolean partitioned) + throws Exception { + return partitioned ? getPartitionTargets(transaction) : getTableTarget(transaction); + } + + /** Counts existing allocation records and completed bucket commits for the target. */ + public BucketProgress getBucketProgress( + BulkLoadTransaction transaction, @Nullable Long partitionId) throws Exception { + String bucketRoot = BulkLoadBucketZNode.root(transaction, partitionId); + return countBucketProgress(bucketRoot, zooKeeperClient.getChildren(bucketRoot)); + } + + /** Persists withdrawn targets so prepared bucket writes fail their target version check. */ + public void persistWithdrawnTargets( + BulkLoadTransaction transaction, + List withdrawnTargets, + int coordinatorEpochZkVersion) + throws Exception { + List updates = new ArrayList<>(); + for (BulkLoadTarget target : withdrawnTargets) { + updates.add( + zkOp.updateOp( + BulkLoadTargetZNode.path( + transaction.tableId, + transaction.bulkLoadId, + target.partitionId), + BulkLoadTargetZNode.encode(target))); + } + writeWithCoordinatorEpochCheck(updates, coordinatorEpochZkVersion); + } + + /** Ends the transaction and atomically releases its owners. */ + public BulkLoadTransaction finishTransaction( + VersionedData transaction, + List targets, + int state, + @Nullable String abortMessage, + int coordinatorEpochZkVersion) + throws Exception { + BulkLoadTransaction current = transaction.data(); + checkState(current.state == BulkLoadTransaction.RUNNING, "BulkLoad is already terminal."); + if (state == BulkLoadTransaction.COMMITTED) { + for (BulkLoadTarget target : targets) { + if (target.withdrawn) { + continue; + } + String bucketRoot = BulkLoadBucketZNode.root(current, target.partitionId); + List bucketNodes = zooKeeperClient.getChildren(bucketRoot); + // Allocate creates at most one record for each bucket in the target's fixed range. + if (bucketNodes.size() != target.bucketCount + || countBucketProgress(bucketRoot, bucketNodes).committed + != target.bucketCount) { + throw new BulkLoadIncompleteException("BulkLoad transaction is incomplete."); + } + } + } + BulkLoadTransaction result = + current.withTerminalState(state, System.currentTimeMillis(), abortMessage); + List operations = new ArrayList<>(); + // Advancing the root version also fences in-flight bucket mutations. + operations.add( + zkOp.updateOp( + BulkLoadTransactionZNode.path(current.tableId, current.bulkLoadId), + BulkLoadTransactionZNode.encode(result), + transaction.zkVersion())); + for (BulkLoadTarget target : targets) { + operations.add( + zkOp.deleteOp(BulkLoadOwnerZNode.path(current.tableId, target.partitionId))); + } + writeWithCoordinatorEpochCheck(operations, coordinatorEpochZkVersion); + return result; + } + + /** Lists physical table IDs with BulkLoad metadata. */ + public List listTableIdsWithBulkLoadMetadata() throws Exception { + return zooKeeperClient.getChildren(BulkLoadTableZNode.root()).stream() + .map(Long::parseLong) + .collect(Collectors.toList()); + } + + /** + * Reads running and retained terminal transactions and their versions for one physical table. + */ + public List> getTransactionsForTable(long tableId) + throws Exception { + return readTransactions(childPaths(BulkLoadTableZNode.transactions(tableId))); + } + + /** Ends a running transaction before removing its bucket records. */ + public void reclaimTransaction( + VersionedData storedTransaction, int coordinatorEpochZkVersion) + throws Exception { + BulkLoadTransaction transaction = storedTransaction.data(); + List targets = discoverTargets(transaction); + if (transaction.state == BulkLoadTransaction.RUNNING) { + finishTransaction( + storedTransaction, + targets, + BulkLoadTransaction.ABORTED, + null, + coordinatorEpochZkVersion); + } + deleteTransactionRecords(transaction, targets, coordinatorEpochZkVersion); + } + + /** Removes organizing directories once the event thread has reclaimed the last result. */ + public void pruneTableDirectories(long tableId, int coordinatorEpochZkVersion) + throws Exception { + String tableRoot = BulkLoadTableZNode.path(tableId); + if (!zooKeeperClient.getStat(tableRoot).isPresent()) { + return; + } + for (String path : + new String[] { + BulkLoadOwnerZNode.partitions(tableId), + BulkLoadOwnerZNode.root(tableId), + BulkLoadTableZNode.transactions(tableId), + tableRoot + }) { + try { + writeWithCoordinatorEpochCheck( + Collections.singletonList(zkOp.deleteOp(path)), coordinatorEpochZkVersion); + } catch (KeeperException.NoNodeException | KeeperException.NotEmptyException ignored) { + // A directory may be absent or still contain records pending the next pass. + } + } + } + + private List> readTransactions(Collection paths) + throws Exception { + Map> transactions = new HashMap<>(); + for (ZkGetDataResponse response : zooKeeperClient.getDataInBackground(paths)) { + if (response.getResultCode() == KeeperException.Code.NONODE) { + continue; + } + response.maybeThrow(); + int version = checkNotNull(response.getStat()).getVersion(); + transactions.put( + response.getPath(), + new VersionedData<>( + BulkLoadTransactionZNode.decode(response.getData()), version)); + } + List> ordered = new ArrayList<>(transactions.size()); + for (String path : paths) { + VersionedData transaction = transactions.get(path); + if (transaction != null) { + ordered.add(transaction); + } + } + return ordered; + } + + private List discoverTargets(BulkLoadTransaction transaction) throws Exception { + List tableTarget = getTableTarget(transaction); + return tableTarget.isEmpty() ? getPartitionTargets(transaction) : tableTarget; + } + + private List getTableTarget(BulkLoadTransaction transaction) throws Exception { + Optional> target = + zooKeeperClient.getBulkLoadTarget(transaction, null); + return target.isPresent() + ? Collections.singletonList(target.get().data()) + : Collections.emptyList(); + } + + private List getPartitionTargets(BulkLoadTransaction transaction) + throws Exception { + String partitionTargetsRoot = + BulkLoadTargetZNode.partitions(transaction.tableId, transaction.bulkLoadId); + List targets = new ArrayList<>(); + for (ZkGetDataResponse response : + zooKeeperClient.getDataInBackground(childPaths(partitionTargetsRoot))) { + if (response.getResultCode() != KeeperException.Code.NONODE) { + response.maybeThrow(); + targets.add(BulkLoadTargetZNode.decode(response.getData())); + } + } + targets.sort(Comparator.comparing(target -> target.partitionId)); + return targets; + } + + private BucketProgress countBucketProgress(String bucketRoot, List bucketNodes) + throws Exception { + long allocated = 0; + long committed = 0; + for (ZkGetDataResponse response : + zooKeeperClient.getDataInBackground(childPaths(bucketRoot, bucketNodes))) { + if (response.getResultCode() == KeeperException.Code.NONODE) { + continue; + } + response.maybeThrow(); + allocated++; + if (BulkLoadBucketZNode.decode(response.getData()).state == BulkLoadBucket.COMMITTED) { + committed++; + } + } + return new BucketProgress(allocated, committed); + } + + private CuratorOp createPersistent(String path, byte[] data) throws Exception { + return zkOp.createOp(path, data, CreateMode.PERSISTENT); + } + + private void ensureBulkLoadDirectory(String path) throws Exception { + try { + zooKeeperClient + .getCuratorClient() + .create() + .creatingParentsIfNeeded() + .forPath(path, new byte[0]); + } catch (KeeperException.NodeExistsException ignored) { + // Another transaction already created the organizing directory. + } + } + + private void deleteTransactionRecords( + BulkLoadTransaction transaction, + List targets, + int coordinatorEpochZkVersion) + throws Exception { + long tableId = transaction.tableId; + String bulkLoadId = transaction.bulkLoadId; + List removals = new ArrayList<>(); + for (BulkLoadTarget target : targets) { + Long partitionId = target.partitionId; + String bucketRecordsRoot = BulkLoadBucketZNode.root(transaction, partitionId); + deleteBucketRecordsInBatches(bucketRecordsRoot, coordinatorEpochZkVersion); + removals.add(zkOp.deleteOp(bucketRecordsRoot)); + removals.add(zkOp.deleteOp(BulkLoadTargetZNode.path(tableId, bulkLoadId, partitionId))); + } + if (!targets.isEmpty() && targets.get(0).partitionId != null) { + removals.add(zkOp.deleteOp(BulkLoadTargetZNode.partitions(tableId, bulkLoadId))); + } + removals.add(zkOp.deleteOp(BulkLoadTargetZNode.root(tableId, bulkLoadId))); + removals.add(zkOp.deleteOp(BulkLoadTransactionZNode.path(tableId, bulkLoadId))); + writeWithCoordinatorEpochCheck(removals, coordinatorEpochZkVersion); + } + + private void deleteBucketRecordsInBatches( + String bucketRecordsRoot, int coordinatorEpochZkVersion) throws Exception { + List children = zooKeeperClient.getChildren(bucketRecordsRoot); + for (int start = 0; start < children.size(); start += BUCKET_DELETE_BATCH_SIZE) { + int end = Math.min(start + BUCKET_DELETE_BATCH_SIZE, children.size()); + List operations = new ArrayList<>(end - start); + for (int i = start; i < end; i++) { + operations.add(zkOp.deleteOp(bucketRecordsRoot + "/" + children.get(i))); + } + writeWithCoordinatorEpochCheck(operations, coordinatorEpochZkVersion); + } + } + + private List childPaths(String root) throws Exception { + return childPaths(root, zooKeeperClient.getChildren(root)); + } + + private static List childPaths(String root, List children) { + List paths = new ArrayList<>(children.size()); + for (String child : children) { + paths.add(root + "/" + child); + } + return paths; + } + + private void writeWithCoordinatorEpochCheck( + List operations, int coordinatorEpochZkVersion) throws Exception { + zooKeeperClient.writeBulkLoadMetadata( + zooKeeperClient.wrapRequestsWithEpochCheck(operations, coordinatorEpochZkVersion), + coordinatorEpochZkVersion); + } + + /** The persisted bucket progress for a single physical target. */ + public static final class BucketProgress { + public final long allocated; + public final long committed; + + private BucketProgress(long allocated, long committed) { + this.allocated = allocated; + this.committed = committed; + } + } +} 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 0bf795419e3..1fce6aae013 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 @@ -1564,7 +1564,7 @@ public boolean checkBulkLoadBucketCommitted(BulkLoadTransaction transaction, Tab } } - private void writeBulkLoadMetadata(List fencedOperations, int epochVersion) + void writeBulkLoadMetadata(List fencedOperations, int epochVersion) throws Exception { try { zkClient.transaction().forOperations(fencedOperations); @@ -1576,7 +1576,7 @@ private void writeBulkLoadMetadata(List fencedOperations, int epochVe } } - private static boolean failedMultiOperation(KeeperException e, int index) { + static boolean failedMultiOperation(KeeperException e, int index) { List results = e.getResults(); return results != null && index < results.size() 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 a82fda333b8..e5bdfce9531 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 @@ -310,10 +310,25 @@ public static String path() { // ZNodes under "/bulk_load/" // ------------------------------------------------------------------------------------------ + /** The transaction and ownership directories of one physical table. */ + public static final class BulkLoadTableZNode { + public static String root() { + return "/bulk_load/tables"; + } + + public static String path(long tableId) { + return root() + "/" + tableId; + } + + public static String transactions(long tableId) { + return path(tableId) + "/transactions"; + } + } + /** The transaction record written by BeginBulkLoad. */ public static final class BulkLoadTransactionZNode { public static String path(long tableId, String bulkLoadId) { - return "/bulk_load/tables/" + tableId + "/transactions/" + bulkLoadId; + return BulkLoadTableZNode.transactions(tableId) + "/" + bulkLoadId; } public static byte[] encode(BulkLoadTransaction transaction) { @@ -328,10 +343,18 @@ public static BulkLoadTransaction decode(byte[] json) { /** The table or physical partition targeted by a transaction. */ public static final class BulkLoadTargetZNode { + public static String root(long tableId, String bulkLoadId) { + return BulkLoadTransactionZNode.path(tableId, bulkLoadId) + "/targets"; + } + + public static String partitions(long tableId, String bulkLoadId) { + return root(tableId, bulkLoadId) + "/partitions"; + } + public static String path(long tableId, String bulkLoadId, @Nullable Long partitionId) { - return BulkLoadTransactionZNode.path(tableId, bulkLoadId) - + "/targets" - + (partitionId == null ? "/table" : "/partitions/" + partitionId); + return partitionId == null + ? root(tableId, bulkLoadId) + "/table" + : partitions(tableId, bulkLoadId) + "/" + partitionId; } public static byte[] encode(BulkLoadTarget target) { @@ -343,13 +366,48 @@ public static BulkLoadTarget decode(byte[] json) { } } + /** The transaction that currently owns a table or physical partition. */ + public static final class BulkLoadOwnerZNode { + public static String root(long tableId) { + return BulkLoadTableZNode.path(tableId) + "/owners"; + } + + public static String partitions(long tableId) { + return root(tableId) + "/partitions"; + } + + public static String path(long tableId, @Nullable Long partitionId) { + return partitionId == null + ? root(tableId) + "/table" + : partitions(tableId) + "/" + partitionId; + } + + public static byte[] encode(String bulkLoadId) { + return JsonSerdeUtils.writeValueAsBytes( + bulkLoadId, + (id, out) -> { + out.writeStartObject(); + out.writeNumberField("version", 1); + out.writeStringField("bulk_load_id", id); + out.writeEndObject(); + }); + } + + public static String decode(byte[] json) { + return JsonSerdeUtils.readValue(json, node -> node.get("bulk_load_id").asText()); + } + } + /** The allocation and commit state of a target bucket. */ public static final class BulkLoadBucketZNode { - public static String path(BulkLoadTransaction transaction, TableBucket bucket) { + public static String root(BulkLoadTransaction transaction, @Nullable Long partitionId) { return BulkLoadTargetZNode.path( - transaction.tableId, transaction.bulkLoadId, bucket.getPartitionId()) - + "/buckets/" - + bucket.getBucket(); + transaction.tableId, transaction.bulkLoadId, partitionId) + + "/buckets"; + } + + public static String path(BulkLoadTransaction transaction, TableBucket bucket) { + return root(transaction, bucket.getPartitionId()) + "/" + bucket.getBucket(); } public static byte[] encode(BulkLoadBucket bucket) { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTarget.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTarget.java index fd3ed08b22a..2e370dfe44d 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTarget.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTarget.java @@ -43,4 +43,9 @@ public BulkLoadTarget( this.remoteDataDir = remoteDataDir; this.withdrawn = withdrawn; } + + /** Returns the representation of this target after its partition is dropped. */ + public BulkLoadTarget withdraw() { + return new BulkLoadTarget(partitionId, partitionName, bucketCount, remoteDataDir, true); + } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTransaction.java b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTransaction.java index 197536bdca9..a3ae56f01d9 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTransaction.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/zk/data/bulkload/BulkLoadTransaction.java @@ -60,4 +60,19 @@ public BulkLoadTransaction( this.finishedTime = finishedTime; this.abortMessage = abortMessage; } + + /** Returns the terminal representation of this transaction. */ + public BulkLoadTransaction withTerminalState( + int state, long now, @Nullable String abortMessage) { + return new BulkLoadTransaction( + tableId, + bulkLoadId, + tablePath, + schemaId, + remoteDataDir, + state, + createdTime, + now, + abortMessage); + } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/BulkLoadBucketCommitTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/BulkLoadBucketCommitTest.java index 673f583eaab..915d8172553 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/BulkLoadBucketCommitTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/BulkLoadBucketCommitTest.java @@ -20,9 +20,13 @@ import org.apache.fluss.config.ConfigOptions; import org.apache.fluss.config.Configuration; import org.apache.fluss.exception.BulkLoadConflictException; +import org.apache.fluss.exception.BulkLoadIncompleteException; import org.apache.fluss.exception.BulkLoadNotFoundException; +import org.apache.fluss.exception.BulkLoadStateException; +import org.apache.fluss.exception.BulkLoadTargetWithdrawnException; import org.apache.fluss.exception.FencedLeaderEpochException; import org.apache.fluss.exception.InvalidBulkLoadSnapshotException; +import org.apache.fluss.exception.InvalidRequestException; import org.apache.fluss.exception.NetworkException; import org.apache.fluss.exception.NotCoordinatorLeaderException; import org.apache.fluss.fs.FsPath; @@ -40,21 +44,35 @@ import org.apache.fluss.record.KvRecord; import org.apache.fluss.rpc.gateway.CoordinatorGateway; import org.apache.fluss.rpc.gateway.TabletServerGateway; +import org.apache.fluss.rpc.messages.AbortBulkLoadRequest; +import org.apache.fluss.rpc.messages.AbortBulkLoadResponse; import org.apache.fluss.rpc.messages.AcquireKvSnapshotLeaseRequest; import org.apache.fluss.rpc.messages.AdjustIsrResponse; import org.apache.fluss.rpc.messages.AllocateBulkLoadBucketSnapshotRequest; import org.apache.fluss.rpc.messages.AllocateBulkLoadBucketSnapshotResponse; +import org.apache.fluss.rpc.messages.AlterTableRequest; +import org.apache.fluss.rpc.messages.BeginBulkLoadRequest; +import org.apache.fluss.rpc.messages.BeginBulkLoadResponse; import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotRequest; +import org.apache.fluss.rpc.messages.CommitBulkLoadRequest; import org.apache.fluss.rpc.messages.CommitKvSnapshotResponse; import org.apache.fluss.rpc.messages.DropKvSnapshotLeaseRequest; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoRequest; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoResponse; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsRequest; import org.apache.fluss.rpc.messages.LookupRequest; import org.apache.fluss.rpc.messages.NotifyLeaderAndIsrRequest; +import org.apache.fluss.rpc.messages.PbAddColumn; import org.apache.fluss.rpc.messages.PbBulkLoadHandle; +import org.apache.fluss.rpc.messages.PbBulkLoadStatus; +import org.apache.fluss.rpc.messages.PbBulkLoadTargetInfo; +import org.apache.fluss.rpc.messages.PbBulkLoadTargetProgress; import org.apache.fluss.rpc.messages.PbNotifyLeaderAndIsrRespForBucket; import org.apache.fluss.rpc.messages.PbPutKvRespForBucket; import org.apache.fluss.rpc.messages.PutKvRequest; import org.apache.fluss.rpc.protocol.Errors; import org.apache.fluss.server.coordinator.bulkload.BulkLoadManager; +import org.apache.fluss.server.coordinator.event.AbortBulkLoadEvent; import org.apache.fluss.server.coordinator.event.AccessContextEvent; import org.apache.fluss.server.coordinator.event.AdjustIsrReceivedEvent; import org.apache.fluss.server.coordinator.event.CommitKvSnapshotEvent; @@ -81,6 +99,8 @@ import org.apache.fluss.server.zk.ZooKeeperExtension; import org.apache.fluss.server.zk.data.BucketSnapshot; import org.apache.fluss.server.zk.data.LeaderAndIsr; +import org.apache.fluss.server.zk.data.PartitionRegistration; +import org.apache.fluss.server.zk.data.ZkData.BulkLoadTableZNode; import org.apache.fluss.server.zk.data.ZkData.BulkLoadTargetZNode; import org.apache.fluss.server.zk.data.ZkData.BulkLoadTransactionZNode; import org.apache.fluss.server.zk.data.ZkData.LeaderAndIsrZNode; @@ -101,6 +121,8 @@ import org.apache.fluss.utils.FlussPaths; import org.apache.fluss.utils.clock.SystemClock; import org.apache.fluss.utils.concurrent.FlussScheduler; +import org.apache.fluss.utils.json.DataTypeJsonSerde; +import org.apache.fluss.utils.json.JsonSerdeUtils; import org.apache.fluss.utils.types.Tuple2; import io.github.fluss_contrib.rocksdb.Checkpoint; @@ -123,6 +145,7 @@ import java.nio.file.Paths; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -143,6 +166,9 @@ import static org.apache.fluss.server.testutils.KvTestUtils.assertLookupResponse; import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createPartition; import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createTable; +import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newAlterTableRequest; +import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newDropPartitionRequest; +import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newDropTableRequest; import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newLookupRequest; import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newPutKvRequest; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.getAdjustIsrResponseData; @@ -155,7 +181,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -/** Exercises the Coordinator commit against a prepared allocation and real ZooKeeper state. */ +/** Exercises BulkLoad Coordinator RPCs and bucket publication against real ZooKeeper state. */ class BulkLoadBucketCommitTest { @RegisterExtension static final AllCallbackWrapper ZK = @@ -370,6 +396,7 @@ private void start(TableDescriptor descriptor, String partitionName, int replica Configuration conf = new Configuration() .set(ConfigOptions.KV_MAX_RETAINED_SNAPSHOTS, 1) + .set(ConfigOptions.COORDINATOR_BULKLOAD_MAX_TARGETS, 2) .set(ConfigOptions.KV_SNAPSHOT_INTERVAL, Duration.ofHours(1)) .set(ConfigOptions.SERVER_IO_POOL_SIZE, 1); cluster = @@ -392,7 +419,6 @@ private void start(TableDescriptor descriptor, String partitionName, int replica client = cluster.getZooKeeperClient(); Replica replica = cluster.waitAndGetLeaderReplica(bucket); remoteDataDir = replica.getRemoteDataDir(); - seedRunningTarget(replica.getTableInfo()); expectedLeaderEpoch = replica.getLeaderEpoch() + 1; leader = cluster.newTabletServerClientForNode(replica.getLeaderId()); coordinator = cluster.newCoordinatorClient(); @@ -405,7 +431,10 @@ private void start(TableDescriptor descriptor, String partitionName, int replica cluster.getCoordinatorServer() .getCoordinatorEventProcessor() .completedSnapshotStoreManager(); - PbBulkLoadHandle handle = new PbBulkLoadHandle().setTableId(tableId).setBulkLoadId(LOAD_ID); + PbBulkLoadHandle handle = + (partitionName == null ? begin(LOAD_ID) : begin(LOAD_ID, partitionName)) + .getStatus() + .getHandle(); allocateRequest = new AllocateBulkLoadBucketSnapshotRequest().setHandle(handle).setBucketId(0); commitRequest = new CommitBulkLoadBucketSnapshotRequest().setHandle(handle).setBucketId(0); @@ -439,6 +468,221 @@ private void commit() throws Exception { coordinator.commitBulkLoadBucketSnapshot(commitRequest).get(30, TimeUnit.SECONDS); } + private BeginBulkLoadResponse begin(String id, String... partitions) throws Exception { + BeginBulkLoadRequest request = + new BeginBulkLoadRequest() + .setBulkLoadId(id) + .addAllPartitionNames(Arrays.asList(partitions)); + request.setTablePath() + .setDatabaseName(TABLE.getDatabaseName()) + .setTableName(TABLE.getTableName()); + return coordinator.beginBulkLoad(request).get(30, TimeUnit.SECONDS); + } + + private GetBulkLoadInfoResponse info(PbBulkLoadHandle handle) throws Exception { + return coordinator + .getBulkLoadInfo(new GetBulkLoadInfoRequest().setHandle(handle)) + .get(30, TimeUnit.SECONDS); + } + + private List list(String... partitions) throws Exception { + ListInProgressBulkLoadsRequest request = + new ListInProgressBulkLoadsRequest() + .addAllPartitionNames(Arrays.asList(partitions)); + request.setTablePath() + .setDatabaseName(TABLE.getDatabaseName()) + .setTableName(TABLE.getTableName()); + return coordinator + .listInProgressBulkLoads(request) + .get(30, TimeUnit.SECONDS) + .getTransactionsList(); + } + + private PbBulkLoadStatus finish(PbBulkLoadHandle handle) throws Exception { + return coordinator + .commitBulkLoad(new CommitBulkLoadRequest().setHandle(handle)) + .get(30, TimeUnit.SECONDS) + .getStatus(); + } + + private PbBulkLoadStatus abort(PbBulkLoadHandle handle, String message) throws Exception { + return coordinator + .abortBulkLoad( + new AbortBulkLoadRequest().setHandle(handle).setAbortMessage(message)) + .get(30, TimeUnit.SECONDS) + .getStatus(); + } + + @Test + void testAbortKeepsPublishedBucketAndRetentionKeepsItsSuccessorOwner() throws Exception { + start(DATA1_TABLE_DESCRIPTOR_PK.withBucketCount(2), null); + PbBulkLoadHandle handle = allocateRequest.getHandle(); + allocate(); + Tuple2 imported = + uploadCheckpoint(genKvRecords(new Object[] {1, "imported"})); + commit(); + coordinator + .allocateBulkLoadBucketSnapshot(allocateRequest.setBucketId(1)) + .get(30, TimeUnit.SECONDS); + assertThatThrownBy(() -> finish(handle)) + .hasRootCauseInstanceOf(BulkLoadIncompleteException.class); + + PbBulkLoadStatus aborted = abort(handle, "cancelled"); + assertThat(aborted.getState()).isEqualTo(BulkLoadTransaction.ABORTED); + assertThat(aborted.getAbortMessage()).isEqualTo("cancelled"); + PbBulkLoadStatus replayed = abort(handle, "different reason"); + assertThat(replayed.getAbortMessage()).isEqualTo("cancelled"); + assertThat(replayed.getFinishedTime()).isEqualTo(aborted.getFinishedTime()); + PbBulkLoadTargetProgress target = info(handle).getTargetAt(0); + assertThat(target.getAllocatedBucketCount()).isEqualTo(2); + assertThat(target.getCommittedBucketCount()).isEqualTo(1); + assertThatThrownBy(() -> finish(handle)) + .hasRootCauseInstanceOf(BulkLoadStateException.class); + assertThatThrownBy( + () -> + coordinator + .commitBulkLoadBucketSnapshot(commitRequest.setBucketId(1)) + .get(30, TimeUnit.SECONDS)) + .hasRootCauseInstanceOf(BulkLoadStateException.class); + assertThat(list()).isEmpty(); + PbBulkLoadStatus successor = begin("successor").getStatus(); + + CoordinatorEventManager events = + cluster.getCoordinatorServer() + .getCoordinatorEventProcessor() + .getCoordinatorEventManager(); + manager.enqueueMetadataReclamation(aborted.getFinishedTime() - 1, events) + .get(30, TimeUnit.SECONDS); + assertThat(info(handle).getStatus().getState()).isEqualTo(BulkLoadTransaction.ABORTED); + manager.enqueueMetadataReclamation(aborted.getFinishedTime(), events) + .get(30, TimeUnit.SECONDS); + assertThatThrownBy(() -> info(handle)) + .hasRootCauseInstanceOf(BulkLoadNotFoundException.class); + assertThat(list()) + .extracting(status -> status.getHandle().getBulkLoadId()) + .containsExactly("successor"); + assertThatThrownBy(() -> begin("overlapping")) + .hasRootCauseInstanceOf(BulkLoadConflictException.class); + PbBulkLoadStatus abortedSuccessor = abort(successor.getHandle(), "expired successor"); + manager.enqueueMetadataReclamation(abortedSuccessor.getFinishedTime(), events) + .get(30, TimeUnit.SECONDS); + assertThat(client.getStat(BulkLoadTableZNode.path(bucket.getTableId()))).isEmpty(); + assertThat(begin("after-retention").getStatus().getState()) + .isEqualTo(BulkLoadTransaction.RUNNING); + restartTabletServer(); + retry(Duration.ofSeconds(30), () -> assertLookupRow(imported, 2)); + } + + @Test + void testDropTableReclaimsRunningBulkLoad() throws Exception { + start(); + allocate(); + long tableId = bucket.getTableId(); + coordinator + .dropTable( + newDropTableRequest(TABLE.getDatabaseName(), TABLE.getTableName(), false)) + .get(30, TimeUnit.SECONDS); + retry( + Duration.ofSeconds(15), + () -> assertThat(client.getStat(BulkLoadTableZNode.path(tableId))).isEmpty()); + } + + @Test + void testPartitionOwnershipAndHistoricalBuildContext() throws Exception { + start(partitionedDescriptor(), "p1"); + PbBulkLoadHandle handle = allocateRequest.getHandle(); + BeginBulkLoadResponse first = begin(LOAD_ID, "p1"); + long originalPartitionId = bucket.getPartitionId(); + + AlterTableRequest rescale = + newAlterTableRequest( + TABLE, + Collections.emptyMap(), + Collections.emptyList(), + Collections.emptyList(), + false); + rescale.setModifyBucketCount().setNewBucketCount(2); + coordinator.alterTable(rescale).get(30, TimeUnit.SECONDS); + createPartition(cluster, TABLE, partitionSpec("p2"), false); + + PbAddColumn column = + new PbAddColumn() + .setColumnName("new_column") + .setDataTypeJson( + JsonSerdeUtils.writeValueAsBytes( + DataTypes.STRING(), DataTypeJsonSerde.INSTANCE)) + .setColumnPositionType(0); + coordinator + .alterTable( + newAlterTableRequest( + TABLE, + Collections.emptyMap(), + Collections.emptyList(), + Collections.singletonList(column), + false)) + .get(30, TimeUnit.SECONDS); + coordinator + .dropPartition(newDropPartitionRequest(TABLE, partitionSpec("p1"), false)) + .get(30, TimeUnit.SECONDS); + createPartition(cluster, TABLE, partitionSpec("p1"), false); + PartitionRegistration replacement = client.getPartition(TABLE, "p1").get(); + assertThat(replacement.getPartitionId()).isNotEqualTo(originalPartitionId); + assertThat(list("p1")).isEmpty(); + PbBulkLoadTargetProgress withdrawn = info(handle).getTargetAt(0); + assertThat(withdrawn.isWithdrawn()).isTrue(); + assertThat(withdrawn.getPartitionId()).isEqualTo(originalPartitionId); + BulkLoadTransaction transaction = + client.getBulkLoadTransaction(handle.getTableId(), handle.getBulkLoadId()) + .get() + .data(); + assertThat( + client.getBulkLoadTarget(transaction, originalPartitionId) + .get() + .data() + .withdrawn) + .isFalse(); + assertThatThrownBy(this::allocate) + .hasRootCauseInstanceOf(BulkLoadTargetWithdrawnException.class); + + BeginBulkLoadResponse replay = begin(LOAD_ID, "p1"); + assertThat(replay.getTableInfo().getSchemaId()) + .isEqualTo(first.getTableInfo().getSchemaId()); + assertThat(TableDescriptor.fromJsonBytes(replay.getTableInfo().getTableJson()).getSchema()) + .isEqualTo(partitionedDescriptor().getSchema()); + PbBulkLoadTargetInfo originalTarget = replay.getTargetAt(0); + assertThat(originalTarget.getPartitionId()).isEqualTo(originalPartitionId); + assertThat(originalTarget.getBucketCount()).isEqualTo(1); + assertThat(originalTarget.getRemoteDataDir()) + .isEqualTo(first.getTargetAt(0).getRemoteDataDir()); + BeginBulkLoadResponse next = begin("replacement", "p1"); + assertThat(next.getTargetAt(0).getPartitionId()).isEqualTo(replacement.getPartitionId()); + assertThat(next.getTargetAt(0).getRemoteDataDir()) + .isEqualTo(replacement.getRemoteDataDir()); + assertThat(next.getTableInfo().getSchemaId()) + .isGreaterThan(first.getTableInfo().getSchemaId()); + assertThat(next.getTargetAt(0).getBucketCount()).isEqualTo(2); + assertThat(finish(handle).getState()).isEqualTo(BulkLoadTransaction.COMMITTED); + assertThat(info(handle).getTargetAt(0).isWithdrawn()).isTrue(); + + // p2 precedes the conflicting replacement p1 in physical target order. + assertThat(client.getPartition(TABLE, "p2").get().getPartitionId()) + .isLessThan(replacement.getPartitionId()); + assertThatThrownBy(() -> begin("overlap", "p2", "p1")) + .hasRootCauseInstanceOf(BulkLoadConflictException.class); + assertThat(client.getBulkLoadTransaction(bucket.getTableId(), "overlap")).isEmpty(); + createPartition(cluster, TABLE, partitionSpec("p3"), false); + assertThatThrownBy(() -> begin("too-many-targets", "p1", "p2", "p3")) + .hasRootCauseInstanceOf(InvalidRequestException.class); + begin("second", "p2", "p3"); + assertThat(list("p1", "p2", "p3")) + .extracting(status -> status.getHandle().getBulkLoadId()) + .containsExactlyInAnyOrder("replacement", "second"); + } + + private static PartitionSpec partitionSpec(String name) { + return new PartitionSpec(Collections.singletonMap("pt", name)); + } + private Tuple2 uploadCheckpoint(List rows) throws Exception { List> values = getKeyValuePairs(rows); FsPath dir = snapshotDirectory(snapshotId); @@ -686,6 +930,19 @@ void testUnconfirmedPublicationIsolatesBucketAndRecoversWithoutRetry(boolean per assertThat(client.getLeaderAndIsr(bucket).get().leaderEpoch()).isEqualTo(expected); // Both the inline check and a background check failed before connectivity returned. assertThat(failedChecks.await(30, TimeUnit.SECONDS)).isTrue(); + if (persisted) { + long tableId = bucket.getTableId(); + CompletableFuture response = new CompletableFuture<>(); + AbortBulkLoadEvent abort = + new AbortBulkLoadEvent(tableId, LOAD_ID, "cancelled", response); + publicationProcessor.getCoordinatorEventManager().put(abort); + long finishedTime = + response.get(30, TimeUnit.SECONDS).getStatus().getFinishedTime(); + manager.enqueueMetadataReclamation( + finishedTime, publicationProcessor.getCoordinatorEventManager()) + .get(30, TimeUnit.SECONDS); + assertThat(client.getBulkLoadTransaction(tableId, LOAD_ID)).isPresent(); + } verificationAvailable.set(true); retry( Duration.ofSeconds(30), @@ -825,20 +1082,9 @@ private T accessPublicationContext(Function action) @Test void testPartitionRecoveryReplaysWalAndPreservesSuccessorOnRetry() throws Exception { - Schema schema = - Schema.newBuilder() - .column("a", DataTypes.INT()) - .column("b", DataTypes.STRING()) - .column("pt", DataTypes.STRING()) - .primaryKey("a", "pt") - .build(); - start( - TableDescriptor.builder() - .schema(schema) - .distributedBy(1, "a") - .partitionedBy("pt") - .build(), - "p1"); + TableDescriptor descriptor = partitionedDescriptor(); + Schema schema = descriptor.getSchema(); + start(descriptor, "p1"); putRows(genKvRecords(schema.getRowType(), new Object[] {0, "base", "p1"})); long recoveryOffset = cluster.triggerAndWaitSnapshot(bucket).getLogOffset(); List beforeAllocation = @@ -855,10 +1101,16 @@ void testPartitionRecoveryReplaysWalAndPreservesSuccessorOnRetry() throws Except Tuple2 appended = getKeyValuePairs(tail).get(0); FsPath dir = snapshotDirectory(snapshotId); commit(); + PbBulkLoadHandle handle = commitRequest.getHandle(); + PbBulkLoadStatus committed = finish(handle); + assertThat(committed.getState()).isEqualTo(BulkLoadTransaction.COMMITTED); retry(Duration.ofSeconds(30), () -> assertLookupRow(imported)); int successorEpoch = client.getLeaderAndIsr(bucket).get().leaderEpoch(); CompletedSnapshot next = cluster.triggerAndWaitSnapshot(bucket); awaitDeletion(dir); + assertThat(finish(handle).getFinishedTime()).isEqualTo(committed.getFinishedTime()); + assertThat(begin(LOAD_ID, "p1").getStatus().getState()) + .isEqualTo(BulkLoadTransaction.COMMITTED); commit(); AllocateBulkLoadBucketSnapshotResponse replay = coordinator @@ -875,6 +1127,20 @@ void testPartitionRecoveryReplaysWalAndPreservesSuccessorOnRetry() throws Except assertLookupRow(appended); } + private static TableDescriptor partitionedDescriptor() { + return TableDescriptor.builder() + .schema( + Schema.newBuilder() + .column("a", DataTypes.INT()) + .column("b", DataTypes.STRING()) + .column("pt", DataTypes.STRING()) + .primaryKey("a", "pt") + .build()) + .distributedBy(1, "a") + .partitionedBy("pt") + .build(); + } + private static void awaitDeletion(FsPath path) { retry(Duration.ofSeconds(30), () -> assertThat(Paths.get(path.toUri())).doesNotExist()); } @@ -1002,8 +1268,13 @@ private void putRows(List rows) throws Exception { } private void assertLookupRow(Tuple2 row) throws Exception { + assertLookupRow(row, 1); + } + + private void assertLookupRow(Tuple2 row, int routingBucketCount) + throws Exception { LookupRequest request = newLookupRequest(bucket.getTableId(), bucket.getBucket(), row.f0); - request.getBucketsReqAt(0).setRoutingBucketCount(1); + request.getBucketsReqAt(0).setRoutingBucketCount(routingBucketCount); if (bucket.getPartitionId() != null) { request.getBucketsReqAt(0).setPartitionId(bucket.getPartitionId()); } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorContextTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorContextTest.java index 09618fcbf75..74ae782f183 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorContextTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/CoordinatorContextTest.java @@ -96,6 +96,23 @@ void testRemovePartitionClearsPartitionInfo() { assertThat(context.getPartitionInfoById(100L)).isNull(); } + @Test + void testRemovingOldObjectsPreservesReplacementPaths() { + CoordinatorContext context = new CoordinatorContext(ZkEpoch.INITIAL_EPOCH); + TablePath table = TablePath.of("db1", "table1"); + PhysicalTablePath partition = PhysicalTablePath.of(table, "2026"); + context.putTablePath(1L, table); + context.putPartition(100L, partition, createPartitionInfo(100L, "2026")); + context.putTablePath(2L, table); + context.putPartition(101L, partition, createPartitionInfo(101L, "2026")); + + context.removePartition(new TablePartition(1L, 100L)); + context.removeTable(1L); + + assertThat(context.getTableIdByPath(table)).isEqualTo(2L); + assertThat(context.getPartitionId(partition)).contains(101L); + } + @Test void testResetContextClearsPartitionInfo() { CoordinatorContext context = new CoordinatorContext(ZkEpoch.INITIAL_EPOCH); diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/TestCoordinatorGateway.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/TestCoordinatorGateway.java index 69f6e2fe01b..e830c77f92e 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/TestCoordinatorGateway.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/TestCoordinatorGateway.java @@ -22,6 +22,8 @@ import org.apache.fluss.exception.NetworkException; import org.apache.fluss.metadata.TableBucket; import org.apache.fluss.rpc.gateway.CoordinatorGateway; +import org.apache.fluss.rpc.messages.AbortBulkLoadRequest; +import org.apache.fluss.rpc.messages.AbortBulkLoadResponse; import org.apache.fluss.rpc.messages.AcquireKvSnapshotLeaseRequest; import org.apache.fluss.rpc.messages.AcquireKvSnapshotLeaseResponse; import org.apache.fluss.rpc.messages.AddServerTagByRackRequest; @@ -40,10 +42,14 @@ import org.apache.fluss.rpc.messages.AlterTableResponse; import org.apache.fluss.rpc.messages.ApiVersionsRequest; import org.apache.fluss.rpc.messages.ApiVersionsResponse; +import org.apache.fluss.rpc.messages.BeginBulkLoadRequest; +import org.apache.fluss.rpc.messages.BeginBulkLoadResponse; import org.apache.fluss.rpc.messages.CancelRebalanceRequest; import org.apache.fluss.rpc.messages.CancelRebalanceResponse; import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotRequest; import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotResponse; +import org.apache.fluss.rpc.messages.CommitBulkLoadRequest; +import org.apache.fluss.rpc.messages.CommitBulkLoadResponse; import org.apache.fluss.rpc.messages.CommitKvSnapshotRequest; import org.apache.fluss.rpc.messages.CommitKvSnapshotResponse; import org.apache.fluss.rpc.messages.CommitLakeTableSnapshotRequest; @@ -82,6 +88,8 @@ import org.apache.fluss.rpc.messages.DropPartitionResponse; import org.apache.fluss.rpc.messages.DropTableRequest; import org.apache.fluss.rpc.messages.DropTableResponse; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoRequest; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoResponse; import org.apache.fluss.rpc.messages.GetClusterHealthRequest; import org.apache.fluss.rpc.messages.GetClusterHealthResponse; import org.apache.fluss.rpc.messages.GetDatabaseInfoRequest; @@ -106,6 +114,8 @@ import org.apache.fluss.rpc.messages.ListAclsResponse; import org.apache.fluss.rpc.messages.ListDatabasesRequest; import org.apache.fluss.rpc.messages.ListDatabasesResponse; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsRequest; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsResponse; import org.apache.fluss.rpc.messages.ListKvSnapshotsRequest; import org.apache.fluss.rpc.messages.ListKvSnapshotsResponse; import org.apache.fluss.rpc.messages.ListPartitionInfosRequest; @@ -570,4 +580,31 @@ public CompletableFuture commitBulkLoadBuc CommitBulkLoadBucketSnapshotRequest request) { throw new UnsupportedOperationException(); } + + @Override + public CompletableFuture beginBulkLoad(BeginBulkLoadRequest request) { + throw new UnsupportedOperationException(); + } + + @Override + public CompletableFuture commitBulkLoad(CommitBulkLoadRequest request) { + throw new UnsupportedOperationException(); + } + + @Override + public CompletableFuture abortBulkLoad(AbortBulkLoadRequest request) { + throw new UnsupportedOperationException(); + } + + @Override + public CompletableFuture getBulkLoadInfo( + GetBulkLoadInfoRequest request) { + throw new UnsupportedOperationException(); + } + + @Override + public CompletableFuture listInProgressBulkLoads( + ListInProgressBulkLoadsRequest request) { + throw new UnsupportedOperationException(); + } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadAuthorizationITCase.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadAuthorizationITCase.java new file mode 100644 index 00000000000..386d0cdef0c --- /dev/null +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadAuthorizationITCase.java @@ -0,0 +1,152 @@ +/* + * 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.bulkload; + +import org.apache.fluss.config.ConfigOptions; +import org.apache.fluss.config.Configuration; +import org.apache.fluss.exception.AuthorizationException; +import org.apache.fluss.exception.UnknownTableOrBucketException; +import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.metadata.TablePath; +import org.apache.fluss.rpc.gateway.CoordinatorGateway; +import org.apache.fluss.rpc.messages.AbortBulkLoadRequest; +import org.apache.fluss.rpc.messages.AllocateBulkLoadBucketSnapshotRequest; +import org.apache.fluss.rpc.messages.BeginBulkLoadRequest; +import org.apache.fluss.rpc.messages.CommitBulkLoadBucketSnapshotRequest; +import org.apache.fluss.rpc.messages.CommitBulkLoadRequest; +import org.apache.fluss.rpc.messages.CreateAclsRequest; +import org.apache.fluss.rpc.messages.GetBulkLoadInfoRequest; +import org.apache.fluss.rpc.messages.ListInProgressBulkLoadsRequest; +import org.apache.fluss.rpc.messages.PbBulkLoadHandle; +import org.apache.fluss.security.acl.AccessControlEntry; +import org.apache.fluss.security.acl.AclBinding; +import org.apache.fluss.security.acl.FlussPrincipal; +import org.apache.fluss.security.acl.OperationType; +import org.apache.fluss.security.acl.PermissionType; +import org.apache.fluss.security.acl.Resource; +import org.apache.fluss.server.testutils.FlussClusterExtension; +import org.apache.fluss.server.zk.data.bulkload.BulkLoadTransaction; + +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.util.Collections; +import java.util.List; + +import static org.apache.fluss.record.TestData.DATA1_TABLE_DESCRIPTOR_PK; +import static org.apache.fluss.rpc.util.CommonRpcMessageUtils.toPbAclInfos; +import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createTable; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Verifies table permissions for BulkLoad RPCs. */ +class BulkLoadAuthorizationITCase { + private static final TablePath PATH = TablePath.of("bulkload_auth", "orders"); + + @RegisterExtension + static final FlussClusterExtension CLUSTER = + FlussClusterExtension.builder() + .setCoordinatorServerListeners("FLUSS://localhost:0, CLIENT://localhost:0") + .setTabletServerListeners("FLUSS://localhost:0, CLIENT://localhost:0") + .setClusterConf(new Configuration().set(ConfigOptions.AUTHORIZER_ENABLED, true)) + .build(); + + @Test + void testDescribeAndWritePermissions() throws Exception { + long tableId = createTable(CLUSTER, PATH, DATA1_TABLE_DESCRIPTOR_PK.withBucketCount(1)); + CLUSTER.waitAndGetLeaderReplica(new TableBucket(tableId, 0)); + CoordinatorGateway internal = CLUSTER.newCoordinatorClient(); + CoordinatorGateway external = CLUSTER.newCoordinatorClient("CLIENT"); + PbBulkLoadHandle handle = + internal.beginBulkLoad(begin("internal-load")).get().getStatus().getHandle(); + GetBulkLoadInfoRequest info = new GetBulkLoadInfoRequest().setHandle(handle); + ListInProgressBulkLoadsRequest list = new ListInProgressBulkLoadsRequest(); + list.setTablePath() + .setDatabaseName(PATH.getDatabaseName()) + .setTableName(PATH.getTableName()); + AbortBulkLoadRequest abort = new AbortBulkLoadRequest().setHandle(handle); + assertDenied(() -> external.getBulkLoadInfo(info).get()); + assertDenied(() -> external.listInProgressBulkLoads(list).get()); + + grant(internal, OperationType.DESCRIBE); + assertThat(external.getBulkLoadInfo(info).get().getStatus().getState()) + .isEqualTo(BulkLoadTransaction.RUNNING); + assertThat(external.listInProgressBulkLoads(list).get().getTransactionsCount()) + .isEqualTo(1); + assertDenied(() -> external.beginBulkLoad(begin("external-load")).get()); + assertDenied( + () -> + external.allocateBulkLoadBucketSnapshot( + new AllocateBulkLoadBucketSnapshotRequest() + .setHandle(handle) + .setBucketId(0)) + .get()); + assertDenied( + () -> + external.commitBulkLoadBucketSnapshot( + new CommitBulkLoadBucketSnapshotRequest() + .setHandle(handle) + .setBucketId(0)) + .get()); + assertDenied( + () -> external.commitBulkLoad(new CommitBulkLoadRequest().setHandle(handle)).get()); + assertDenied(() -> external.abortBulkLoad(abort).get()); + + grant(internal, OperationType.WRITE); + assertThat(external.abortBulkLoad(abort).get().getStatus().getState()) + .isEqualTo(BulkLoadTransaction.ABORTED); + + PbBulkLoadHandle unknownTableHandle = + new PbBulkLoadHandle().setTableId(Long.MAX_VALUE).setBulkLoadId("internal-load"); + assertThatThrownBy( + () -> + external.getBulkLoadInfo( + new GetBulkLoadInfoRequest() + .setHandle(unknownTableHandle)) + .get()) + .hasRootCauseInstanceOf(UnknownTableOrBucketException.class); + } + + private static void assertDenied(ThrowingCallable call) { + assertThatThrownBy(call).rootCause().isInstanceOf(AuthorizationException.class); + } + + private static void grant(CoordinatorGateway coordinator, OperationType operation) + throws Exception { + List bindings = + Collections.singletonList( + new AclBinding( + Resource.table(PATH), + new AccessControlEntry( + FlussPrincipal.ANONYMOUS, + "*", + operation, + PermissionType.ALLOW))); + coordinator.createAcls(new CreateAclsRequest().addAllAcls(toPbAclInfos(bindings))).get(); + CLUSTER.waitUntilAuthenticationSync(bindings, true); + } + + private static BeginBulkLoadRequest begin(String id) { + BeginBulkLoadRequest request = new BeginBulkLoadRequest().setBulkLoadId(id); + request.setTablePath() + .setDatabaseName(PATH.getDatabaseName()) + .setTableName(PATH.getTableName()); + return request; + } +} diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java index 23611f4a0d1..a4d63e9cae5 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java @@ -19,12 +19,14 @@ import org.apache.fluss.cluster.Endpoint; import org.apache.fluss.cluster.ServerType; +import org.apache.fluss.exception.NotCoordinatorLeaderException; import org.apache.fluss.metrics.Gauge; import org.apache.fluss.metrics.Histogram; import org.apache.fluss.metrics.Metric; import org.apache.fluss.metrics.MetricNames; import org.apache.fluss.metrics.groups.AbstractMetricGroup; import org.apache.fluss.metrics.registry.NOPMetricRegistry; +import org.apache.fluss.rpc.messages.CommitBulkLoadResponse; import org.apache.fluss.server.coordinator.CoordinatorContext; import org.apache.fluss.server.metadata.ServerInfo; import org.apache.fluss.server.metrics.group.CoordinatorMetricGroup; @@ -37,12 +39,14 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.fluss.testutils.common.CommonTestUtils.retry; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test for {@link CoordinatorEventManager}. */ class CoordinatorEventManagerTest { @@ -223,6 +227,30 @@ void testCloseUnregistersMetrics() { } } + @Test + void testBulkLoadLifecycleEventsFailWhenCoordinatorStops() { + TestingMetricRegistry registry = new TestingMetricRegistry(); + CoordinatorMetricGroup metricGroup = + new CoordinatorMetricGroup(registry, "cluster1", "host", "0"); + CoordinatorEventManager manager = new CoordinatorEventManager(event -> {}, metricGroup); + + try { + CompletableFuture response = new CompletableFuture<>(); + manager.put(new CommitBulkLoadEvent(1, "load", response)); + manager.close(); + assertThatThrownBy(() -> response.get(10, TimeUnit.SECONDS)) + .hasRootCauseInstanceOf(NotCoordinatorLeaderException.class); + + CompletableFuture lateResponse = new CompletableFuture<>(); + manager.put(new CommitBulkLoadEvent(1, "load", lateResponse)); + assertThatThrownBy(() -> lateResponse.get(10, TimeUnit.SECONDS)) + .hasRootCauseInstanceOf(NotCoordinatorLeaderException.class); + } finally { + manager.close(); + metricGroup.close(); + } + } + private static void processAccessContext( AccessContextEvent event, CoordinatorContext context) { try { diff --git a/website/docs/maintenance/configuration.md b/website/docs/maintenance/configuration.md index eeeb4e13c47..3b50c206738 100644 --- a/website/docs/maintenance/configuration.md +++ b/website/docs/maintenance/configuration.md @@ -79,6 +79,8 @@ The logging-related environment options (`env.log.dir`, `env.log.level`, `env.lo | coordinator.io-pool.size | Integer | 10 | **Deprecated**: This option is deprecated. Please use `server.io-pool.size` instead. The size of the IO thread pool to run blocking operations for coordinator server. This includes discard unnecessary snapshot files. Increase this value if you experience slow unnecessary snapshot files clean. The default value is 10. | | coordinator.producer-offsets.ttl | Duration | 24h | The TTL (time-to-live) for producer offsets. Producer offsets older than this TTL will be automatically cleaned up by the coordinator server. Producer offsets are used for undo recovery when a Flink job fails over before completing its first checkpoint. The default value is 24 hours. | | coordinator.producer-offsets.cleanup-interval | Duration | 1h | The interval for cleaning up expired producer offsets and orphan files in remote storage. The cleanup task runs periodically to remove expired offsets and any orphan files that may have been left behind due to incomplete operations. The default value is 1 hour. | +| coordinator.bulkload.max-targets | Integer | 1000 | Maximum number of physical targets selected by one BulkLoad transaction. | +| coordinator.bulkload.result-retention | Duration | 7d | Minimum retention of a completed or aborted BulkLoad result while the original table exists. | | coordinator.control-request.retry-backoff | Duration | 100ms | The backoff duration the coordinator waits before retrying a control-plane request to a tablet server after a transient RPC-layer failure. | | coordinator.control-request.timeout | Duration | 30s | The timeout the sender thread waits for a response to a control-plane request before treating it as failed and retrying. | | coordinator.lifecycle-throttler.inflight-timeout | Duration | 3min | The timeout for an in-flight drop event in the coordinator's TableLifecycleThrottler. If a drop event has been admitted but the corresponding completion callback has not arrived within this timeout, the throttler abandons tracking of that drop and continues admitting the next pending drop. | From 997256b1159fa0c6ad304583f63894151be40171 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E9=B5=BA?= Date: Thu, 26 Nov 2026 17:06:06 +0800 Subject: [PATCH 2/5] [server] Address BulkLoad lifecycle review feedback --- fluss-rpc/src/main/proto/FlussApi.proto | 1 + .../coordinator/bulkload/BulkLoadManager.java | 42 ++++++++++--------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/fluss-rpc/src/main/proto/FlussApi.proto b/fluss-rpc/src/main/proto/FlussApi.proto index b712509a209..bbf2cce3cbc 100644 --- a/fluss-rpc/src/main/proto/FlussApi.proto +++ b/fluss-rpc/src/main/proto/FlussApi.proto @@ -983,6 +983,7 @@ message PbBulkLoadHandle { message PbBulkLoadStatus { required PbBulkLoadHandle handle = 1; + // 0 = RUNNING, 1 = COMMITTED, 2 = ABORTED. required int32 state = 2; required int64 created_time = 3; optional int64 finished_time = 4; diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java index 248e2846116..0d2174fd07b 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java @@ -111,18 +111,18 @@ public BulkLoadManager( public BeginBulkLoadResponse begin( TableInfo table, @Nullable String bulkLoadId, - List names, + List partitionNames, int maxTargets, Function resolvePartitionTarget) throws Exception { - requireDistinctPartitions(names); + requireDistinctPartitions(partitionNames); String id = bulkLoadId == null ? UUID.randomUUID().toString() : bulkLoadId; long tableId = table.getTableId(); if (bulkLoadId != null) { Optional> previous = zooKeeperClient.getBulkLoadTransaction(tableId, id); if (previous.isPresent()) { - return replayBegin(previous.get().data(), names, table); + return replayBegin(previous.get().data(), partitionNames, table); } } @@ -136,17 +136,18 @@ public BeginBulkLoadResponse begin( throw new InvalidRequestException( "BulkLoad does not support tables with a merge engine."); } - if (table.isPartitioned() == names.isEmpty()) { + if (table.isPartitioned() == partitionNames.isEmpty()) { throw new InvalidRequestException("Invalid partition selection for this table."); } - if (Math.max(1, names.size()) > maxTargets) { + if (Math.max(1, partitionNames.size()) > maxTargets) { throw new InvalidRequestException("BulkLoad exceeds max-targets."); } - if (names.contains(HISTORICAL_PARTITION_VALUE)) { + if (partitionNames.contains(HISTORICAL_PARTITION_VALUE)) { throw new InvalidRequestException("Historical partitions are unsupported."); } - List targets = resolveBeginTargets(table, names, resolvePartitionTarget); + List targets = + resolveBeginTargets(table, partitionNames, resolvePartitionTarget); BulkLoadTransaction transaction = new BulkLoadTransaction( tableId, @@ -166,7 +167,7 @@ public BeginBulkLoadResponse begin( zooKeeperClient.getBulkLoadTransaction(tableId, id); if (current.isPresent()) { BulkLoadTransaction existing = current.get().data(); - return replayBegin(existing, names, table); + return replayBegin(existing, partitionNames, table); } throw e; } @@ -214,8 +215,8 @@ public GetBulkLoadInfoResponse getBulkLoadInfo(long tableId, String bulkLoadId) /** Lists the running transactions owning any of the selected current physical targets. */ public ListInProgressBulkLoadsResponse listInProgressBulkLoads( - TablePath path, List names) throws Exception { - requireDistinctPartitions(names); + TablePath path, List partitionNames) throws Exception { + requireDistinctPartitions(partitionNames); TableRegistration table = zooKeeperClient .getTable(path) @@ -223,21 +224,21 @@ public ListInProgressBulkLoadsResponse listInProgressBulkLoads( () -> new TableNotExistException( "Table " + path + " does not exist.")); - if (!table.isPartitioned() && !names.isEmpty()) { + if (!table.isPartitioned() && !partitionNames.isEmpty()) { throw new InvalidRequestException("Non-partitioned target has partition names."); } List ids = new ArrayList<>(); if (table.isPartitioned()) { Collection selected = - names.isEmpty() ? zooKeeperClient.getPartitions(path) : names; + partitionNames.isEmpty() ? zooKeeperClient.getPartitions(path) : partitionNames; Map registrations = zooKeeperClient.getPartitionRegistrations(path, selected); for (String name : selected) { PartitionRegistration partition = registrations.get(name); if (partition != null && partition.getTableId() == table.tableId) { ids.add(partition.getPartitionId()); - } else if (!names.isEmpty()) { + } else if (!partitionNames.isEmpty()) { throw partitionNotFound(name); } } @@ -316,7 +317,7 @@ public void startMetadataReclamation( scheduleMetadataReclamation( eventManager, retentionMillis, sweepRunning), 0, - Duration.ofMinutes(1).toMillis()); + Duration.ofHours(1).toMillis()); } /** Cancels the periodic trigger before the Coordinator event queue closes. */ @@ -529,7 +530,8 @@ private Map getCurrentPartitions( } private BeginBulkLoadResponse replayBegin( - BulkLoadTransaction transaction, List names, TableInfo table) throws Exception { + BulkLoadTransaction transaction, List partitionNames, TableInfo table) + throws Exception { List targets = transactionStore.getTargets(transaction, table.isPartitioned()); Set original = new HashSet<>(); @@ -538,7 +540,7 @@ private BeginBulkLoadResponse replayBegin( original.add(target.partitionName); } } - if (!original.equals(new HashSet<>(names))) { + if (!original.equals(new HashSet<>(partitionNames))) { throw new InvalidRequestException("bulk_load_id has different targets."); } TableDescriptor descriptor = table.toTableDescriptor(); @@ -560,7 +562,7 @@ private BeginBulkLoadResponse replayBegin( private static List resolveBeginTargets( TableInfo table, - List names, + List partitionNames, Function resolvePartitionTarget) { if (!table.isPartitioned()) { return Collections.singletonList( @@ -568,7 +570,7 @@ private static List resolveBeginTargets( null, null, table.getNumBuckets(), table.getRemoteDataDir(), false)); } List targets = new ArrayList<>(); - for (String name : names) { + for (String name : partitionNames) { BulkLoadTarget target = resolvePartitionTarget.apply(name); if (target == null) { throw partitionNotFound(name); @@ -621,8 +623,8 @@ private static PbBulkLoadStatus status(BulkLoadTransaction transaction) { return status; } - private static void requireDistinctPartitions(List names) { - if (new HashSet<>(names).size() != names.size()) { + private static void requireDistinctPartitions(List partitionNames) { + if (new HashSet<>(partitionNames).size() != partitionNames.size()) { throw new InvalidRequestException("Duplicate partition names."); } } From 9967d36aac9ba0906ab789e57a11dc37e8e0aa2c Mon Sep 17 00:00:00 2001 From: Jark Wu Date: Fri, 27 Nov 2026 01:04:21 +0800 Subject: [PATCH 3/5] [rust] Sync generated BulkLoad state documentation Generated-by: OpenAI Codex AI-Contributed/Feature: 0/1 AI-Contributed/UT: 0/0 (cherry picked from commit 265bbd0fe11027d39d0c4b5574f8b1c1f29c0199) --- fluss-rust/crates/fluss/src/proto/fluss.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/fluss-rust/crates/fluss/src/proto/fluss.rs b/fluss-rust/crates/fluss/src/proto/fluss.rs index cf8d3faa2ac..7586fb66390 100644 --- a/fluss-rust/crates/fluss/src/proto/fluss.rs +++ b/fluss-rust/crates/fluss/src/proto/fluss.rs @@ -1280,6 +1280,7 @@ pub struct PbBulkLoadHandle { pub struct PbBulkLoadStatus { #[prost(message, required, tag = "1")] pub handle: PbBulkLoadHandle, + /// 0 = RUNNING, 1 = COMMITTED, 2 = ABORTED. #[prost(int32, required, tag = "2")] pub state: i32, #[prost(int64, required, tag = "3")] From 25345c80b99492e49930f522ab99d6786831f225 Mon Sep 17 00:00:00 2001 From: Jark Wu Date: Fri, 27 Nov 2026 01:08:42 +0800 Subject: [PATCH 4/5] docs: Clarify BulkLoad transaction target description in configuration Co-Authored-By: Codex AI-Contributed/Feature: 6/6 AI-Contributed/UT: 0/0 --- .../src/main/java/org/apache/fluss/config/ConfigOptions.java | 4 +++- website/docs/maintenance/configuration.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java index 44b4b6f8105..32fbca6996f 100644 --- a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java +++ b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java @@ -217,7 +217,9 @@ public class ConfigOptions { .intType() .defaultValue(1000) .withDescription( - "Maximum physical targets selected by one BulkLoad transaction."); + "Maximum number of targets in one bulk load transaction. A bulk load target is" + + " an entire non-partitioned table or one selected partition of a partitioned table," + + " regardless of how many buckets it contains."); public static final ConfigOption COORDINATOR_BULKLOAD_RESULT_RETENTION = key("coordinator.bulkload.result-retention") diff --git a/website/docs/maintenance/configuration.md b/website/docs/maintenance/configuration.md index 3b50c206738..d50dbcea1c6 100644 --- a/website/docs/maintenance/configuration.md +++ b/website/docs/maintenance/configuration.md @@ -79,7 +79,7 @@ The logging-related environment options (`env.log.dir`, `env.log.level`, `env.lo | coordinator.io-pool.size | Integer | 10 | **Deprecated**: This option is deprecated. Please use `server.io-pool.size` instead. The size of the IO thread pool to run blocking operations for coordinator server. This includes discard unnecessary snapshot files. Increase this value if you experience slow unnecessary snapshot files clean. The default value is 10. | | coordinator.producer-offsets.ttl | Duration | 24h | The TTL (time-to-live) for producer offsets. Producer offsets older than this TTL will be automatically cleaned up by the coordinator server. Producer offsets are used for undo recovery when a Flink job fails over before completing its first checkpoint. The default value is 24 hours. | | coordinator.producer-offsets.cleanup-interval | Duration | 1h | The interval for cleaning up expired producer offsets and orphan files in remote storage. The cleanup task runs periodically to remove expired offsets and any orphan files that may have been left behind due to incomplete operations. The default value is 1 hour. | -| coordinator.bulkload.max-targets | Integer | 1000 | Maximum number of physical targets selected by one BulkLoad transaction. | +| coordinator.bulkload.max-targets | Integer | 1000 | Maximum number of targets in one bulk load transaction. A bulk load target is an entire non-partitioned table or one selected partition of a partitioned table, regardless of how many buckets it contains. | | coordinator.bulkload.result-retention | Duration | 7d | Minimum retention of a completed or aborted BulkLoad result while the original table exists. | | coordinator.control-request.retry-backoff | Duration | 100ms | The backoff duration the coordinator waits before retrying a control-plane request to a tablet server after a transient RPC-layer failure. | | coordinator.control-request.timeout | Duration | 30s | The timeout the sender thread waits for a response to a control-plane request before treating it as failed and retrying. | From 149fc708ff55257d972a0bb0808e8858126f5e13 Mon Sep 17 00:00:00 2001 From: Jark Wu Date: Fri, 27 Nov 2026 01:15:24 +0800 Subject: [PATCH 5/5] refactor: Update BulkLoad event classes to use getResultFuture for result handling Co-Authored-By: Codex AI-Contributed/Feature: 37/167 AI-Contributed/UT: 20/20 --- .../CoordinatorEventProcessor.java | 36 ++++++++++-------- .../coordinator/bulkload/BulkLoadManager.java | 7 ++-- .../coordinator/event/AbortBulkLoadEvent.java | 13 +++++-- .../coordinator/event/BeginBulkLoadEvent.java | 13 +++++-- .../event/CommitBulkLoadBucketEvent.java | 9 ++++- .../event/CommitBulkLoadEvent.java | 16 ++++++-- .../event/CoordinatorEventManager.java | 37 ++++++------------- .../event/CoordinatorEventWithResult.java | 27 ++++++++++++++ .../ReclaimTableBulkLoadMetadataEvent.java | 9 ++++- .../event/CoordinatorEventManagerTest.java | 20 ++++++++++ 10 files changed, 126 insertions(+), 61 deletions(-) create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventWithResult.java 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 284054159e8..cc8bbf17c6a 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 @@ -407,9 +407,9 @@ private void processReclaimTableBulkLoadMetadata(ReclaimTableBulkLoadMetadataEve event.retentionCutoff, getActiveBulkLoadTable(event.tableId) == null, coordinatorContext.hasPendingBulkLoadPublication(event.tableId)); - event.result.complete(null); + event.getResultFuture().complete(null); } catch (Exception e) { - event.result.completeExceptionally(e); + event.getResultFuture().completeExceptionally(e); } } @@ -449,28 +449,29 @@ private void processCommitBulkLoadBucket(CommitBulkLoadBucketEvent event) { throw unconfirmed; } if (!published.isPresent()) { - event.result.complete(null); + event.getResultFuture().complete(null); return; } coordinatorContext.putBucketLeaderAndIsr(bucket, published.get()); notifyOnlineReplicas(bucket); } catch (Throwable failure) { - event.result.completeExceptionally(failure); + event.getResultFuture().completeExceptionally(failure); return; } try { event.snapshotStore.registerImportedSnapshot(snapshot); - event.result.complete(null); + event.getResultFuture().complete(null); } catch (Exception failure) { - event.result.completeExceptionally( - new UnknownServerException( - "BulkLoad snapshot " - + snapshot.getSnapshotID() - + " for " - + bucket - + " was committed, but local registration failed.", - failure)); + event.getResultFuture() + .completeExceptionally( + new UnknownServerException( + "BulkLoad snapshot " + + snapshot.getSnapshotID() + + " for " + + bucket + + " was committed, but local registration failed.", + failure)); } } @@ -1022,15 +1023,18 @@ public void process(CoordinatorEvent event) { if (event instanceof BeginBulkLoadEvent) { BeginBulkLoadEvent beginBulkLoadEvent = (BeginBulkLoadEvent) event; completeFromCallable( - beginBulkLoadEvent.result, () -> processBeginBulkLoad(beginBulkLoadEvent)); + beginBulkLoadEvent.getResultFuture(), + () -> processBeginBulkLoad(beginBulkLoadEvent)); } else if (event instanceof CommitBulkLoadEvent) { CommitBulkLoadEvent commitBulkLoadEvent = (CommitBulkLoadEvent) event; completeFromCallable( - commitBulkLoadEvent.result, () -> processCommitBulkLoad(commitBulkLoadEvent)); + commitBulkLoadEvent.getResultFuture(), + () -> processCommitBulkLoad(commitBulkLoadEvent)); } else if (event instanceof AbortBulkLoadEvent) { AbortBulkLoadEvent abortBulkLoadEvent = (AbortBulkLoadEvent) event; completeFromCallable( - abortBulkLoadEvent.result, () -> processAbortBulkLoad(abortBulkLoadEvent)); + abortBulkLoadEvent.getResultFuture(), + () -> processAbortBulkLoad(abortBulkLoadEvent)); } else if (event instanceof ReclaimTableBulkLoadMetadataEvent) { processReclaimTableBulkLoadMetadata((ReclaimTableBulkLoadMetadataEvent) event); } else if (event instanceof CommitBulkLoadBucketEvent) { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java index 0d2174fd07b..6415d8b51c7 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/bulkload/BulkLoadManager.java @@ -460,7 +460,7 @@ public CompletableFuture commitBucketSnapshot( coordinatorEpochZkVersion, snapshotStores.getOrCreateCompletedSnapshotStore(tablePath, bucket)); eventManager.put(event); - return event.result + return event.getResultFuture() .handle( (ignored, failure) -> { if (failure instanceof KeeperException.NoNodeException @@ -472,7 +472,7 @@ public CompletableFuture commitBucketSnapshot( }, ioExecutor); } - return event.result; + return event.getResultFuture(); }) .thenCompose(result -> result); } @@ -506,7 +506,8 @@ private CompletableFuture enqueueTableMetadataReclamation( ReclaimTableBulkLoadMetadataEvent event = new ReclaimTableBulkLoadMetadataEvent(tableId, retentionCutoff); eventManager.put(event); - return event.result.exceptionally(failure -> handleReclamationFailure(tableId, failure)); + return event.getResultFuture() + .exceptionally(failure -> handleReclamationFailure(tableId, failure)); } private Void handleReclamationFailure(long tableId, Throwable failure) { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java index c6641b214b3..9ade55431c2 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/AbortBulkLoadEvent.java @@ -24,20 +24,25 @@ import java.util.concurrent.CompletableFuture; /** Aborts a BulkLoad transaction and releases ownership. */ -public final class AbortBulkLoadEvent implements CoordinatorEvent { +public final class AbortBulkLoadEvent implements CoordinatorEventWithResult { public final long tableId; public final String bulkLoadId; public final @Nullable String abortMessage; - public final CompletableFuture result; + private final CompletableFuture resultFuture; public AbortBulkLoadEvent( long tableId, String bulkLoadId, @Nullable String abortMessage, - CompletableFuture result) { + CompletableFuture resultFuture) { this.tableId = tableId; this.bulkLoadId = bulkLoadId; this.abortMessage = abortMessage; - this.result = result; + this.resultFuture = resultFuture; + } + + @Override + public CompletableFuture getResultFuture() { + return resultFuture; } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java index c7bd9873f15..9ff945997ad 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/BeginBulkLoadEvent.java @@ -26,20 +26,25 @@ import java.util.concurrent.CompletableFuture; /** Starts or replays a BulkLoad transaction. */ -public final class BeginBulkLoadEvent implements CoordinatorEvent { +public final class BeginBulkLoadEvent implements CoordinatorEventWithResult { public final TablePath tablePath; public final @Nullable String bulkLoadId; public final List partitionNames; - public final CompletableFuture result; + private final CompletableFuture resultFuture; public BeginBulkLoadEvent( TablePath tablePath, @Nullable String bulkLoadId, List partitionNames, - CompletableFuture result) { + CompletableFuture resultFuture) { this.tablePath = tablePath; this.bulkLoadId = bulkLoadId; this.partitionNames = partitionNames; - this.result = result; + this.resultFuture = resultFuture; + } + + @Override + public CompletableFuture getResultFuture() { + return resultFuture; } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadBucketEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadBucketEvent.java index 02b20c078bb..e01aa13239a 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadBucketEvent.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadBucketEvent.java @@ -28,7 +28,7 @@ import java.util.concurrent.CompletableFuture; /** Publishes the validated snapshot and the bucket's next role in the same transaction. */ -public final class CommitBulkLoadBucketEvent implements CoordinatorEvent { +public final class CommitBulkLoadBucketEvent implements CoordinatorEventWithResult { public final CompletedSnapshot snapshot; public final VersionedData transaction; public final VersionedData target; @@ -36,7 +36,7 @@ public final class CommitBulkLoadBucketEvent implements CoordinatorEvent { public final @Nullable Integer partitionVersion; public final int coordinatorEpochVersion; public final CompletedSnapshotStore snapshotStore; - public final CompletableFuture result = new CompletableFuture<>(); + private final CompletableFuture resultFuture = new CompletableFuture<>(); public CommitBulkLoadBucketEvent( CompletedSnapshot snapshot, @@ -54,4 +54,9 @@ public CommitBulkLoadBucketEvent( this.partitionVersion = partitionVersion; this.coordinatorEpochVersion = coordinatorEpochVersion; } + + @Override + public CompletableFuture getResultFuture() { + return resultFuture; + } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java index dc3d87d13e5..b56da361130 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CommitBulkLoadEvent.java @@ -22,15 +22,23 @@ import java.util.concurrent.CompletableFuture; /** Commits a BulkLoad transaction after verifying bucket completion. */ -public final class CommitBulkLoadEvent implements CoordinatorEvent { +public final class CommitBulkLoadEvent + implements CoordinatorEventWithResult { public final long tableId; public final String bulkLoadId; - public final CompletableFuture result; + private final CompletableFuture resultFuture; public CommitBulkLoadEvent( - long tableId, String bulkLoadId, CompletableFuture result) { + long tableId, + String bulkLoadId, + CompletableFuture resultFuture) { this.tableId = tableId; this.bulkLoadId = bulkLoadId; - this.result = result; + this.resultFuture = resultFuture; + } + + @Override + public CompletableFuture getResultFuture() { + return resultFuture; } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java index 98feb5183bf..b16b4f4a94f 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManager.java @@ -35,7 +35,6 @@ import org.slf4j.LoggerFactory; import java.util.Set; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; @@ -227,7 +226,7 @@ public void put(CoordinatorEvent event) { inLock( putLock, () -> { - if (thread.isShutdownInitiated() && rejectPendingBulkLoadEvent(event)) { + if (thread.isShutdownInitiated() && rejectPendingEvent(event)) { return; } try { @@ -243,7 +242,7 @@ public void put(CoordinatorEvent event) { event, event.getClass()); } catch (InterruptedException e) { - rejectPendingBulkLoadEvent(event); + rejectPendingEvent(event); LOG.error("Fail to put coordinator event {}.", event, e); } }); @@ -255,36 +254,22 @@ public void clearAndPut(CoordinatorEvent event) { () -> { QueuedEvent pending; while ((pending = queue.poll()) != null) { - rejectPendingBulkLoadEvent(pending.event); + rejectPendingEvent(pending.event); } put(event); }); } - private static boolean rejectPendingBulkLoadEvent(CoordinatorEvent event) { - if (event instanceof CommitBulkLoadBucketEvent) { - CommitBulkLoadBucketEvent commit = (CommitBulkLoadBucketEvent) event; - commit.result.completeExceptionally( - new NotCoordinatorLeaderException( - "Coordinator stopped before publishing " - + commit.snapshot.getTableBucket())); + private static boolean rejectPendingEvent(CoordinatorEvent event) { + if (event instanceof CoordinatorEventWithResult) { + ((CoordinatorEventWithResult) event) + .getResultFuture() + .completeExceptionally( + new NotCoordinatorLeaderException( + "Coordinator could not process the pending event.")); return true; } - - CompletableFuture response; - if (event instanceof BeginBulkLoadEvent) { - response = ((BeginBulkLoadEvent) event).result; - } else if (event instanceof CommitBulkLoadEvent) { - response = ((CommitBulkLoadEvent) event).result; - } else if (event instanceof AbortBulkLoadEvent) { - response = ((AbortBulkLoadEvent) event).result; - } else { - return false; - } - response.completeExceptionally( - new NotCoordinatorLeaderException( - "Coordinator stopped before processing BulkLoad metadata.")); - return true; + return false; } private class CoordinatorEventThread extends ShutdownableThread { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventWithResult.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventWithResult.java new file mode 100644 index 00000000000..e2698ae82d6 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/CoordinatorEventWithResult.java @@ -0,0 +1,27 @@ +/* + * 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; + +import java.util.concurrent.CompletableFuture; + +/** A coordinator event whose result must be completed even if the event cannot be processed. */ +public interface CoordinatorEventWithResult extends CoordinatorEvent { + + /** Returns the future for the result of processing this event. */ + CompletableFuture getResultFuture(); +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java index fc455fe3d30..ff3b6c04a31 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/event/ReclaimTableBulkLoadMetadataEvent.java @@ -20,13 +20,18 @@ import java.util.concurrent.CompletableFuture; /** Requests BulkLoad metadata reclamation for one physical table. */ -public final class ReclaimTableBulkLoadMetadataEvent implements CoordinatorEvent { +public final class ReclaimTableBulkLoadMetadataEvent implements CoordinatorEventWithResult { public final long tableId; public final long retentionCutoff; - public final CompletableFuture result = new CompletableFuture<>(); + private final CompletableFuture resultFuture = new CompletableFuture<>(); public ReclaimTableBulkLoadMetadataEvent(long tableId, long retentionCutoff) { this.tableId = tableId; this.retentionCutoff = retentionCutoff; } + + @Override + public CompletableFuture getResultFuture() { + return resultFuture; + } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java index a4d63e9cae5..9f5535405de 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/event/CoordinatorEventManagerTest.java @@ -251,6 +251,26 @@ void testBulkLoadLifecycleEventsFailWhenCoordinatorStops() { } } + @Test + void testShutdownRejectsQueuedMetadataReclamation() { + CoordinatorMetricGroup metricGroup = + new CoordinatorMetricGroup(new TestingMetricRegistry(), "cluster1", "host", "0"); + CoordinatorEventManager manager = new CoordinatorEventManager(event -> {}, metricGroup); + ReclaimTableBulkLoadMetadataEvent reclaim = new ReclaimTableBulkLoadMetadataEvent(1L, 0L); + try { + // Leave the event thread unstarted so close drains the queued reclamation. + manager.put(reclaim); + manager.close(); + + assertThat(reclaim.getResultFuture()).isCompletedExceptionally(); + assertThatThrownBy(reclaim.getResultFuture()::join) + .hasCauseInstanceOf(NotCoordinatorLeaderException.class) + .hasRootCauseMessage("Coordinator could not process the pending event."); + } finally { + metricGroup.close(); + } + } + private static void processAccessContext( AccessContextEvent event, CoordinatorContext context) { try {