Stephen0421 commented on code in PR #9207: URL: https://github.com/apache/paimon/pull/9207#discussion_r3892287495
########## paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/orphan/FlinkManagedBlobOrphanFilesClean.java: ########## @@ -0,0 +1,867 @@ +/* + * 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.paimon.flink.orphan; + +import org.apache.paimon.Snapshot; +import org.apache.paimon.catalog.Catalog; +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.flink.utils.BoundedOneInputOperator; +import org.apache.paimon.flink.utils.BoundedTwoInputOperator; +import org.apache.paimon.fs.FileStatus; +import org.apache.paimon.fs.Path; +import org.apache.paimon.manifest.ManifestEntry; +import org.apache.paimon.manifest.ManifestFile; +import org.apache.paimon.manifest.ManifestFileMeta; +import org.apache.paimon.manifest.ManifestList; +import org.apache.paimon.operation.CleanOrphanFilesResult; +import org.apache.paimon.operation.ManagedBlobOrphanFilesClean; +import org.apache.paimon.operation.ManagedBlobOrphanFilesClean.SidecarWorkItem; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.Table; +import org.apache.paimon.utils.DataFilePathFactories; +import org.apache.paimon.utils.FileStorePathFactory; + +import org.apache.flink.api.common.RuntimeExecutionMode; +import org.apache.flink.api.common.functions.OpenContext; +import org.apache.flink.api.common.typeinfo.TypeInformation; +import org.apache.flink.api.common.typeinfo.Types; +import org.apache.flink.api.java.tuple.Tuple2; +import org.apache.flink.api.java.tuple.Tuple3; +import org.apache.flink.configuration.Configuration; +import org.apache.flink.configuration.CoreOptions; +import org.apache.flink.configuration.ExecutionOptions; +import org.apache.flink.streaming.api.datastream.DataStream; +import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; +import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; +import org.apache.flink.streaming.api.functions.ProcessFunction; +import org.apache.flink.streaming.api.functions.sink.v2.DiscardingSink; +import org.apache.flink.streaming.api.operators.InputSelection; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.util.CloseableIterator; +import org.apache.flink.util.Collector; +import org.apache.flink.util.OutputTag; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; + +import static org.apache.flink.api.common.typeinfo.BasicTypeInfo.STRING_TYPE_INFO; +import static org.apache.flink.util.Preconditions.checkState; +import static org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX; +import static org.apache.paimon.utils.Preconditions.checkArgument; + +/** Flink {@link ManagedBlobOrphanFilesClean}. */ +public class FlinkManagedBlobOrphanFilesClean extends ManagedBlobOrphanFilesClean { + + private static final Logger LOG = + LoggerFactory.getLogger(FlinkManagedBlobOrphanFilesClean.class); + + @Nullable private final Integer parallelism; + + public FlinkManagedBlobOrphanFilesClean( + FileStoreTable table, + long olderThanMillis, + boolean dryRun, + @Nullable Integer parallelism) { + super(table, olderThanMillis, dryRun); + validateParallelism(parallelism); + this.parallelism = parallelism; + } + + @Nullable + public DataStream<CleanOrphanFilesResult> doClean(StreamExecutionEnvironment env) { + List<String> topologyBefore; + try { + topologyBefore = snapshotTopology(); + } catch (java.io.IOException e) { + throw new RuntimeException(e); + } + + Configuration flinkConf = new Configuration(); + flinkConf.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH); + flinkConf.set(ExecutionOptions.SORT_INPUTS, false); + flinkConf.set(ExecutionOptions.USE_BATCH_STATE_BACKEND, false); + if (parallelism != null) { + flinkConf.set(CoreOptions.DEFAULT_PARALLELISM, parallelism); + } + flinkConf.setString("execution.batch.adaptive.auto-parallelism.enabled", "false"); + env.configure(flinkConf); + + List<String> branches = validBranches(); + final OutputTag<Boolean> firstMarkSkipGcTag = + new OutputTag<Boolean>("first-managed-blob-mark-skip") {}; + SingleOutputStreamOperator<Tuple2<String, String>> firstManifestLists = + env.fromCollection(branches) + .name("branch-source") + .process( + new ProcessFunction<String, Tuple2<String, String>>() { + @Override + public void processElement( + String branch, + ProcessFunction<String, Tuple2<String, String>>.Context + ctx, + Collector<Tuple2<String, String>> out) + throws Exception { + emitManifestLists(branch, out::collect); + } + }) + .name("collect-first-mark-manifest-lists"); + + SingleOutputStreamOperator<String> usedPacks = + collectUsedPacks(firstManifestLists, firstMarkSkipGcTag, "first"); + + DataStream<Boolean> firstMarkCompleted = markCompletion(usedPacks, "first"); + SingleOutputStreamOperator<Tuple2<String, String>> secondManifestLists = + firstMarkCompleted + .transform( + "wait-before-second-managed-blob-mark", + Types.TUPLE(Types.STRING, Types.STRING), + new BoundedOneInputOperator<Boolean, Tuple2<String, String>>() { + + @Override + public void processElement(StreamRecord<Boolean> element) {} + + @Override + public void endInput() throws Exception { + for (String branch : branches) { + emitManifestLists( + branch, + manifestList -> + output.collect( + new StreamRecord<>( + manifestList))); + } + } + }) + .forceNonParallel(); + + final OutputTag<Boolean> secondMarkSkipGcTag = + new OutputTag<Boolean>("second-managed-blob-mark-skip") {}; + SingleOutputStreamOperator<String> usedPacks2 = + collectUsedPacks(secondManifestLists, secondMarkSkipGcTag, "second"); + + DataStream<Boolean> usedPacksChanged = compareUsedPacks(usedPacks, usedPacks2); + DataStream<Boolean> topologyChanged = + markCompletion(usedPacks2, "second") + .transform( + "check-managed-blob-snapshot-topology", + TypeInformation.of(Boolean.class), + new BoundedOneInputOperator<Boolean, Boolean>() { + + @Override + public void processElement(StreamRecord<Boolean> element) {} + + @Override + public void endInput() throws Exception { + List<String> topologyAfter = snapshotTopology(); + if (!topologyBefore.equals(topologyAfter)) { + LOG.warn( + "Skip managed blob pack GC for table {} because snapshot topology changed during used-pack collection.", + table.fullName()); + output.collect(new StreamRecord<>(Boolean.TRUE)); + } + } + }) + .forceNonParallel(); + + final OutputTag<Boolean> candidateSkipGcTag = + new OutputTag<Boolean>("candidate-managed-blob-skip") {}; + SingleOutputStreamOperator<Tuple3<String, String, Long>> candidates = + env.fromCollection(Collections.singletonList(1), TypeInformation.of(Integer.class)) + .process( + new ProcessFunction<Integer, String>() { + @Override + public void processElement( + Integer i, + ProcessFunction<Integer, String>.Context ctx, + Collector<String> out) { + FileStorePathFactory pathFactory = + table.store().pathFactory(); + listPaimonFileDirs( + table.fullName(), + pathFactory.manifestPath().toString(), + pathFactory.indexPath().toString(), + pathFactory.statisticsPath().toString(), + pathFactory.dataFilePath().toString(), + partitionKeysNum, + table.coreOptions().dataFileExternalPaths()) + .stream() + .map(Path::toUri) + .map(Object::toString) + .forEach(out::collect); + } + }) + .name("list-dirs") + .forceNonParallel() + .process( + new ProcessFunction<String, Tuple3<String, String, Long>>() { + @Override + public void processElement( + String dir, + ProcessFunction<String, Tuple3<String, String, Long>> + .Context + ctx, + Collector<Tuple3<String, String, Long>> out) { + for (FileStatus file : tryBestListingDirs(new Path(dir))) { + if (!file.isDir() + && oldEnough(file) + && isManagedBlobPackName( + file.getPath().getName())) { + Optional<String> identity = + FlinkManagedBlobOrphanFilesClean.this + .packIdentityForCleanup( + file.getPath()); + if (identity.isPresent()) { + out.collect( + Tuple3.of( + identity.get(), + file.getPath().toString(), + file.getLen())); + } else { + LOG.warn( + "Cannot safely identify candidate managed blob pack {}. Skip pack GC this run.", + file.getPath()); + ctx.output(candidateSkipGcTag, Boolean.TRUE); + } + } + } + } + }) + .name("collect-candidate-packs"); + + final OutputTag<Tuple2<String, Long>> unusedPackTag = + new OutputTag<Tuple2<String, Long>>("unused-managed-blob") {}; + + SingleOutputStreamOperator<CleanOrphanFilesResult> unusedJoin = + usedPacks2 + .keyBy(identity -> identity) + .connect(candidates.keyBy(candidate -> candidate.f0)) + .transform( + "join-used-and-candidate-packs", + TypeInformation.of(CleanOrphanFilesResult.class), + new BoundedTwoInputOperator< + String, + Tuple3<String, String, Long>, + CleanOrphanFilesResult>() { + + private boolean buildEnd; + private final Set<String> used = new HashSet<>(); + + @Override + public InputSelection nextSelection() { + return buildEnd + ? InputSelection.SECOND + : InputSelection.FIRST; + } + + @Override + public void endInput(int inputId) { + switch (inputId) { + case 1: + checkState(!buildEnd, "Should not build ended."); + buildEnd = true; + break; + case 2: + checkState(buildEnd, "Should build ended."); + output.collect( + new StreamRecord<>( + new CleanOrphanFilesResult(0, 0))); + break; + } + } + + @Override + public void processElement1(StreamRecord<String> element) { + used.add(element.getValue()); + } + + @Override + public void processElement2( + StreamRecord<Tuple3<String, String, Long>> element) { + checkState(buildEnd, "Should build ended."); + Tuple3<String, String, Long> candidate = element.getValue(); + if (!used.contains(candidate.f0)) { + output.collect( + unusedPackTag, + new StreamRecord<>( + Tuple2.of(candidate.f1, candidate.f2))); + } + } + }); + + DataStream<Boolean> skipGc = + usedPacks + .getSideOutput(firstMarkSkipGcTag) + .union( + usedPacks2.getSideOutput(secondMarkSkipGcTag), + usedPacksChanged, + topologyChanged, + candidates.getSideOutput(candidateSkipGcTag)); + + final OutputTag<Path> emptyDirTag = new OutputTag<Path>("empty-managed-blob-dir") {}; + SingleOutputStreamOperator<CleanOrphanFilesResult> cleaned = + unusedJoin + .getSideOutput(unusedPackTag) + .connect(skipGc.broadcast()) + .transform( + "clean-unused-managed-blobs", + TypeInformation.of(CleanOrphanFilesResult.class), + new BoundedTwoInputOperator< + Tuple2<String, Long>, Boolean, CleanOrphanFilesResult>() { + + private boolean skipEnded; + private boolean skipGc; + private long emittedFilesCount; + private long emittedFilesLen; + + @Override + public InputSelection nextSelection() { Review Comment: Thanks. The managed-blob cleanup job now forces `BatchShuffleMode.ALL_EXCHANGES_BLOCKING`, so unused packs are materialized before the skip/delete operator and cannot form a pipelined feedback cycle with the candidate skip side output. The same blocking shuffle is applied to `remove_orphan_files`, which uses the same used/candidate join order. Added a regression that starts from `ALL_EXCHANGES_PIPELINED` and asserts the job rewrites it to blocking. ########## paimon-core/src/main/java/org/apache/paimon/operation/LocalManagedBlobOrphanFilesClean.java: ########## @@ -0,0 +1,344 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.catalog.Catalog; +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.fs.Path; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.Table; +import org.apache.paimon.utils.Pair; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletionService; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX; +import static org.apache.paimon.utils.Preconditions.checkArgument; +import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool; +import static org.apache.paimon.utils.ThreadPoolUtils.randomlyExecuteSequentialReturn; +import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute; + +/** Local {@link ManagedBlobOrphanFilesClean}. */ +public class LocalManagedBlobOrphanFilesClean extends ManagedBlobOrphanFilesClean + implements AutoCloseable { + + /** + * Upper bound for waiting cancelled table cleanups after a database-wide failure. {@code + * shutdownNow()} only requests interruption; a FileIO call may ignore it until a socket + * timeout. Waiting forever would hide the original failure. + */ + private static final long TERMINATION_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(120); + + private final ThreadPoolExecutor executor; + + public LocalManagedBlobOrphanFilesClean( + FileStoreTable table, long olderThanMillis, boolean dryRun) { + super(table, olderThanMillis, dryRun); + this.executor = + createCachedThreadPool( + table.coreOptions().fileOperationThreadNum(), + "MANAGED_BLOB_ORPHAN_FILES_CLEAN"); + } + + public CleanOrphanFilesResult clean() throws IOException { + List<Path> deleteFiles = new ArrayList<>(); + long deletedFilesLenInBytes = 0; + Map<String, Pair<Path, Long>> candidates = getCandidatePacks(); + if (candidates.isEmpty()) { + return new CleanOrphanFilesResult(0, 0, deleteFiles); + } + if (candidates.containsKey(SKIP_MANAGED_BLOB_GC)) { + LOG.warn( + "Skip managed blob pack GC for table {} because a listed pack path cannot be resolved safely.", + table.fullName()); + return new CleanOrphanFilesResult(0, 0, deleteFiles); + } + + List<String> topologyBefore = snapshotTopology(); + Set<String> usedPacks = collectUsedPacks(); + betweenUsedCollections(); + Set<String> usedPacks2 = collectUsedPacks(); + if (shouldAbortPackGc(topologyBefore, usedPacks, usedPacks2)) { + return new CleanOrphanFilesResult(0, 0, deleteFiles); + } + + for (Map.Entry<String, Pair<Path, Long>> candidate : candidates.entrySet()) { + throwIfInterrupted(); + if (usedPacks2.contains(candidate.getKey())) { + continue; + } + Pair<Path, Long> info = candidate.getValue(); + if (cleanManagedBlobFile(info.getLeft())) { + deletedFilesLenInBytes += info.getRight(); + deleteFiles.add(info.getLeft()); + } + } + + throwIfInterrupted(); + if (!dryRun) { + cleanEmptyDataDirectory(deleteFiles); + } + return new CleanOrphanFilesResult(deleteFiles.size(), deletedFilesLenInBytes, deleteFiles); + } + + private static void throwIfInterrupted() throws IOException { + if (Thread.currentThread().isInterrupted()) { + throw new IOException("Interrupted while cleaning managed blob orphan files."); + } + } + + @Override + protected Set<String> collectUsedPacks() { + ReachabilityScan scan = newReachabilityScan(); + return validBranches().stream() + .flatMap(branch -> getUsedPacks(branch, scan).stream()) + .collect(Collectors.toSet()); + } + + private Set<String> getUsedPacks(String branch, ReachabilityScan scan) { + Set<String> used = ConcurrentHashMap.newKeySet(); + try { + randomlyOnlyExecute( Review Comment: Thanks. Snapshot tasks in one mark pass now wait in completion order and cancel the remaining tasks on the first failure, so a later failed snapshot is not hidden by an earlier one stuck in uninterruptible I/O. Added a completion-order test for sibling snapshot tasks. ########## paimon-core/src/main/java/org/apache/paimon/operation/LocalManagedBlobOrphanFilesClean.java: ########## @@ -0,0 +1,344 @@ +/* + * 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.paimon.operation; + +import org.apache.paimon.CoreOptions; +import org.apache.paimon.catalog.Catalog; +import org.apache.paimon.catalog.Identifier; +import org.apache.paimon.fs.Path; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.Table; +import org.apache.paimon.utils.Pair; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletionService; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.paimon.utils.FileStorePathFactory.BUCKET_PATH_PREFIX; +import static org.apache.paimon.utils.Preconditions.checkArgument; +import static org.apache.paimon.utils.ThreadPoolUtils.createCachedThreadPool; +import static org.apache.paimon.utils.ThreadPoolUtils.randomlyExecuteSequentialReturn; +import static org.apache.paimon.utils.ThreadPoolUtils.randomlyOnlyExecute; + +/** Local {@link ManagedBlobOrphanFilesClean}. */ +public class LocalManagedBlobOrphanFilesClean extends ManagedBlobOrphanFilesClean + implements AutoCloseable { + + /** + * Upper bound for waiting cancelled table cleanups after a database-wide failure. {@code + * shutdownNow()} only requests interruption; a FileIO call may ignore it until a socket + * timeout. Waiting forever would hide the original failure. + */ + private static final long TERMINATION_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(120); + + private final ThreadPoolExecutor executor; + + public LocalManagedBlobOrphanFilesClean( + FileStoreTable table, long olderThanMillis, boolean dryRun) { + super(table, olderThanMillis, dryRun); + this.executor = + createCachedThreadPool( + table.coreOptions().fileOperationThreadNum(), + "MANAGED_BLOB_ORPHAN_FILES_CLEAN"); + } + + public CleanOrphanFilesResult clean() throws IOException { + List<Path> deleteFiles = new ArrayList<>(); + long deletedFilesLenInBytes = 0; + Map<String, Pair<Path, Long>> candidates = getCandidatePacks(); + if (candidates.isEmpty()) { + return new CleanOrphanFilesResult(0, 0, deleteFiles); + } + if (candidates.containsKey(SKIP_MANAGED_BLOB_GC)) { + LOG.warn( + "Skip managed blob pack GC for table {} because a listed pack path cannot be resolved safely.", + table.fullName()); + return new CleanOrphanFilesResult(0, 0, deleteFiles); + } + + List<String> topologyBefore = snapshotTopology(); + Set<String> usedPacks = collectUsedPacks(); + betweenUsedCollections(); + Set<String> usedPacks2 = collectUsedPacks(); + if (shouldAbortPackGc(topologyBefore, usedPacks, usedPacks2)) { + return new CleanOrphanFilesResult(0, 0, deleteFiles); + } + + for (Map.Entry<String, Pair<Path, Long>> candidate : candidates.entrySet()) { + throwIfInterrupted(); + if (usedPacks2.contains(candidate.getKey())) { + continue; + } + Pair<Path, Long> info = candidate.getValue(); + if (cleanManagedBlobFile(info.getLeft())) { + deletedFilesLenInBytes += info.getRight(); + deleteFiles.add(info.getLeft()); + } + } + + throwIfInterrupted(); + if (!dryRun) { + cleanEmptyDataDirectory(deleteFiles); + } + return new CleanOrphanFilesResult(deleteFiles.size(), deletedFilesLenInBytes, deleteFiles); + } + + private static void throwIfInterrupted() throws IOException { + if (Thread.currentThread().isInterrupted()) { + throw new IOException("Interrupted while cleaning managed blob orphan files."); + } + } + + @Override + protected Set<String> collectUsedPacks() { + ReachabilityScan scan = newReachabilityScan(); + return validBranches().stream() + .flatMap(branch -> getUsedPacks(branch, scan).stream()) + .collect(Collectors.toSet()); + } + + private Set<String> getUsedPacks(String branch, ReachabilityScan scan) { + Set<String> used = ConcurrentHashMap.newKeySet(); + try { + randomlyOnlyExecute( + executor, + snapshot -> { + try { + emitUsedPacks(branch, snapshot, scan, used::add); + } catch (IOException e) { + throw new RuntimeException(e); + } + }, + safelyGetAllSnapshots(branch)); + } catch (IOException e) { + throw new RuntimeException(e); + } + return used; + } + + private Map<String, Pair<Path, Long>> getCandidatePacks() { + List<Path> fileDirs = listPaimonFileDirs(); + Iterator<Pair<Path, Long>> packs = + randomlyExecuteSequentialReturn(executor, packLister(), fileDirs); + Map<String, Pair<Path, Long>> result = new HashMap<>(); + while (packs.hasNext()) { + Pair<Path, Long> fileInfo = packs.next(); + Optional<String> identity = packIdentityForCleanup(fileInfo.getLeft()); + if (!identity.isPresent()) { + result.clear(); + result.put(SKIP_MANAGED_BLOB_GC, fileInfo); + return result; + } + result.put(identity.get(), fileInfo); + } + return result; + } + + private Function<Path, List<Pair<Path, Long>>> packLister() { + return path -> + tryBestListingDirs(path).stream() + .filter(status -> !status.isDir()) + .filter(this::oldEnough) + .filter(status -> isManagedBlobPackName(status.getPath().getName())) + .map(status -> Pair.of(status.getPath(), status.getLen())) + .collect(Collectors.toList()); + } + + private void cleanEmptyDataDirectory(List<Path> deleted) { + if (deleted.isEmpty()) { + return; + } + Set<Path> bucketDirs = + deleted.stream() + .map(Path::getParent) + .filter(path -> path.toString().contains(BUCKET_PATH_PREFIX)) + .collect(Collectors.toSet()); + randomlyOnlyExecute(executor, this::tryDeleteEmptyDirectory, bucketDirs); + Set<Path> partitionDirs = + bucketDirs.stream().map(Path::getParent).collect(Collectors.toSet()); + tryCleanDataDirectory(partitionDirs, partitionKeysNum); + } + + public static List<LocalManagedBlobOrphanFilesClean> createCleans( + Catalog catalog, + String databaseName, + @Nullable String tableName, + long olderThanMillis, + @Nullable Integer parallelism, + boolean dryRun) + throws Catalog.DatabaseNotExistException, Catalog.TableNotExistException { + List<String> tableNames = Collections.singletonList(tableName); + if (tableName == null || "*".equals(tableName)) { + tableNames = catalog.listTables(databaseName); + } + + Map<String, String> dynamicOptions = + parallelism == null + ? Collections.emptyMap() + : new HashMap<String, String>() { + { + put( + CoreOptions.FILE_OPERATION_THREAD_NUM.key(), + parallelism.toString()); + } + }; + + List<LocalManagedBlobOrphanFilesClean> cleans = new ArrayList<>(tableNames.size()); + for (String t : tableNames) { + Identifier identifier = new Identifier(databaseName, t); + Table table = catalog.getTable(identifier).copy(dynamicOptions); + checkArgument( + table instanceof FileStoreTable, + "Only FileStoreTable supports remove-orphan-blobs action. The table type is '%s'.", + table.getClass().getName()); + cleans.add( + new LocalManagedBlobOrphanFilesClean( + (FileStoreTable) table, olderThanMillis, dryRun)); + } + return cleans; + } + + public static CleanOrphanFilesResult executeDatabase( + Catalog catalog, + String databaseName, + @Nullable String tableName, + long olderThanMillis, + @Nullable Integer parallelism, + boolean dryRun) + throws Catalog.DatabaseNotExistException, Catalog.TableNotExistException { + List<LocalManagedBlobOrphanFilesClean> tableCleans = + createCleans( + catalog, databaseName, tableName, olderThanMillis, parallelism, dryRun); + ExecutorService executorService = + Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); Review Comment: Thanks. The database-wide pool now uses a named daemon thread factory (`MANAGED-BLOB-ORPHAN-DB-CLEAN`), so a FileIO call that ignores interruption past the termination timeout cannot pin a standalone JVM or leak workers in embedded local-mode calls. The bounded wait and interruption checks are unchanged. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
