[GitHub] [carbondata] vikramahuja1001 opened a new pull request #4005: [WIP] Trash Folder support in carbondata

classic Classic list List threaded Threaded
147 messages Options
1 ... 45678
Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] CarbonDataQA2 commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox

CarbonDataQA2 commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736348873


   Build Failed  with Spark 2.3.4, Please check CI http://121.244.95.60:12545/job/ApacheCarbonPRBuilder2.3/4987/
   


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] vikramahuja1001 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

vikramahuja1001 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533261640



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,196 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.constants.CarbonCommonConstants;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+    throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = getStaleSegmentFiles(carbonTable);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = CarbonTablePath.DataFileUtil.getSegmentNoFromSegmentFile(
+          staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        // segmentLocation is the location in Fact/part0 where the segment is stored.
+        CarbonFile segmentLocation = FileFactory.getCarbonFile(carbonTable.getTablePath() +

Review comment:
       done

##########
File path: core/src/main/java/org/apache/carbondata/core/util/CarbonProperties.java
##########
@@ -2086,6 +2087,49 @@ public int getMaxSIRepairLimit(String dbName, String tableName) {
     return Math.abs(Integer.parseInt(thresholdValue));
   }
 
+  /**
+   * The below method returns the time(in milliseconds) for which timestamp folder retention in
+   * trash folder will take place.
+   */
+  public long getTrashFolderRetentionTime() {
+    long milliSecondsInADay = TimeUnit.DAYS.toMillis(1);
+    return (long)validateTrashFolderRetentionTime() * milliSecondsInADay;

Review comment:
       done

##########
File path: core/src/main/java/org/apache/carbondata/core/util/CarbonProperties.java
##########
@@ -2086,6 +2087,49 @@ public int getMaxSIRepairLimit(String dbName, String tableName) {
     return Math.abs(Integer.parseInt(thresholdValue));
   }
 
+  /**
+   * The below method returns the time(in milliseconds) for which timestamp folder retention in
+   * trash folder will take place.
+   */
+  public long getTrashFolderRetentionTime() {
+    long milliSecondsInADay = TimeUnit.DAYS.toMillis(1);
+    return (long)validateTrashFolderRetentionTime() * milliSecondsInADay;
+  }
+
+  /**
+   * The below method returns the time(in days) for which timestamp folder retention in trash
+   * folder will take place
+   */
+  private int validateTrashFolderRetentionTime() {

Review comment:
       done

##########
File path: core/src/main/java/org/apache/carbondata/core/util/DeleteLoadFolders.java
##########
@@ -183,16 +186,18 @@ private static boolean checkIfLoadCanBeDeleted(LoadMetadataDetails oneLoad,
         return true;
       }
       long deletionTime = oneLoad.getModificationOrDeletionTimestamp();
-
+      if (isCleanFilesOperation) {

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.

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] CarbonDataQA2 commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

CarbonDataQA2 commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736502949


   Build Failed  with Spark 2.3.4, Please check CI http://121.244.95.60:12545/job/ApacheCarbonPRBuilder2.3/4989/
   


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] CarbonDataQA2 commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

CarbonDataQA2 commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736507588


   Build Failed  with Spark 2.4.5, Please check CI http://121.244.95.60:12545/job/ApacheCarbon_PR_Builder_2.4.5/3234/
   


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] QiangCai commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

QiangCai commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533390359



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,223 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+import org.apache.carbondata.core.util.path.CarbonTablePath.DataFileUtil;
+
+import javafx.util.Pair;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+    throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    Pair<List<String>, List<String>> staleSegmentFiles = getStaleSegmentFiles(carbonTable);
+    for (String staleSegmentFile : staleSegmentFiles.getKey()) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        if (locationMap.entrySet().iterator().next().getValue().isRelative()) {
+          CarbonFile segmentPath = FileFactory.getCarbonFile(CarbonTablePath.getSegmentPath(
+              carbonTable.getTablePath(), segmentNumber));
+          // copy the complete segment to the trash folder
+          TrashUtil.copySegmentToTrash(segmentPath, TrashUtil.getCompleteTrashFolderPath(
+              carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber));
+          // Deleting the stale Segment folders and the segment file.
+          try {
+            CarbonUtil.deleteFoldersAndFiles(segmentPath);
+            // delete the segment file as well
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                staleSegmentFile));
+            for (String duplicateStaleSegmentFile : staleSegmentFiles.getValue()) {
+              if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+                  .equals(segmentNumber)) {
+                FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable
+                    .getTablePath(), duplicateStaleSegmentFile));
+              }
+            }
+          } catch (IOException | InterruptedException e) {
+            LOGGER.error("Unable to delete the segment: " + segmentPath + " from after moving" +
+                " it to the trash folder. Please delete them manually : " + e.getMessage(), e);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will clean all the stale segments for partition table, delete the source folders
+   * after copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegmentsForPartitionTable(CarbonTable carbonTable)
+    throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    Pair<List<String>, List<String>> staleSegmentFiles = getStaleSegmentFiles(carbonTable);
+    for (String staleSegmentFile : staleSegmentFiles.getKey()) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      // for each segment we get the indexfile first, then we get the carbondata file. Move both
+      // of those to trash folder
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      List<String> filesToProcess = fileStore.readIndexFiles(SegmentStatus.SUCCESS, true,
+          FileFactory.getConfiguration());
+
+      // get carbondata files from here
+      Map<String, List<String>> indexFilesMap = fileStore.getIndexFilesMap();
+      for (Map.Entry<String, List<String>> entry : indexFilesMap.entrySet()) {
+        filesToProcess.addAll(entry.getValue());
+      }
+      // After all the files have been added to list, move them to the trash folder
+      TrashUtil.copyFilesToTrash(filesToProcess, TrashUtil.getCompleteTrashFolderPath(
+          carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber), segmentNumber);
+      // After every file of that segment has been copied, need to delete those files.
+      try {
+        for (String file : filesToProcess) {
+          FileFactory.deleteFile(file);
+        }
+        // Delete the segment file too
+        FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+            staleSegmentFile));
+        // remove duplicate segment files if any
+        for (String duplicateStaleSegmentFile : staleSegmentFiles.getValue()) {
+          if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+              .equals(segmentNumber)) {
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                duplicateStaleSegmentFile));
+          }
+        }
+      } catch (IOException e) {
+        LOGGER.error("Error while deleting the source data files. Please delete the files of" +
+            " segment: " + segmentNumber + " manually.", e);
+      }
+    }
+    // Delete the empty partition folders
+    deleteEmptyPartitionFoldersRecursively(FileFactory.getCarbonFile(carbonTable.getTablePath()));
+  }
+
+  /**
+   * This method will find all the stale segments by comparing the segment files in the
+   * metadata directory with the segments in the table status file. Any segment which has entry
+   * in the metadata folder and is not present in the table status file is considered as a
+   * stale segment. Only comparing from tablestatus file, not checking tablestatus.history file
+   */
+  private static Pair<List<String>, List<String>> getStaleSegmentFiles(CarbonTable carbonTable) {
+    // details contains segments in the tablestatus file, and all segments contains segments files.
+    // Segment number from those segment files is extracted and Stale segement file name is
+    // returned.
+    String segmentFilesLocation =
+        CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+    Pair<List<String>, List<String>> segmentFileNameList = getSegmentFiles(segmentFilesLocation);
+    ArrayList<String> staleSegmentList = new ArrayList<>(segmentFileNameList.getKey().size());
+    // there are no segments present in the Metadata folder. Can return here
+    if (segmentFileNameList.getKey().size() == 0) {
+      return segmentFileNameList;
+    }
+    LoadMetadataDetails[] details = SegmentStatusManager.readLoadMetadata(carbonTable
+        .getMetadataPath());
+    Set<String> loadNameSet = Arrays.stream(details).map(loadMetadataDetails -> loadMetadataDetails
+        .getLoadName()).collect(Collectors.toSet());
+    for (String segmentFileName : segmentFileNameList.getKey()) {
+      if (!loadNameSet.contains(DataFileUtil.getSegmentNoFromSegmentFile(
+          segmentFileName))) {
+        staleSegmentList.add(segmentFileName);
+      }
+    }
+    List<String> redundantSegmentFile = new ArrayList<>(segmentFileNameList.getValue().size());
+    for (String segmentFileName : segmentFileNameList.getValue()) {
+      if (!loadNameSet.contains(DataFileUtil.getSegmentNoFromSegmentFile(
+          segmentFileName))) {
+        redundantSegmentFile.add(segmentFileName);
+      }
+    }
+    return new Pair<>(staleSegmentList, redundantSegmentFile);
+  }
+
+  /**
+   * This method will delete all the empty partition folders starting from the table path
+   */
+  public static void deleteEmptyPartitionFoldersRecursively(CarbonFile tablePath) {
+    CarbonFile[] listOfFiles = tablePath.listFiles();
+    if (listOfFiles.length == 0) {
+      tablePath.delete();
+    } else {
+      for (CarbonFile file: listOfFiles) {
+        if (file.isDirectory() && file.getName().contains("=")) {
+          deleteEmptyPartitionFoldersRecursively(file);
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will give the segment file names in the metadata folder after removing duplicates
+   * and will also return the duplicate segment files which are not required(the one with less
+   * than maximum timestamp)
+   */
+  public static Pair<List<String>, List<String>> getSegmentFiles(String segmentFileLocation) {

Review comment:
         public static void getSegmentFiles(String segmentFileLocation, List<String> ..., List<String> ...) {
   




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] QiangCai commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

QiangCai commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533390359



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,223 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+import org.apache.carbondata.core.util.path.CarbonTablePath.DataFileUtil;
+
+import javafx.util.Pair;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+    throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    Pair<List<String>, List<String>> staleSegmentFiles = getStaleSegmentFiles(carbonTable);
+    for (String staleSegmentFile : staleSegmentFiles.getKey()) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        if (locationMap.entrySet().iterator().next().getValue().isRelative()) {
+          CarbonFile segmentPath = FileFactory.getCarbonFile(CarbonTablePath.getSegmentPath(
+              carbonTable.getTablePath(), segmentNumber));
+          // copy the complete segment to the trash folder
+          TrashUtil.copySegmentToTrash(segmentPath, TrashUtil.getCompleteTrashFolderPath(
+              carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber));
+          // Deleting the stale Segment folders and the segment file.
+          try {
+            CarbonUtil.deleteFoldersAndFiles(segmentPath);
+            // delete the segment file as well
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                staleSegmentFile));
+            for (String duplicateStaleSegmentFile : staleSegmentFiles.getValue()) {
+              if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+                  .equals(segmentNumber)) {
+                FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable
+                    .getTablePath(), duplicateStaleSegmentFile));
+              }
+            }
+          } catch (IOException | InterruptedException e) {
+            LOGGER.error("Unable to delete the segment: " + segmentPath + " from after moving" +
+                " it to the trash folder. Please delete them manually : " + e.getMessage(), e);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will clean all the stale segments for partition table, delete the source folders
+   * after copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegmentsForPartitionTable(CarbonTable carbonTable)
+    throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    Pair<List<String>, List<String>> staleSegmentFiles = getStaleSegmentFiles(carbonTable);
+    for (String staleSegmentFile : staleSegmentFiles.getKey()) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      // for each segment we get the indexfile first, then we get the carbondata file. Move both
+      // of those to trash folder
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      List<String> filesToProcess = fileStore.readIndexFiles(SegmentStatus.SUCCESS, true,
+          FileFactory.getConfiguration());
+
+      // get carbondata files from here
+      Map<String, List<String>> indexFilesMap = fileStore.getIndexFilesMap();
+      for (Map.Entry<String, List<String>> entry : indexFilesMap.entrySet()) {
+        filesToProcess.addAll(entry.getValue());
+      }
+      // After all the files have been added to list, move them to the trash folder
+      TrashUtil.copyFilesToTrash(filesToProcess, TrashUtil.getCompleteTrashFolderPath(
+          carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber), segmentNumber);
+      // After every file of that segment has been copied, need to delete those files.
+      try {
+        for (String file : filesToProcess) {
+          FileFactory.deleteFile(file);
+        }
+        // Delete the segment file too
+        FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+            staleSegmentFile));
+        // remove duplicate segment files if any
+        for (String duplicateStaleSegmentFile : staleSegmentFiles.getValue()) {
+          if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+              .equals(segmentNumber)) {
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                duplicateStaleSegmentFile));
+          }
+        }
+      } catch (IOException e) {
+        LOGGER.error("Error while deleting the source data files. Please delete the files of" +
+            " segment: " + segmentNumber + " manually.", e);
+      }
+    }
+    // Delete the empty partition folders
+    deleteEmptyPartitionFoldersRecursively(FileFactory.getCarbonFile(carbonTable.getTablePath()));
+  }
+
+  /**
+   * This method will find all the stale segments by comparing the segment files in the
+   * metadata directory with the segments in the table status file. Any segment which has entry
+   * in the metadata folder and is not present in the table status file is considered as a
+   * stale segment. Only comparing from tablestatus file, not checking tablestatus.history file
+   */
+  private static Pair<List<String>, List<String>> getStaleSegmentFiles(CarbonTable carbonTable) {
+    // details contains segments in the tablestatus file, and all segments contains segments files.
+    // Segment number from those segment files is extracted and Stale segement file name is
+    // returned.
+    String segmentFilesLocation =
+        CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+    Pair<List<String>, List<String>> segmentFileNameList = getSegmentFiles(segmentFilesLocation);
+    ArrayList<String> staleSegmentList = new ArrayList<>(segmentFileNameList.getKey().size());
+    // there are no segments present in the Metadata folder. Can return here
+    if (segmentFileNameList.getKey().size() == 0) {
+      return segmentFileNameList;
+    }
+    LoadMetadataDetails[] details = SegmentStatusManager.readLoadMetadata(carbonTable
+        .getMetadataPath());
+    Set<String> loadNameSet = Arrays.stream(details).map(loadMetadataDetails -> loadMetadataDetails
+        .getLoadName()).collect(Collectors.toSet());
+    for (String segmentFileName : segmentFileNameList.getKey()) {
+      if (!loadNameSet.contains(DataFileUtil.getSegmentNoFromSegmentFile(
+          segmentFileName))) {
+        staleSegmentList.add(segmentFileName);
+      }
+    }
+    List<String> redundantSegmentFile = new ArrayList<>(segmentFileNameList.getValue().size());
+    for (String segmentFileName : segmentFileNameList.getValue()) {
+      if (!loadNameSet.contains(DataFileUtil.getSegmentNoFromSegmentFile(
+          segmentFileName))) {
+        redundantSegmentFile.add(segmentFileName);
+      }
+    }
+    return new Pair<>(staleSegmentList, redundantSegmentFile);
+  }
+
+  /**
+   * This method will delete all the empty partition folders starting from the table path
+   */
+  public static void deleteEmptyPartitionFoldersRecursively(CarbonFile tablePath) {
+    CarbonFile[] listOfFiles = tablePath.listFiles();
+    if (listOfFiles.length == 0) {
+      tablePath.delete();
+    } else {
+      for (CarbonFile file: listOfFiles) {
+        if (file.isDirectory() && file.getName().contains("=")) {
+          deleteEmptyPartitionFoldersRecursively(file);
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will give the segment file names in the metadata folder after removing duplicates
+   * and will also return the duplicate segment files which are not required(the one with less
+   * than maximum timestamp)
+   */
+  public static Pair<List<String>, List<String>> getSegmentFiles(String segmentFileLocation) {

Review comment:
         public static void collectSegmentFiles(String segmentFileLocation, List<String> ..., List<String> ...) {
   




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] CarbonDataQA2 commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

CarbonDataQA2 commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736569211


   Build Failed  with Spark 2.3.4, Please check CI http://121.244.95.60:12545/job/ApacheCarbonPRBuilder2.3/4991/
   


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] CarbonDataQA2 commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

CarbonDataQA2 commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736570532


   Build Success with Spark 2.4.5, Please check CI http://121.244.95.60:12545/job/ApacheCarbon_PR_Builder_2.4.5/3236/
   


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] CarbonDataQA2 commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

CarbonDataQA2 commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736639647


   Build Success with Spark 2.3.4, Please check CI http://121.244.95.60:12545/job/ApacheCarbonPRBuilder2.3/4995/
   


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] CarbonDataQA2 commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

CarbonDataQA2 commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736640874


   Build Success with Spark 2.4.5, Please check CI http://121.244.95.60:12545/job/ApacheCarbon_PR_Builder_2.4.5/3240/
   


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] QiangCai commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

QiangCai commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736650399


   LGTM


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] ajantha-bhat commented on pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

