Stephen0421 commented on code in PR #9207:
URL: https://github.com/apache/paimon/pull/9207#discussion_r3795110500


##########
paimon-core/src/main/java/org/apache/paimon/operation/LocalManagedBlobOrphanFilesClean.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicLong;
+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 {
+
+    private final ThreadPoolExecutor executor;
+    private final List<Path> deleteFiles = new ArrayList<>();
+    private final AtomicLong deletedFilesLenInBytes = new AtomicLong(0);
+
+    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 {
+        Map<String, Pair<Path, Long>> candidates = getCandidatePacks();
+        if (candidates.isEmpty()) {
+            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);
+        }
+
+        candidates.entrySet().stream()
+                .filter(e -> !usedPacks2.contains(e.getKey()))
+                .map(Map.Entry::getValue)
+                .forEach(
+                        info -> {
+                            if (cleanManagedBlobFile(info.getLeft())) {
+                                
deletedFilesLenInBytes.addAndGet(info.getRight());
+                                deleteFiles.add(info.getLeft());
+                            }
+                        });
+
+        if (!dryRun) {
+            cleanEmptyDataDirectory(deleteFiles);
+        }
+        return new CleanOrphanFilesResult(
+                deleteFiles.size(), deletedFilesLenInBytes.get(), deleteFiles);
+    }
+
+    @Override
+    protected Set<String> collectUsedPacks() {
+        return validBranches().stream()
+                .flatMap(branch -> getUsedPacks(branch).stream())
+                .collect(Collectors.toSet());
+    }
+
+    private Set<String> getUsedPacks(String branch) {
+        Set<String> used = ConcurrentHashMap.newKeySet();
+        try {
+            randomlyOnlyExecute(
+                    executor,
+                    snapshot -> {
+                        try {
+                            emitUsedPacks(branch, snapshot, 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();
+            result.put(packIdentity(fileInfo.getLeft()), 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 =

Review Comment:
   Fixed.
   
   Database cleanup now uses `ExecutorCompletionService`, so a failed table is 
observed immediately even if an earlier submitted table is still running.
   
   All exit paths cancel unfinished futures, interrupt the per-table cleaners, 
close their executors, call `shutdownNow()`, wait for termination, and preserve 
the caller's interrupt status. The deletion loop also checks interruption 
between files.
   
   The tests cover both submission-order failure and cancellation while another 
table is already inside the real deletion loop, and verify that no deletion 
continues after the procedure returns.



-- 
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]

Reply via email to