You are viewing a plain text version of this content. The canonical link for it is here.
Posted to gitbox@hive.apache.org by "ayushtkn (via GitHub)" <gi...@apache.org> on 2023/11/23 10:58:02 UTC

[PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

ayushtkn opened a new pull request, #4897:
URL: https://github.com/apache/hive/pull/4897

   ### What changes were proposed in this pull request?
   
   Implement delete orphan files
   
   ### Why are the changes needed?
   
   To clean orphan files.
   
   ### Does this PR introduce _any_ user-facing change?
   
   adds a delete orphan files query for iceberg tables
   
   ### Is the change a dependency upgrade?
   
   No.
   
   ### How was this patch tested?
   
   UT


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4897:
URL: https://github.com/apache/hive/pull/4897#issuecomment-1824398442

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4897)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [17 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarsource.com/sonarcloud/appendices/scanner-environment/)
   
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4897:
URL: https://github.com/apache/hive/pull/4897#issuecomment-1826864649

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4897)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [9 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarsource.com/sonarcloud/appendices/scanner-environment/)
   
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "ayushtkn (via GitHub)" <gi...@apache.org>.
ayushtkn commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1403921601


##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java:
##########
@@ -850,12 +851,44 @@ public void executeOperation(org.apache.hadoop.hive.ql.metadata.Table hmsTable,
         IcebergTableUtil.performMetadataDelete(icebergTable, deleteMetadataSpec.getBranchName(),
             deleteMetadataSpec.getSarg());
         break;
+      case DELETE_ORPHAN_FILES:

Review Comment:
   Theoretically yes, it has to store Path strings. I am not sure how much memory that can take, but if you see Hive Replication, It launches Distcp per table, so that does listing for each table in the Hs2 only, so that doesn't choke, & launch MR jobs for copy, not for listing.
   
   I did some benchmarking stuff there, so for ~3.8 million it was taking about 250-300 mb, but there it stores some more stuff as well, so here it should be less.
   
   Yep, but we can explore having a Tez job, I don't have a clear idea how we can get it done via that route, but I will create a follow-up & discuss with folks & figure out a way :-) 



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "zhangbutao (via GitHub)" <gi...@apache.org>.
zhangbutao commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1403851700


##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java:
##########
@@ -850,12 +851,44 @@ public void executeOperation(org.apache.hadoop.hive.ql.metadata.Table hmsTable,
         IcebergTableUtil.performMetadataDelete(icebergTable, deleteMetadataSpec.getBranchName(),
             deleteMetadataSpec.getSarg());
         break;
+      case DELETE_ORPHAN_FILES:

Review Comment:
   It means we regard the `Delete Orphan Files` action as a metadata operation, so all the delete operation is done by HS2.
    If the iceberg table has big data and many orphan files, will the HS2 suffer from performance issue? Can we lauch tez task to delete orphan files?



##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java:
##########
@@ -850,12 +851,44 @@ public void executeOperation(org.apache.hadoop.hive.ql.metadata.Table hmsTable,
         IcebergTableUtil.performMetadataDelete(icebergTable, deleteMetadataSpec.getBranchName(),
             deleteMetadataSpec.getSarg());
         break;
+      case DELETE_ORPHAN_FILES:
+        int numDeleteThreads = conf.getInt(HiveConf.ConfVars.HIVE_ICEBERG_EXPIRE_SNAPSHOT_NUMTHREADS.varname,
+            HiveConf.ConfVars.HIVE_ICEBERG_EXPIRE_SNAPSHOT_NUMTHREADS.defaultIntVal);
+        AlterTableExecuteSpec.DeleteOrphanFilesDesc deleteOrphanFilesSpec =
+            (AlterTableExecuteSpec.DeleteOrphanFilesDesc) executeSpec.getOperationParams();
+        deleteOrphanFiles(icebergTable, deleteOrphanFilesSpec.getTimestampMillis(), numDeleteThreads);
+        break;
       default:
         throw new UnsupportedOperationException(
             String.format("Operation type %s is not supported", executeSpec.getOperationType().name()));
     }
   }
 
+  private void deleteOrphanFiles(Table icebergTable, long timestampMillis, int numThreads) {
+    ExecutorService deleteExecutorService = null;
+    try {
+      if (numThreads > 0) {
+        LOG.info("Executing delete orphan files on iceberg table {} with {} threads", icebergTable.name(), numThreads);
+        deleteExecutorService = getDeleteExecutorService(icebergTable.name(), numThreads);
+      }
+
+      HiveIcebergDeleteOrphanFiles deleteOrphanFiles = new HiveIcebergDeleteOrphanFiles(conf, icebergTable);
+      deleteOrphanFiles.olderThan(timestampMillis);
+      if (deleteExecutorService != null) {
+        deleteOrphanFiles.olderThan(timestampMillis);
+      }

Review Comment:
   Line 876 and Line 878 have a same code: `deleteOrphanFiles.olderThan(timestampMillis);`
   Why?



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4897:
URL: https://github.com/apache/hive/pull/4897#issuecomment-1825179847

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4897)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [9 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarsource.com/sonarcloud/appendices/scanner-environment/)
   
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "zhangbutao (via GitHub)" <gi...@apache.org>.
zhangbutao commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1405832380


##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/actions/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive.actions;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));

Review Comment:
   At present, we clean both metadata files and data files. Should we give a option to let users to decide which location to delete. It looks like spark-iceberg has done this. I personally think it is usefull as this can relieve hs2 pressure if only cleaning partial location.
   But we can improve the feature later.



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "ayushtkn (via GitHub)" <gi...@apache.org>.
ayushtkn commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1407276282


##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/actions/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive.actions;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));

Review Comment:
   makes sense, I will create a ticket for that, thx



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "sonarcloud[bot] (via GitHub)" <gi...@apache.org>.
sonarcloud[bot] commented on PR #4897:
URL: https://github.com/apache/hive/pull/4897#issuecomment-1824860793

   Kudos, SonarCloud Quality Gate passed!&nbsp; &nbsp; [![Quality Gate passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/passed-16px.png 'Quality Gate passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=4897)
   
   [![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=BUG)  
   [![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=VULNERABILITY)  
   [![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT) [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=4897&resolved=false&types=SECURITY_HOTSPOT)  
   [![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL) [9 Code Smells](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=4897&resolved=false&types=CODE_SMELL)
   
   [![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=coverage&view=list) No Coverage information  
   [![No Duplication information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/NoDuplicationInfo-16px.png 'No Duplication information')](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=4897&metric=duplicated_lines_density&view=list) No Duplication information
   
   ![warning](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/message_warning-16px.png 'warning') The version of Java (11.0.8) you have used to run this analysis is deprecated and we will stop accepting it soon. Please update to at least Java 17.
   Read more [here](https://docs.sonarsource.com/sonarcloud/appendices/scanner-environment/)
   
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "ayushtkn (via GitHub)" <gi...@apache.org>.
ayushtkn merged PR #4897:
URL: https://github.com/apache/hive/pull/4897


-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "zhangbutao (via GitHub)" <gi...@apache.org>.
zhangbutao commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1405347851


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/AlterTableExecuteSpec.java:
##########
@@ -270,4 +271,27 @@ public SearchArgument getSarg() {
       return sarg;
     }
   }
+
+    /**
+   * Value object class, that stores the delete orphan files operation specific parameters.
+   * <ul>
+   *   <li>timestampMillis: the time before which files should be considered to be deleted</li>
+   * </ul>
+   */
+    public static class DeleteOrphanFilesDesc {
+    private final long timestampMillis;
+
+    public DeleteOrphanFilesDesc(long timestampMillis) {
+      this.timestampMillis = timestampMillis;

Review Comment:
   What will happen if timestampMillis is < 0?



##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation = null;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));
+
+    LOG.debug("Deleting {} files while cleaning orphan files for {}", result.deletedFiles, table.name());
+    Tasks.foreach(result.deletedFiles).executeWith(deleteExecutorService).retry(3)
+        .stopRetryOn(FileNotFoundException.class).suppressFailureWhenFinished().onFailure((file, thrown) ->
+          LOG.warn("Delete failed for file: {}", file, thrown)).run(deleteFunc::accept);
+    return result;
+  }
+
+  private Set<String> cleanContentFiles(long lastTime) {
+    Set<String> validFiles = Sets.union(getAllContentFilePath(), getAllStatisticsFilePath(table));
+    LOG.debug("Valid content file for {} are {}", table.name(), validFiles);
+    try {
+      Path dataPath = new Path(tableLocation, DATA_FOLDER_NAME);
+      return getFilesToBeDeleted(lastTime, validFiles, dataPath);
+    } catch (IOException ex) {
+      throw new UncheckedIOException(ex);
+    }
+  }
+
+  public Set<String> getAllContentFilePath() {
+    Set<String> validFilesPath = Sets.newHashSet();
+    Table metadatTable = getMetadataTable();
+
+    TableScan tableScan = metadatTable.newScan();
+    CloseableIterable<FileScanTask> manifestFileScanTasks = tableScan.planFiles();
+    CloseableIterable<StructLike> entries = CloseableIterable.concat(entriesOfManifest(manifestFileScanTasks));
+
+    for (StructLike entry : entries) {
+      StructLike fileRecord = entry.get(4, StructLike.class);
+      String filePath = fileRecord.get(1, String.class);
+      validFilesPath.add(getUriPath(filePath));
+    }
+    return validFilesPath;
+  }
+
+  private Iterable<CloseableIterable<StructLike>> entriesOfManifest(
+      CloseableIterable<FileScanTask> fileScanTasks) {
+    return Iterables.transform(
+        fileScanTasks,
+        task -> {
+          assert task != null;
+          return ((DataTask) task).rows();
+        });
+  }
+
+  public static Set<String> getAllStatisticsFilePath(Table table) {
+    return ReachableFileUtil.statisticsFilesLocations(table).stream().map(HiveIcebergDeleteOrphanFiles::getUriPath)
+        .collect(Collectors.toSet());
+  }
+
+  protected Set<String> cleanMetadata(long lastTime) {
+    LOG.info("{} start clean metadata files", table.name());
+    try {
+      Set<String> validFiles = getValidMetadataFiles(table);
+      LOG.debug("Valid metadata files for {} are {}", table.name(), validFiles);
+      Path metadataLocation = new Path(tableLocation, METADATA_FOLDER_NAME);
+      return getFilesToBeDeleted(lastTime, validFiles, metadataLocation);
+    } catch (IOException ioe) {
+      throw new UncheckedIOException(ioe);
+    }
+  }
+
+  private Set<String> getFilesToBeDeleted(long lastTime, Set<String> validFiles, Path location)
+      throws IOException {
+    Set<String> filesToDelete = Sets.newHashSet();
+    FileSystem fs = location.getFileSystem(conf);
+    RemoteIterator<LocatedFileStatus> metadataLocations = fs.listFiles(location, true);
+    while (metadataLocations.hasNext()) {
+      LocatedFileStatus metadataFile = metadataLocations.next();
+      if (metadataFile.getModificationTime() < lastTime && !validFiles.contains(
+          getUriPath(metadataFile.getPath().toString()))) {
+        filesToDelete.add(metadataFile.getPath().toString());
+      }
+    }
+    return filesToDelete;
+  }
+
+  private Table getMetadataTable() {
+    return MetadataTableUtils.createMetadataTableInstance(((HasTableOperations) table).operations(), table.name(),
+        table.name() + "#" + ALL_ENTRIES.name(), ALL_ENTRIES);
+  }
+
+  private static Set<String> getValidMetadataFiles(Table internalTable) {

Review Comment:
   What's the meaning of `internalTable`?



##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {

Review Comment:
   Should we use a new package for these iceberg action? such as `org.apache.iceberg.mr.hive.actions`
   Then we can add more actions in this package later.



##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation = null;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));
+
+    LOG.debug("Deleting {} files while cleaning orphan files for {}", result.deletedFiles, table.name());
+    Tasks.foreach(result.deletedFiles).executeWith(deleteExecutorService).retry(3)
+        .stopRetryOn(FileNotFoundException.class).suppressFailureWhenFinished().onFailure((file, thrown) ->
+          LOG.warn("Delete failed for file: {}", file, thrown)).run(deleteFunc::accept);
+    return result;
+  }
+
+  private Set<String> cleanContentFiles(long lastTime) {
+    Set<String> validFiles = Sets.union(getAllContentFilePath(), getAllStatisticsFilePath(table));
+    LOG.debug("Valid content file for {} are {}", table.name(), validFiles);

Review Comment:
   `validFiles` maybe a very long character if table has many files. Maybe we can use its size instead?



##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation = null;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));
+
+    LOG.debug("Deleting {} files while cleaning orphan files for {}", result.deletedFiles, table.name());

Review Comment:
   `result.deletedFiles` maybe a very long character if table has many orphan files. Maybe we can use its size instead?



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "ayushtkn (via GitHub)" <gi...@apache.org>.
ayushtkn commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1405438725


##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation = null;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));
+
+    LOG.debug("Deleting {} files while cleaning orphan files for {}", result.deletedFiles, table.name());
+    Tasks.foreach(result.deletedFiles).executeWith(deleteExecutorService).retry(3)
+        .stopRetryOn(FileNotFoundException.class).suppressFailureWhenFinished().onFailure((file, thrown) ->
+          LOG.warn("Delete failed for file: {}", file, thrown)).run(deleteFunc::accept);
+    return result;
+  }
+
+  private Set<String> cleanContentFiles(long lastTime) {
+    Set<String> validFiles = Sets.union(getAllContentFilePath(), getAllStatisticsFilePath(table));
+    LOG.debug("Valid content file for {} are {}", table.name(), validFiles);
+    try {
+      Path dataPath = new Path(tableLocation, DATA_FOLDER_NAME);
+      return getFilesToBeDeleted(lastTime, validFiles, dataPath);
+    } catch (IOException ex) {
+      throw new UncheckedIOException(ex);
+    }
+  }
+
+  public Set<String> getAllContentFilePath() {
+    Set<String> validFilesPath = Sets.newHashSet();
+    Table metadatTable = getMetadataTable();
+
+    TableScan tableScan = metadatTable.newScan();
+    CloseableIterable<FileScanTask> manifestFileScanTasks = tableScan.planFiles();
+    CloseableIterable<StructLike> entries = CloseableIterable.concat(entriesOfManifest(manifestFileScanTasks));
+
+    for (StructLike entry : entries) {
+      StructLike fileRecord = entry.get(4, StructLike.class);
+      String filePath = fileRecord.get(1, String.class);
+      validFilesPath.add(getUriPath(filePath));
+    }
+    return validFilesPath;
+  }
+
+  private Iterable<CloseableIterable<StructLike>> entriesOfManifest(
+      CloseableIterable<FileScanTask> fileScanTasks) {
+    return Iterables.transform(
+        fileScanTasks,
+        task -> {
+          assert task != null;
+          return ((DataTask) task).rows();
+        });
+  }
+
+  public static Set<String> getAllStatisticsFilePath(Table table) {
+    return ReachableFileUtil.statisticsFilesLocations(table).stream().map(HiveIcebergDeleteOrphanFiles::getUriPath)
+        .collect(Collectors.toSet());
+  }
+
+  protected Set<String> cleanMetadata(long lastTime) {
+    LOG.info("{} start clean metadata files", table.name());
+    try {
+      Set<String> validFiles = getValidMetadataFiles(table);
+      LOG.debug("Valid metadata files for {} are {}", table.name(), validFiles);
+      Path metadataLocation = new Path(tableLocation, METADATA_FOLDER_NAME);
+      return getFilesToBeDeleted(lastTime, validFiles, metadataLocation);
+    } catch (IOException ioe) {
+      throw new UncheckedIOException(ioe);
+    }
+  }
+
+  private Set<String> getFilesToBeDeleted(long lastTime, Set<String> validFiles, Path location)
+      throws IOException {
+    Set<String> filesToDelete = Sets.newHashSet();
+    FileSystem fs = location.getFileSystem(conf);
+    RemoteIterator<LocatedFileStatus> metadataLocations = fs.listFiles(location, true);
+    while (metadataLocations.hasNext()) {
+      LocatedFileStatus metadataFile = metadataLocations.next();
+      if (metadataFile.getModificationTime() < lastTime && !validFiles.contains(
+          getUriPath(metadataFile.getPath().toString()))) {
+        filesToDelete.add(metadataFile.getPath().toString());
+      }
+    }
+    return filesToDelete;
+  }
+
+  private Table getMetadataTable() {
+    return MetadataTableUtils.createMetadataTableInstance(((HasTableOperations) table).operations(), table.name(),
+        table.name() + "#" + ALL_ENTRIES.name(), ALL_ENTRIES);
+  }
+
+  private static Set<String> getValidMetadataFiles(Table internalTable) {

Review Comment:
   I changed it icebergTable, no special meaning, it is the normal table, not sure why I did that :-) 



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "ayushtkn (via GitHub)" <gi...@apache.org>.
ayushtkn commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1405438665


##########
ql/src/java/org/apache/hadoop/hive/ql/parse/AlterTableExecuteSpec.java:
##########
@@ -270,4 +271,27 @@ public SearchArgument getSarg() {
       return sarg;
     }
   }
+
+    /**
+   * Value object class, that stores the delete orphan files operation specific parameters.
+   * <ul>
+   *   <li>timestampMillis: the time before which files should be considered to be deleted</li>
+   * </ul>
+   */
+    public static class DeleteOrphanFilesDesc {
+    private final long timestampMillis;
+
+    public DeleteOrphanFilesDesc(long timestampMillis) {
+      this.timestampMillis = timestampMillis;

Review Comment:
   I added a PreCondition above to check that, I am not sure if toEpochMillis can be -ve or not, but better to be safe



##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation = null;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));
+
+    LOG.debug("Deleting {} files while cleaning orphan files for {}", result.deletedFiles, table.name());

Review Comment:
   Done



##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {
+
+  public static final String METADATA_FOLDER_NAME = "metadata";
+  public static final String DATA_FOLDER_NAME = "data";
+  private static final Logger LOG = LoggerFactory.getLogger(HiveIcebergDeleteOrphanFiles.class);
+  private String tableLocation = null;
+  private long olderThanTimestamp = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3);
+  private Consumer<String> deleteFunc;
+  private ExecutorService deleteExecutorService = MoreExecutors.newDirectExecutorService();
+
+  private final Configuration conf;
+  private final Table table;
+
+  public HiveIcebergDeleteOrphanFiles(Configuration conf, Table table) {
+    this.conf = conf;
+    this.table = table;
+    this.deleteFunc = file -> table.io().deleteFile(file);
+    this.tableLocation = table.location();
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles location(String location) {
+    this.tableLocation = location;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles olderThan(long newOlderThanTimestamp) {
+    this.olderThanTimestamp = newOlderThanTimestamp;
+    return this;
+  }
+
+  // TODO: Implement later, if there is any use case.
+  @Override
+  public HiveIcebergDeleteOrphanFiles deleteWith(Consumer<String> newDeleteFunc) {
+    this.deleteFunc = newDeleteFunc;
+    return this;
+  }
+
+  @Override
+  public HiveIcebergDeleteOrphanFiles executeDeleteWith(ExecutorService executorService) {
+    this.deleteExecutorService = executorService;
+    return this;
+  }
+
+  @Override
+  public Result execute() {
+    LOG.info("Cleaning orphan files for {}", table.name());
+    HiveIcebergDeleteOrphanFilesResult result = new HiveIcebergDeleteOrphanFilesResult();
+    result.addDeletedFiles(cleanContentFiles(olderThanTimestamp));
+    result.addDeletedFiles(cleanMetadata(olderThanTimestamp));
+
+    LOG.debug("Deleting {} files while cleaning orphan files for {}", result.deletedFiles, table.name());
+    Tasks.foreach(result.deletedFiles).executeWith(deleteExecutorService).retry(3)
+        .stopRetryOn(FileNotFoundException.class).suppressFailureWhenFinished().onFailure((file, thrown) ->
+          LOG.warn("Delete failed for file: {}", file, thrown)).run(deleteFunc::accept);
+    return result;
+  }
+
+  private Set<String> cleanContentFiles(long lastTime) {
+    Set<String> validFiles = Sets.union(getAllContentFilePath(), getAllStatisticsFilePath(table));
+    LOG.debug("Valid content file for {} are {}", table.name(), validFiles);

Review Comment:
   Done



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "ayushtkn (via GitHub)" <gi...@apache.org>.
ayushtkn commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1405438583


##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergDeleteOrphanFiles.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocatedFileStatus;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.RemoteIterator;
+import org.apache.iceberg.DataTask;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.MetadataTableUtils;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.StructLike;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.actions.DeleteOrphanFiles;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.relocated.com.google.common.util.concurrent.MoreExecutors;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.iceberg.MetadataTableType.ALL_ENTRIES;
+
+public class HiveIcebergDeleteOrphanFiles implements DeleteOrphanFiles {

Review Comment:
   Done



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-27906: Iceberg: Implement Delete Orphan Files. [hive]

Posted by "ayushtkn (via GitHub)" <gi...@apache.org>.
ayushtkn commented on code in PR #4897:
URL: https://github.com/apache/hive/pull/4897#discussion_r1403918576


##########
iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java:
##########
@@ -850,12 +851,44 @@ public void executeOperation(org.apache.hadoop.hive.ql.metadata.Table hmsTable,
         IcebergTableUtil.performMetadataDelete(icebergTable, deleteMetadataSpec.getBranchName(),
             deleteMetadataSpec.getSarg());
         break;
+      case DELETE_ORPHAN_FILES:
+        int numDeleteThreads = conf.getInt(HiveConf.ConfVars.HIVE_ICEBERG_EXPIRE_SNAPSHOT_NUMTHREADS.varname,
+            HiveConf.ConfVars.HIVE_ICEBERG_EXPIRE_SNAPSHOT_NUMTHREADS.defaultIntVal);
+        AlterTableExecuteSpec.DeleteOrphanFilesDesc deleteOrphanFilesSpec =
+            (AlterTableExecuteSpec.DeleteOrphanFilesDesc) executeSpec.getOperationParams();
+        deleteOrphanFiles(icebergTable, deleteOrphanFilesSpec.getTimestampMillis(), numDeleteThreads);
+        break;
       default:
         throw new UnsupportedOperationException(
             String.format("Operation type %s is not supported", executeSpec.getOperationType().name()));
     }
   }
 
+  private void deleteOrphanFiles(Table icebergTable, long timestampMillis, int numThreads) {
+    ExecutorService deleteExecutorService = null;
+    try {
+      if (numThreads > 0) {
+        LOG.info("Executing delete orphan files on iceberg table {} with {} threads", icebergTable.name(), numThreads);
+        deleteExecutorService = getDeleteExecutorService(icebergTable.name(), numThreads);
+      }
+
+      HiveIcebergDeleteOrphanFiles deleteOrphanFiles = new HiveIcebergDeleteOrphanFiles(conf, icebergTable);
+      deleteOrphanFiles.olderThan(timestampMillis);
+      if (deleteExecutorService != null) {
+        deleteOrphanFiles.olderThan(timestampMillis);
+      }

Review Comment:
   copy-paste error, The plan was like in explire snapshot, if deleteExecutorService isn't null use that for delete



-- 
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: gitbox-unsubscribe@hive.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org