ajantha-bhat commented on pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#issuecomment-736668554


   LGTM


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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533593984



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,205 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+import org.apache.carbondata.core.util.path.CarbonTablePath.DataFileUtil;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        if (locationMap.entrySet().iterator().next().getValue().isRelative()) {
+          CarbonFile segmentPath = FileFactory.getCarbonFile(CarbonTablePath.getSegmentPath(
+              carbonTable.getTablePath(), segmentNumber));
+          // copy the complete segment to the trash folder
+          TrashUtil.copySegmentToTrash(segmentPath, TrashUtil.getCompleteTrashFolderPath(
+              carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber));
+          // Deleting the stale Segment folders and the segment file.
+          try {
+            CarbonUtil.deleteFoldersAndFiles(segmentPath);
+            // delete the segment file as well
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                staleSegmentFile));
+            for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+              if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+                  .equals(segmentNumber)) {
+                FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable
+                    .getTablePath(), duplicateStaleSegmentFile));
+              }
+            }
+          } catch (IOException | InterruptedException e) {
+            LOGGER.error("Unable to delete the segment: " + segmentPath + " from after moving" +
+                " it to the trash folder. Please delete them manually : " + e.getMessage(), e);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will clean all the stale segments for partition table, delete the source folders
+   * after copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegmentsForPartitionTable(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      // for each segment we get the indexfile first, then we get the carbondata file. Move both
+      // of those to trash folder
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      List<String> filesToProcess = fileStore.readIndexFiles(SegmentStatus.SUCCESS, true,
+          FileFactory.getConfiguration());
+
+      // get carbondata files from here
+      Map<String, List<String>> indexFilesMap = fileStore.getIndexFilesMap();
+      for (Map.Entry<String, List<String>> entry : indexFilesMap.entrySet()) {
+        filesToProcess.addAll(entry.getValue());
+      }
+      // After all the files have been added to list, move them to the trash folder
+      TrashUtil.copyFilesToTrash(filesToProcess, TrashUtil.getCompleteTrashFolderPath(
+          carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber), segmentNumber);
+      // After every file of that segment has been copied, need to delete those files.
+      try {
+        for (String file : filesToProcess) {
+          FileFactory.deleteFile(file);
+        }
+        // Delete the segment file too
+        FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+            staleSegmentFile));
+        // remove duplicate segment files if any
+        for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+          if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+              .equals(segmentNumber)) {
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                duplicateStaleSegmentFile));
+          }
+        }
+      } catch (IOException e) {
+        LOGGER.error("Error while deleting the source data files. Please delete the files of" +
+            " segment: " + segmentNumber + " manually.", e);
+      }
+    }
+    // Delete the empty partition folders
+    deleteEmptyPartitionFoldersRecursively(FileFactory.getCarbonFile(carbonTable.getTablePath()));
+  }
+
+  /**
+   * This method will find all the stale segments by comparing the segment files in the
+   * metadata directory with the segments in the table status file. Any segment which has entry
+   * in the metadata folder and is not present in the table status file is considered as a
+   * stale segment. Only comparing from tablestatus file, not checking tablestatus.history file
+   */
+  private static void getStaleSegmentFiles(CarbonTable carbonTable, List<String> staleSegmentFiles,
+      List<String> redundantSegmentFile) {
+    String segmentFilesLocation =
+        CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+    List<String> segmentFiles = Arrays.stream(FileFactory.getCarbonFile(segmentFilesLocation)
+        .listFiles()).map(segmentFile -> segmentFile.getName()).collect(Collectors
+        .toList());
+    // there are no segments present in the Metadata folder. Can return here
+    if (segmentFiles.size() == 0) {
+      return;
+    }
+    ArrayList<String> staleSegments = new ArrayList<>(staleSegmentFiles.size());

Review comment:
       instead of creating new list, can you use stream.map and collect the list?




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533593984



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,205 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+import org.apache.carbondata.core.util.path.CarbonTablePath.DataFileUtil;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        if (locationMap.entrySet().iterator().next().getValue().isRelative()) {
+          CarbonFile segmentPath = FileFactory.getCarbonFile(CarbonTablePath.getSegmentPath(
+              carbonTable.getTablePath(), segmentNumber));
+          // copy the complete segment to the trash folder
+          TrashUtil.copySegmentToTrash(segmentPath, TrashUtil.getCompleteTrashFolderPath(
+              carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber));
+          // Deleting the stale Segment folders and the segment file.
+          try {
+            CarbonUtil.deleteFoldersAndFiles(segmentPath);
+            // delete the segment file as well
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                staleSegmentFile));
+            for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+              if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+                  .equals(segmentNumber)) {
+                FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable
+                    .getTablePath(), duplicateStaleSegmentFile));
+              }
+            }
+          } catch (IOException | InterruptedException e) {
+            LOGGER.error("Unable to delete the segment: " + segmentPath + " from after moving" +
+                " it to the trash folder. Please delete them manually : " + e.getMessage(), e);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will clean all the stale segments for partition table, delete the source folders
+   * after copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegmentsForPartitionTable(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      // for each segment we get the indexfile first, then we get the carbondata file. Move both
+      // of those to trash folder
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      List<String> filesToProcess = fileStore.readIndexFiles(SegmentStatus.SUCCESS, true,
+          FileFactory.getConfiguration());
+
+      // get carbondata files from here
+      Map<String, List<String>> indexFilesMap = fileStore.getIndexFilesMap();
+      for (Map.Entry<String, List<String>> entry : indexFilesMap.entrySet()) {
+        filesToProcess.addAll(entry.getValue());
+      }
+      // After all the files have been added to list, move them to the trash folder
+      TrashUtil.copyFilesToTrash(filesToProcess, TrashUtil.getCompleteTrashFolderPath(
+          carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber), segmentNumber);
+      // After every file of that segment has been copied, need to delete those files.
+      try {
+        for (String file : filesToProcess) {
+          FileFactory.deleteFile(file);
+        }
+        // Delete the segment file too
+        FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+            staleSegmentFile));
+        // remove duplicate segment files if any
+        for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+          if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+              .equals(segmentNumber)) {
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                duplicateStaleSegmentFile));
+          }
+        }
+      } catch (IOException e) {
+        LOGGER.error("Error while deleting the source data files. Please delete the files of" +
+            " segment: " + segmentNumber + " manually.", e);
+      }
+    }
+    // Delete the empty partition folders
+    deleteEmptyPartitionFoldersRecursively(FileFactory.getCarbonFile(carbonTable.getTablePath()));
+  }
+
+  /**
+   * This method will find all the stale segments by comparing the segment files in the
+   * metadata directory with the segments in the table status file. Any segment which has entry
+   * in the metadata folder and is not present in the table status file is considered as a
+   * stale segment. Only comparing from tablestatus file, not checking tablestatus.history file
+   */
+  private static void getStaleSegmentFiles(CarbonTable carbonTable, List<String> staleSegmentFiles,
+      List<String> redundantSegmentFile) {
+    String segmentFilesLocation =
+        CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+    List<String> segmentFiles = Arrays.stream(FileFactory.getCarbonFile(segmentFilesLocation)
+        .listFiles()).map(segmentFile -> segmentFile.getName()).collect(Collectors
+        .toList());
+    // there are no segments present in the Metadata folder. Can return here
+    if (segmentFiles.size() == 0) {
+      return;
+    }
+    ArrayList<String> staleSegments = new ArrayList<>(staleSegmentFiles.size());

Review comment:
       instead of creating new list, can you use stream.map and collect the list at line 166?




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533595909



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,205 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+import org.apache.carbondata.core.util.path.CarbonTablePath.DataFileUtil;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        if (locationMap.entrySet().iterator().next().getValue().isRelative()) {
+          CarbonFile segmentPath = FileFactory.getCarbonFile(CarbonTablePath.getSegmentPath(
+              carbonTable.getTablePath(), segmentNumber));
+          // copy the complete segment to the trash folder
+          TrashUtil.copySegmentToTrash(segmentPath, TrashUtil.getCompleteTrashFolderPath(
+              carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber));
+          // Deleting the stale Segment folders and the segment file.
+          try {
+            CarbonUtil.deleteFoldersAndFiles(segmentPath);
+            // delete the segment file as well
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                staleSegmentFile));
+            for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+              if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+                  .equals(segmentNumber)) {
+                FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable
+                    .getTablePath(), duplicateStaleSegmentFile));
+              }
+            }
+          } catch (IOException | InterruptedException e) {
+            LOGGER.error("Unable to delete the segment: " + segmentPath + " from after moving" +
+                " it to the trash folder. Please delete them manually : " + e.getMessage(), e);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will clean all the stale segments for partition table, delete the source folders
+   * after copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegmentsForPartitionTable(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      // for each segment we get the indexfile first, then we get the carbondata file. Move both
+      // of those to trash folder
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      List<String> filesToProcess = fileStore.readIndexFiles(SegmentStatus.SUCCESS, true,
+          FileFactory.getConfiguration());
+
+      // get carbondata files from here
+      Map<String, List<String>> indexFilesMap = fileStore.getIndexFilesMap();
+      for (Map.Entry<String, List<String>> entry : indexFilesMap.entrySet()) {
+        filesToProcess.addAll(entry.getValue());
+      }
+      // After all the files have been added to list, move them to the trash folder
+      TrashUtil.copyFilesToTrash(filesToProcess, TrashUtil.getCompleteTrashFolderPath(
+          carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber), segmentNumber);
+      // After every file of that segment has been copied, need to delete those files.
+      try {
+        for (String file : filesToProcess) {
+          FileFactory.deleteFile(file);
+        }
+        // Delete the segment file too
+        FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+            staleSegmentFile));
+        // remove duplicate segment files if any
+        for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+          if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+              .equals(segmentNumber)) {
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                duplicateStaleSegmentFile));
+          }
+        }
+      } catch (IOException e) {
+        LOGGER.error("Error while deleting the source data files. Please delete the files of" +
+            " segment: " + segmentNumber + " manually.", e);
+      }
+    }
+    // Delete the empty partition folders
+    deleteEmptyPartitionFoldersRecursively(FileFactory.getCarbonFile(carbonTable.getTablePath()));
+  }
+
+  /**
+   * This method will find all the stale segments by comparing the segment files in the
+   * metadata directory with the segments in the table status file. Any segment which has entry
+   * in the metadata folder and is not present in the table status file is considered as a
+   * stale segment. Only comparing from tablestatus file, not checking tablestatus.history file
+   */
+  private static void getStaleSegmentFiles(CarbonTable carbonTable, List<String> staleSegmentFiles,
+      List<String> redundantSegmentFile) {
+    String segmentFilesLocation =
+        CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+    List<String> segmentFiles = Arrays.stream(FileFactory.getCarbonFile(segmentFilesLocation)
+        .listFiles()).map(segmentFile -> segmentFile.getName()).collect(Collectors

Review comment:
       replace lambda with method reference




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533596098



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,205 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+import org.apache.carbondata.core.util.path.CarbonTablePath.DataFileUtil;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        if (locationMap.entrySet().iterator().next().getValue().isRelative()) {
+          CarbonFile segmentPath = FileFactory.getCarbonFile(CarbonTablePath.getSegmentPath(
+              carbonTable.getTablePath(), segmentNumber));
+          // copy the complete segment to the trash folder
+          TrashUtil.copySegmentToTrash(segmentPath, TrashUtil.getCompleteTrashFolderPath(
+              carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber));
+          // Deleting the stale Segment folders and the segment file.
+          try {
+            CarbonUtil.deleteFoldersAndFiles(segmentPath);
+            // delete the segment file as well
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                staleSegmentFile));
+            for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+              if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+                  .equals(segmentNumber)) {
+                FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable
+                    .getTablePath(), duplicateStaleSegmentFile));
+              }
+            }
+          } catch (IOException | InterruptedException e) {
+            LOGGER.error("Unable to delete the segment: " + segmentPath + " from after moving" +
+                " it to the trash folder. Please delete them manually : " + e.getMessage(), e);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will clean all the stale segments for partition table, delete the source folders
+   * after copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegmentsForPartitionTable(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      // for each segment we get the indexfile first, then we get the carbondata file. Move both
+      // of those to trash folder
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      List<String> filesToProcess = fileStore.readIndexFiles(SegmentStatus.SUCCESS, true,
+          FileFactory.getConfiguration());
+
+      // get carbondata files from here
+      Map<String, List<String>> indexFilesMap = fileStore.getIndexFilesMap();
+      for (Map.Entry<String, List<String>> entry : indexFilesMap.entrySet()) {
+        filesToProcess.addAll(entry.getValue());
+      }
+      // After all the files have been added to list, move them to the trash folder
+      TrashUtil.copyFilesToTrash(filesToProcess, TrashUtil.getCompleteTrashFolderPath(
+          carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber), segmentNumber);
+      // After every file of that segment has been copied, need to delete those files.
+      try {
+        for (String file : filesToProcess) {
+          FileFactory.deleteFile(file);
+        }
+        // Delete the segment file too
+        FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+            staleSegmentFile));
+        // remove duplicate segment files if any
+        for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+          if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+              .equals(segmentNumber)) {
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                duplicateStaleSegmentFile));
+          }
+        }
+      } catch (IOException e) {
+        LOGGER.error("Error while deleting the source data files. Please delete the files of" +
+            " segment: " + segmentNumber + " manually.", e);
+      }
+    }
+    // Delete the empty partition folders
+    deleteEmptyPartitionFoldersRecursively(FileFactory.getCarbonFile(carbonTable.getTablePath()));
+  }
+
+  /**
+   * This method will find all the stale segments by comparing the segment files in the
+   * metadata directory with the segments in the table status file. Any segment which has entry
+   * in the metadata folder and is not present in the table status file is considered as a
+   * stale segment. Only comparing from tablestatus file, not checking tablestatus.history file
+   */
+  private static void getStaleSegmentFiles(CarbonTable carbonTable, List<String> staleSegmentFiles,
+      List<String> redundantSegmentFile) {
+    String segmentFilesLocation =
+        CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+    List<String> segmentFiles = Arrays.stream(FileFactory.getCarbonFile(segmentFilesLocation)
+        .listFiles()).map(segmentFile -> segmentFile.getName()).collect(Collectors
+        .toList());
+    // there are no segments present in the Metadata folder. Can return here
+    if (segmentFiles.size() == 0) {
+      return;
+    }
+    ArrayList<String> staleSegments = new ArrayList<>(staleSegmentFiles.size());
+    LoadMetadataDetails[] details = SegmentStatusManager.readLoadMetadata(carbonTable
+        .getMetadataPath());
+    Set<String> loadNameSet = Arrays.stream(details).map(loadMetadataDetails -> loadMetadataDetails

Review comment:
       replace lambda with method reference




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533596340



##########
File path: core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,205 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatus;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+import org.apache.carbondata.core.util.path.CarbonTablePath.DataFileUtil;
+
+import org.apache.log4j.Logger;
+
+/**
+ *This util provide clean stale data methods for clean files command
+ */
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CleanFilesUtil.class.getName());
+
+  /**
+   * This method will clean all the stale segments for a table, delete the source folder after
+   * copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegments(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      Map<String, SegmentFileStore.FolderDetails> locationMap = fileStore.getSegmentFile()
+          .getLocationMap();
+      if (locationMap != null) {
+        if (locationMap.entrySet().iterator().next().getValue().isRelative()) {
+          CarbonFile segmentPath = FileFactory.getCarbonFile(CarbonTablePath.getSegmentPath(
+              carbonTable.getTablePath(), segmentNumber));
+          // copy the complete segment to the trash folder
+          TrashUtil.copySegmentToTrash(segmentPath, TrashUtil.getCompleteTrashFolderPath(
+              carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber));
+          // Deleting the stale Segment folders and the segment file.
+          try {
+            CarbonUtil.deleteFoldersAndFiles(segmentPath);
+            // delete the segment file as well
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                staleSegmentFile));
+            for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+              if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+                  .equals(segmentNumber)) {
+                FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable
+                    .getTablePath(), duplicateStaleSegmentFile));
+              }
+            }
+          } catch (IOException | InterruptedException e) {
+            LOGGER.error("Unable to delete the segment: " + segmentPath + " from after moving" +
+                " it to the trash folder. Please delete them manually : " + e.getMessage(), e);
+          }
+        }
+      }
+    }
+  }
+
+  /**
+   * This method will clean all the stale segments for partition table, delete the source folders
+   * after copying the data to the trash and also remove the .segment files of the stale segments
+   */
+  public static void cleanStaleSegmentsForPartitionTable(CarbonTable carbonTable)
+      throws IOException {
+    long timeStampForTrashFolder = CarbonUpdateUtil.readCurrentTime();
+    List<String> staleSegmentFiles = new ArrayList<>();
+    List<String> redundantSegmentFile = new ArrayList<>();
+    getStaleSegmentFiles(carbonTable, staleSegmentFiles, redundantSegmentFile);
+    for (String staleSegmentFile : staleSegmentFiles) {
+      String segmentNumber = DataFileUtil.getSegmentNoFromSegmentFile(staleSegmentFile);
+      // for each segment we get the indexfile first, then we get the carbondata file. Move both
+      // of those to trash folder
+      SegmentFileStore fileStore = new SegmentFileStore(carbonTable.getTablePath(),
+          staleSegmentFile);
+      List<String> filesToProcess = fileStore.readIndexFiles(SegmentStatus.SUCCESS, true,
+          FileFactory.getConfiguration());
+
+      // get carbondata files from here
+      Map<String, List<String>> indexFilesMap = fileStore.getIndexFilesMap();
+      for (Map.Entry<String, List<String>> entry : indexFilesMap.entrySet()) {
+        filesToProcess.addAll(entry.getValue());
+      }
+      // After all the files have been added to list, move them to the trash folder
+      TrashUtil.copyFilesToTrash(filesToProcess, TrashUtil.getCompleteTrashFolderPath(
+          carbonTable.getTablePath(), timeStampForTrashFolder, segmentNumber), segmentNumber);
+      // After every file of that segment has been copied, need to delete those files.
+      try {
+        for (String file : filesToProcess) {
+          FileFactory.deleteFile(file);
+        }
+        // Delete the segment file too
+        FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+            staleSegmentFile));
+        // remove duplicate segment files if any
+        for (String duplicateStaleSegmentFile : redundantSegmentFile) {
+          if (DataFileUtil.getSegmentNoFromSegmentFile(duplicateStaleSegmentFile)
+              .equals(segmentNumber)) {
+            FileFactory.deleteFile(CarbonTablePath.getSegmentFilePath(carbonTable.getTablePath(),
+                duplicateStaleSegmentFile));
+          }
+        }
+      } catch (IOException e) {
+        LOGGER.error("Error while deleting the source data files. Please delete the files of" +
+            " segment: " + segmentNumber + " manually.", e);
+      }
+    }
+    // Delete the empty partition folders
+    deleteEmptyPartitionFoldersRecursively(FileFactory.getCarbonFile(carbonTable.getTablePath()));
+  }
+
+  /**
+   * This method will find all the stale segments by comparing the segment files in the
+   * metadata directory with the segments in the table status file. Any segment which has entry
+   * in the metadata folder and is not present in the table status file is considered as a
+   * stale segment. Only comparing from tablestatus file, not checking tablestatus.history file
+   */
+  private static void getStaleSegmentFiles(CarbonTable carbonTable, List<String> staleSegmentFiles,
+      List<String> redundantSegmentFile) {
+    String segmentFilesLocation =
+        CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+    List<String> segmentFiles = Arrays.stream(FileFactory.getCarbonFile(segmentFilesLocation)
+        .listFiles()).map(segmentFile -> segmentFile.getName()).collect(Collectors
+        .toList());
+    // there are no segments present in the Metadata folder. Can return here
+    if (segmentFiles.size() == 0) {
+      return;
+    }
+    ArrayList<String> staleSegments = new ArrayList<>(staleSegmentFiles.size());
+    LoadMetadataDetails[] details = SegmentStatusManager.readLoadMetadata(carbonTable
+        .getMetadataPath());
+    Set<String> loadNameSet = Arrays.stream(details).map(loadMetadataDetails -> loadMetadataDetails
+        .getLoadName()).collect(Collectors.toSet());
+    for (String segmentFile : segmentFiles) {
+      if (!loadNameSet.contains(DataFileUtil.getSegmentNoFromSegmentFile(
+          segmentFile))) {
+        staleSegments.add(segmentFile);
+      }
+    }
+    if (staleSegments.size() == 0) {
+      return;
+    }
+    // sort the stale segment List
+    Collections.sort(staleSegments);
+    // in case of multiple segment files for a segment, add the segment with the largest
+    // timestamp to staleSegmentFiles list and add the others to redundantsegmentfile list.
+    for (int i = 0; i < staleSegments.size() - 1; i++) {
+      if (!DataFileUtil.getSegmentNoFromSegmentFile(staleSegments.get(i)).equals(
+          DataFileUtil.getSegmentNoFromSegmentFile(staleSegments.get(i + 1)))) {
+        staleSegmentFiles.add(staleSegments.get(i));
+      } else {
+        redundantSegmentFile.add(staleSegments.get(i));
+      }
+    }
+    // adding the last occurence always

Review comment:
       please correct the spelling




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533598665



##########
File path: core/src/main/java/org/apache/carbondata/core/util/TrashUtil.java
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.constants.CarbonCommonConstants;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+
+import org.apache.hadoop.io.IOUtils;
+import org.apache.log4j.Logger;
+
+/**
+ * Mantains the trash folder in carbondata. This class has methods to copy data to the trash and

Review comment:
       correct the spelling




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533599088



##########
File path: core/src/main/java/org/apache/carbondata/core/util/TrashUtil.java
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.constants.CarbonCommonConstants;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+
+import org.apache.hadoop.io.IOUtils;
+import org.apache.log4j.Logger;
+
+/**
+ * Mantains the trash folder in carbondata. This class has methods to copy data to the trash and
+ * remove data from the trash.
+ */
+public final class TrashUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(TrashUtil.class.getName());
+
+  /**
+   * Base method to copy the data to the trash folder.
+   *
+   * @param sourcePath      the path from which to copy the file
+   * @param destinationPath the path where the file will be copied
+   * @return
+   */
+  private static void copyToTrashFolder(String sourcePath, String destinationPath)
+    throws IOException {
+    DataOutputStream dataOutputStream = null;
+    DataInputStream dataInputStream = null;
+    try {
+      dataOutputStream = FileFactory.getDataOutputStream(destinationPath);
+      dataInputStream = FileFactory.getDataInputStream(sourcePath);
+      IOUtils.copyBytes(dataInputStream, dataOutputStream, CarbonCommonConstants.BYTEBUFFER_SIZE);
+    } catch (IOException exception) {
+      LOGGER.error("Unable to copy " + sourcePath + " to the trash folder", exception);
+      throw exception;
+    } finally {
+      CarbonUtil.closeStreams(dataInputStream, dataOutputStream);
+    }
+  }
+
+  /**
+   * The below method copies the complete a file to the trash folder.
+   *
+   * @param filePathToCopy           the files which are to be moved to the trash folder
+   * @param trashFolderWithTimestamp timestamp, partition folder(if any) and segment number
+   * @return

Review comment:
       remove return




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

For queries about this service, please contact Infrastructure at:
[hidden email]


Reply | Threaded
Open this post in threaded view
|

[GitHub] [carbondata] akashrn5 commented on a change in pull request #4005: [CARBONDATA-3978] Trash Folder support in carbondata

GitBox
In reply to this post by GitBox

akashrn5 commented on a change in pull request #4005:
URL: https://github.com/apache/carbondata/pull/4005#discussion_r533599288



##########
File path: core/src/main/java/org/apache/carbondata/core/util/TrashUtil.java
##########
@@ -0,0 +1,229 @@
+/*
+ * 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.carbondata.core.util;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.carbondata.common.logging.LogServiceFactory;
+import org.apache.carbondata.core.constants.CarbonCommonConstants;
+import org.apache.carbondata.core.datastore.filesystem.CarbonFile;
+import org.apache.carbondata.core.datastore.impl.FileFactory;
+import org.apache.carbondata.core.mutate.CarbonUpdateUtil;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+
+import org.apache.hadoop.io.IOUtils;
+import org.apache.log4j.Logger;
+
+/**
+ * Mantains the trash folder in carbondata. This class has methods to copy data to the trash and
+ * remove data from the trash.
+ */
+public final class TrashUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(TrashUtil.class.getName());
+
+  /**
+   * Base method to copy the data to the trash folder.
+   *
+   * @param sourcePath      the path from which to copy the file
+   * @param destinationPath the path where the file will be copied
+   * @return
+   */
+  private static void copyToTrashFolder(String sourcePath, String destinationPath)
+    throws IOException {
+    DataOutputStream dataOutputStream = null;
+    DataInputStream dataInputStream = null;
+    try {
+      dataOutputStream = FileFactory.getDataOutputStream(destinationPath);
+      dataInputStream = FileFactory.getDataInputStream(sourcePath);
+      IOUtils.copyBytes(dataInputStream, dataOutputStream, CarbonCommonConstants.BYTEBUFFER_SIZE);
+    } catch (IOException exception) {
+      LOGGER.error("Unable to copy " + sourcePath + " to the trash folder", exception);
+      throw exception;
+    } finally {
+      CarbonUtil.closeStreams(dataInputStream, dataOutputStream);
+    }
+  }
+
+  /**
+   * The below method copies the complete a file to the trash folder.
+   *
+   * @param filePathToCopy           the files which are to be moved to the trash folder
+   * @param trashFolderWithTimestamp timestamp, partition folder(if any) and segment number
+   * @return
+   */
+  public static void copyFileToTrashFolder(String filePathToCopy,
+      String trashFolderWithTimestamp) throws IOException {
+    CarbonFile carbonFileToCopy = FileFactory.getCarbonFile(filePathToCopy);
+    String destinationPath = trashFolderWithTimestamp + CarbonCommonConstants
+        .FILE_SEPARATOR + carbonFileToCopy.getName();
+    try {
+      if (!FileFactory.isFileExist(destinationPath)) {
+        copyToTrashFolder(filePathToCopy, destinationPath);
+      }
+    } catch (IOException e) {
+      // in case there is any issue while copying the file to the trash folder, we need to delete
+      // the complete segment folder from the trash folder. The trashFolderWithTimestamp contains
+      // the segment folder too. Delete the folder as it is.
+      FileFactory.deleteFile(trashFolderWithTimestamp);
+      LOGGER.error("Error while checking trash folder: " + destinationPath + " or copying" +
+          " file: " + filePathToCopy + " to the trash folder at path", e);
+      throw e;
+    }
+  }
+
+  /**
+   * The below method copies the complete segment folder to the trash folder. Here, the data files
+   * in segment are listed and copied one by one to the trash folder.
+   *
+   * @param segmentPath              the folder which are to be moved to the trash folder
+   * @param trashFolderWithTimestamp trashfolderpath with complete timestamp and segment number
+   * @return

Review comment:
       remove return




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

For queries about this service, please contact Infrastructure at:
[hidden email]


1 ... 45678