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



##########
File path: 
core/src/main/java/org/apache/carbondata/core/util/CleanFilesUtil.java
##########
@@ -0,0 +1,321 @@
+/*
+ * 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.sql.Timestamp;
+import java.util.*;
+
+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.locks.CarbonLockFactory;
+import org.apache.carbondata.core.locks.CarbonLockUtil;
+import org.apache.carbondata.core.locks.ICarbonLock;
+import org.apache.carbondata.core.locks.LockUsage;
+import org.apache.carbondata.core.metadata.SegmentFileStore;
+import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
+import org.apache.carbondata.core.statusmanager.LoadMetadataDetails;
+import org.apache.carbondata.core.statusmanager.SegmentStatusManager;
+import org.apache.carbondata.core.util.path.CarbonTablePath;
+
+import org.apache.log4j.Logger;
+
+public class CleanFilesUtil {
+
+  private static final Logger LOGGER =
+      LogServiceFactory.getLogService(CarbonUtil.class.getName());
+  private static List<CarbonFile> filesInPartitionFolder = new 
ArrayList<CarbonFile>();
+
+  /**
+   *
+   * This method will clean the stale segments and move them to the trash 
folder.
+   */
+  public static void cleanStaleSegmentsNonPartitionTable(CarbonTable 
carbonTable)
+     throws IOException {
+    String metaDataLocation = carbonTable.getMetadataPath();
+    String partitionPath = 
CarbonTablePath.getPartitionDir(carbonTable.getTablePath());
+    String timeStampForTrashFolder = String.valueOf(new 
Timestamp(System.currentTimeMillis())
+        .getTime());
+    if (FileFactory.isFileExist(partitionPath)) {
+      // list all segments before reading tablestatus file.
+      CarbonFile[] allSegments = 
FileFactory.getCarbonFile(partitionPath).listFiles();
+      // there is no segment
+      if (allSegments == null || allSegments.length == 0) {
+        return;
+      }
+      int retryCount = CarbonLockUtil
+          
.getLockProperty(CarbonCommonConstants.NUMBER_OF_TRIES_FOR_CONCURRENT_LOCK,
+          CarbonCommonConstants.NUMBER_OF_TRIES_FOR_CONCURRENT_LOCK_DEFAULT);
+      int maxTimeout = CarbonLockUtil
+          
.getLockProperty(CarbonCommonConstants.MAX_TIMEOUT_FOR_CONCURRENT_LOCK,
+          CarbonCommonConstants.MAX_TIMEOUT_FOR_CONCURRENT_LOCK_DEFAULT);
+      ICarbonLock carbonTableStatusLock = CarbonLockFactory
+          .getCarbonLockObj(carbonTable.getAbsoluteTableIdentifier(), 
LockUsage.TABLE_STATUS_LOCK);
+      try {
+        if (carbonTableStatusLock.lockWithRetries(retryCount, maxTimeout)) {
+          LoadMetadataDetails[] details = 
SegmentStatusManager.readLoadMetadata(metaDataLocation);
+          // there is no segment or failed to read tablestatus file.
+          // so it should stop immediately.
+          // Do not stop if the tablestatus file does not exist, it can have 
stale segments.
+          if (FileFactory.getCarbonFile(carbonTable.getMetadataPath() + 
CarbonCommonConstants
+              .FILE_SEPARATOR + CarbonTablePath.TABLE_STATUS_FILE).exists() && 
(details == null
+              || details.length == 0)) {
+            return;
+          }
+          HashMap<CarbonFile, String> staleSegments = 
getStaleSegmentsNormalTable(details,
+              allSegments);
+          // move these segments one by one to the trash folder
+          for (Map.Entry<CarbonFile, String> entry : staleSegments.entrySet()) 
{
+            TrashUtil.copySegmentToTrash(entry.getKey(), 
carbonTable.getTablePath(),
+                timeStampForTrashFolder + CarbonCommonConstants.FILE_SEPARATOR 
+
+                CarbonCommonConstants.LOAD_FOLDER + entry.getValue());
+            LOGGER.info("Deleting Segment: " + 
entry.getKey().getAbsolutePath());
+            try {
+              CarbonUtil.deleteFoldersAndFiles(entry.getKey());
+              LOGGER.info("Deleting Segment: "  + entry.getKey());
+            } catch (IOException | InterruptedException e) {
+              LOGGER.error("Unable to delete the given path :: " + 
e.getMessage(), e);
+            }
+          }
+          if (staleSegments.size() > 0) {
+            // get the segment metadata path
+            String segmentFilesLocation =
+                
CarbonTablePath.getSegmentFilesLocation(carbonTable.getTablePath());
+            // delete the segment metadata files also
+            CarbonFile[] staleSegmentMetadataFiles = 
FileFactory.getCarbonFile(segmentFilesLocation)
+                .listFiles(file -> (staleSegments.containsValue(file.getName()
+                .split(CarbonCommonConstants.UNDERSCORE)[0])));
+            for (CarbonFile staleSegmentMetadataFile : 
staleSegmentMetadataFiles) {
+              staleSegmentMetadataFile.delete();
+            }
+          }
+        } else {
+          String errorMessage =
+              "Not able to acquire the Table status lock for cleaning stale 
segments for table "
+              + carbonTable.getDatabaseName() + "." + 
carbonTable.getTableName();
+          LOGGER.error(errorMessage);
+        }
+      } finally {
+        carbonTableStatusLock.unlock();
+      }
+    }
+  }
+
+  /**
+   *
+   * This method will copy data files for partition table to the trash folder, 
file by file.
+   */
+  public static List<String> copyPartitionTableFilesToTrash(String segmentFile,
+      String timeStampForTrashFolder, String segmentNo, CarbonTable 
carbonTable,
+      String indexMergeFile) throws IOException {
+    // search for indexMergeFile everywhere and segmentFile in the carbondata 
file and
+    // copy to trash folder
+    List<String> filesToDelete = new ArrayList<>();
+    for (CarbonFile fileList : filesInPartitionFolder) {
+      String nameofFile = 
fileList.getName().replace(CarbonCommonConstants.HYPHEN,
+          CarbonCommonConstants.UNDERSCORE);
+      String nameOfSegment = segmentFile.substring(0, segmentFile.indexOf(
+          CarbonCommonConstants.POINT));
+      String partitionValue = 
fileList.getAbsolutePath().split(CarbonCommonConstants
+          
.FILE_SEPARATOR)[fileList.getAbsolutePath().split(CarbonCommonConstants
+          .FILE_SEPARATOR).length - 2];
+      if (fileList.getName().equals(indexMergeFile)) {
+        TrashUtil.copyFileToTrashFolder(carbonTable.getTablePath(),
+            fileList.getAbsolutePath(), timeStampForTrashFolder + 
CarbonCommonConstants
+            .FILE_SEPARATOR + CarbonCommonConstants.LOAD_FOLDER + segmentNo +
+            CarbonCommonConstants.FILE_SEPARATOR + partitionValue);
+        filesToDelete.add(fileList.getAbsolutePath());
+      } else if (nameofFile.contains(nameOfSegment) && 
fileList.getName().endsWith(
+          CarbonTablePath.INDEX_FILE_EXT)) {
+        TrashUtil.copyFileToTrashFolder(carbonTable.getTablePath(),
+            fileList.getAbsolutePath(), timeStampForTrashFolder + 
CarbonCommonConstants
+            .FILE_SEPARATOR + CarbonCommonConstants.LOAD_FOLDER + segmentNo +
+            CarbonCommonConstants.FILE_SEPARATOR + partitionValue);
+        filesToDelete.add(fileList.getAbsolutePath());
+      } else if (nameofFile.contains(nameOfSegment) && 
fileList.getName().endsWith(
+          CarbonCommonConstants.FACT_FILE_EXT)) {
+        // carbondata file found
+        TrashUtil.copyFileToTrashFolder(carbonTable.getTablePath(), fileList
+            .getAbsolutePath(), timeStampForTrashFolder + CarbonCommonConstants
+            .FILE_SEPARATOR + CarbonCommonConstants.LOAD_FOLDER + segmentNo +
+            CarbonCommonConstants.FILE_SEPARATOR + partitionValue);
+        filesToDelete.add(fileList.getAbsolutePath());
+      }
+    }
+    return filesToDelete;
+  }
+
+  /**
+   *
+   * This method will find all the stale segments in normal table flow.
+   */
+  public static HashMap<CarbonFile, String> 
getStaleSegmentsNormalTable(LoadMetadataDetails[]
+      details, CarbonFile[] allSegments) {
+    Set<String> metadataSet = new HashSet<>(details.length);
+    for (LoadMetadataDetails detail : details) {
+      metadataSet.add(detail.getLoadName());
+    }
+    HashMap<CarbonFile, String> staleSegments = new 
HashMap<>(allSegments.length);
+    for (CarbonFile segment : allSegments) {
+      String segmentName = segment.getName();
+      // check segment folder pattern
+      if (segmentName.startsWith(CarbonTablePath.SEGMENT_PREFIX)) {
+        String[] parts = segmentName.split(CarbonCommonConstants.UNDERSCORE);
+        if (parts.length == 2) {
+          boolean isOriginal = !parts[1].contains(".");
+          // in loading flow,
+          // it should be original segment and segment metadata doesn't exists
+          if (isOriginal && !metadataSet.contains(parts[1])) {
+            staleSegments.put(segment, parts[1]);
+          }
+        }
+      }
+    }
+    return staleSegments;
+  }
+
+  /**
+   *
+   * This method will find all the stale segments for partition table flow.
+   */
+  public static List<String> 
getStaleSegmentsPartitionTable(LoadMetadataDetails[] details,
+      Map<String, String> detailName, CarbonFile[] allSegment) {
+    List<String> staleSegments = new ArrayList<>();
+    for (CarbonFile file : allSegment) {

Review comment:
       worng way. add only whatever is stale




----------------------------------------------------------------
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:
us...@infra.apache.org


Reply via email to