Gabriel39 commented on code in PR #66348: URL: https://github.com/apache/doris/pull/66348#discussion_r3698478896
########## fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/IcebergRemoveOrphanFilesAction.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.doris.connector.iceberg.action; + +import org.apache.doris.connector.api.ConnectorColumn; +import org.apache.doris.connector.api.ConnectorSession; +import org.apache.doris.connector.api.ConnectorType; +import org.apache.doris.connector.api.DorisConnectorException; +import org.apache.doris.connector.api.pushdown.ConnectorPredicate; +import org.apache.doris.foundation.util.ArgumentParsers; + +import com.google.common.collect.Lists; +import org.apache.iceberg.DataFile; +import org.apache.iceberg.DeleteFile; +import org.apache.iceberg.ManifestContent; +import org.apache.iceberg.ManifestFile; +import org.apache.iceberg.ManifestFiles; +import org.apache.iceberg.ManifestReader; +import org.apache.iceberg.ReachableFileUtil; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.io.FileInfo; +import org.apache.iceberg.io.SupportsPrefixOperations; +import org.apache.iceberg.util.PropertyUtil; + +import java.io.IOException; +import java.net.URI; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** Safely lists or deletes old files that are unreachable from every retained snapshot. */ +public class IcebergRemoveOrphanFilesAction extends BaseIcebergAction { + private static final long MIN_RETENTION_MS = Duration.ofHours(24).toMillis(); + public static final String OLDER_THAN = "older_than"; + public static final String LOCATION = "location"; + public static final String DRY_RUN = "dry_run"; + + public IcebergRemoveOrphanFilesAction(Map<String, String> properties, List<String> partitionNames, + ConnectorPredicate whereCondition) { + super("remove_orphan_files", properties, partitionNames, whereCondition); + } + + @Override + protected void registerIcebergArguments() { + namedArguments.registerRequiredArgument(OLDER_THAN, "Creation time cutoff in milliseconds", + ArgumentParsers.nonNegativeLong(OLDER_THAN)); + namedArguments.registerOptionalArgument(LOCATION, "Prefix within the table location", + null, ArgumentParsers.nonEmptyString(LOCATION)); + namedArguments.registerOptionalArgument(DRY_RUN, "Only count orphan files", true, + ArgumentParsers.booleanValue(DRY_RUN)); + } + + @Override + protected void validateIcebergAction() { + validateNoPartitions(); + validateNoWhereCondition(); + String location = namedArguments.getString(LOCATION); + if (location != null) { + try { + normalizeLocation(location); + } catch (IllegalArgumentException e) { + throw new DorisConnectorException("Invalid location URI: " + location, e); + } + } + } + + @Override + protected List<String> executeAction(Table table, ConnectorSession session) { + if (!(table.io() instanceof SupportsPrefixOperations)) { + throw new DorisConnectorException("remove_orphan_files requires FileIO prefix listing support"); + } + if (!PropertyUtil.propertyAsBoolean(table.properties(), TableProperties.GC_ENABLED, + TableProperties.GC_ENABLED_DEFAULT)) { + // A GC-disabled table may share files with another table, so no destructive scan is safe. + throw new DorisConnectorException("Cannot remove orphan files: Iceberg GC is disabled"); + } + List<String> scanLocations = resolveScanLocations(table); + + try { + ReachableIndex reachable = new ReachableIndex(collectReachableFiles(table)); + long orphanCount = 0; + long deletedCount = 0; + long olderThan = namedArguments.getLong(OLDER_THAN); + // The SQL procedure needs a retention fence because concurrent uploads are not reachable until commit. + if (olderThan > System.currentTimeMillis() - MIN_RETENTION_MS) { + throw new DorisConnectorException( + "older_than must retain at least 24 hours of files"); + } + boolean dryRun = namedArguments.getBoolean(DRY_RUN); + Set<String> visitedFiles = new HashSet<>(); + for (String scanLocation : scanLocations) { + // Object stores use raw prefix matching, so the separator excludes sibling prefixes. + String listingPrefix = scanLocation.endsWith("/") ? scanLocation : scanLocation + "/"; + for (FileInfo file : ((SupportsPrefixOperations) table.io()).listPrefix(listingPrefix)) { + if (visitedFiles.add(file.location()) && file.createdAtMillis() < olderThan + && !isReachable(file.location(), reachable)) { + orphanCount++; + if (!dryRun) { + table.io().deleteFile(file.location()); + deletedCount++; + } + } + } + } + return Lists.newArrayList(String.valueOf(orphanCount), String.valueOf(deletedCount)); + } catch (Exception e) { + throw new DorisConnectorException("Failed to remove orphan files: " + e.getMessage(), e); + } + } + + private List<String> resolveScanLocations(Table table) { + List<String> ownedRoots = resolveOwnedRoots(table.location(), table.properties()); + + String requested = namedArguments.getString(LOCATION); + if (requested != null) { + String normalized = normalizeLocation(requested); + boolean owned = ownedRoots.stream().anyMatch(root -> isWithin(normalized, root)); + if (!owned) { + throw new DorisConnectorException( + "location must be within an Iceberg table-owned metadata or data location"); + } + return Lists.newArrayList(normalized); + } + + return minimalOwnedRoots(ownedRoots); + } + + static List<String> resolveOwnedRoots(String tableLocation, Map<String, String> properties) { + String tableRoot = normalizeLocation(tableLocation); + String dataRoot = normalizeLocation(resolveDataLocation(properties, tableRoot)); + List<String> configuredRoots = new ArrayList<>(); + configuredRoots.add(tableRoot); + configuredRoots.add(dataRoot); + // Iceberg may place metadata outside both table and data roots, so it remains an independent owned root. + String metadataRoot = nonEmpty(properties.get(TableProperties.WRITE_METADATA_LOCATION)); + if (metadataRoot != null) { + configuredRoots.add(normalizeLocation(metadataRoot)); + } + return canonicalOwnedRoots(configuredRoots); + } + + static List<String> minimalOwnedRoots(List<String> roots) { + List<String> canonicalRoots = canonicalOwnedRoots(roots); + List<String> minimal = new ArrayList<>(); + for (String candidate : canonicalRoots) { + // Canonically equal aliases are deduplicated first, so only strict containment removes a root. + if (canonicalRoots.stream().noneMatch(other -> !sameFileIdentity(other, candidate) + && isWithinLocation(candidate, other))) { + minimal.add(candidate); + } + } + return minimal; + } + + private static List<String> canonicalOwnedRoots(List<String> roots) { + Map<FileIdentity, String> byIdentity = new LinkedHashMap<>(); + for (String root : roots) { + byIdentity.putIfAbsent(FileIdentity.of(root), root); + } + return new ArrayList<>(byIdentity.values()); + } + + private static String resolveDataLocation(Map<String, String> properties, String tableRoot) { Review Comment: Fixed by handling write.location-provider.impl before built-in properties. Default cleanup now fails with a precise unsupported-layout error for custom providers. A verified explicit location plus allow_unsafe_location=true is the guarded escape hatch, and the test covers both the fail-closed default and guarded external cleanup. ########## fe/fe-filesystem/fe-filesystem-azure/src/main/java/org/apache/doris/filesystem/azure/AzureObjStorage.java: ########## @@ -244,15 +244,31 @@ public void completeMultipartUpload(String remotePath, String uploadId, List<UploadPartResult> parts) throws IOException { try { AzureUri uri = AzureUri.parse(remotePath); - BlockBlobClient blockBlobClient = getClient().getBlobContainerClient(uri.container()) - .getBlobClient(uri.key()).getBlockBlobClient(); + BlobContainerClient containerClient = getClient().getBlobContainerClient(uri.container()); List<String> blockIds = new ArrayList<>(); List<UploadPartResult> sorted = new ArrayList<>(parts); sorted.sort((a, b) -> Integer.compare(a.partNumber(), b.partNumber())); + boolean exactBlockIds = !sorted.isEmpty() && sorted.stream() + .allMatch(part -> part.etag() != null && !part.etag().isEmpty()); for (UploadPartResult part : sorted) { - blockIds.add(toBlockId(part.partNumber())); + // A mixed-version upload must use one namespace consistently; new BEs also stage legacy IDs. + blockIds.add(exactBlockIds ? part.etag() : toBlockId(part.partNumber())); + } + String commitKey = exactBlockIds ? multipartTempKey(uri.key(), uploadId) : uri.key(); + BlobClient commitBlob = containerClient.getBlobClient(commitKey); + commitBlob.getBlockBlobClient().commitBlockList(blockIds); Review Comment: Fixed by eliminating the committed temporary blob. Upload-scoped blocks remain uncommitted and invisible to prefix scans until Put Block List atomically publishes the final key, so there is no scan-visible staging key or cleanup duplicate. ########## fe/fe-filesystem/fe-filesystem-azure/src/main/java/org/apache/doris/filesystem/azure/AzureObjStorage.java: ########## @@ -244,15 +244,31 @@ public void completeMultipartUpload(String remotePath, String uploadId, List<UploadPartResult> parts) throws IOException { try { AzureUri uri = AzureUri.parse(remotePath); - BlockBlobClient blockBlobClient = getClient().getBlobContainerClient(uri.container()) - .getBlobClient(uri.key()).getBlockBlobClient(); + BlobContainerClient containerClient = getClient().getBlobContainerClient(uri.container()); List<String> blockIds = new ArrayList<>(); List<UploadPartResult> sorted = new ArrayList<>(parts); sorted.sort((a, b) -> Integer.compare(a.partNumber(), b.partNumber())); + boolean exactBlockIds = !sorted.isEmpty() && sorted.stream() + .allMatch(part -> part.etag() != null && !part.etag().isEmpty()); for (UploadPartResult part : sorted) { - blockIds.add(toBlockId(part.partNumber())); + // A mixed-version upload must use one namespace consistently; new BEs also stage legacy IDs. + blockIds.add(exactBlockIds ? part.etag() : toBlockId(part.partNumber())); + } + String commitKey = exactBlockIds ? multipartTempKey(uri.key(), uploadId) : uri.key(); + BlobClient commitBlob = containerClient.getBlobClient(commitKey); + commitBlob.getBlockBlobClient().commitBlockList(blockIds); + if (exactBlockIds) { + BlobClient targetBlob = containerClient.getBlobClient(uri.key()); + // The temporary blob is the provider-visible writer fence; only a completed copy publishes it. + targetBlob.beginCopy(commitBlob.getBlobUrl(), null).waitForCompletion(); Review Comment: Fixed by removing the copy/poller protocol entirely. Completion now returns success only from the direct Put Block List request on the target, so there is no terminal copy status to ignore and no temporary committed blob to delete after a failed copy. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
