This is an automated email from the ASF dual-hosted git repository.

ChenSammi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new 355a880ce1a HDDS-17783. Abort Lifecycle task if lifecycle 
configuration is deleted or updated (#12030)
355a880ce1a is described below

commit 355a880ce1a6abd93c1b1dbfddfe766c3851e9f8
Author: Sammi Chen <[email protected]>
AuthorDate: Wed Nov 18 15:49:53 2026 +0800

    HDDS-17783. Abort Lifecycle task if lifecycle configuration is deleted or 
updated (#12030)
---
 .../ozone/om/helpers/OmLifecycleScanState.java     |  26 ++-
 .../ozone/om/helpers/TestOmLifecycleScanState.java |   5 +
 .../ozone/om/service/KeyLifecycleService.java      | 108 +++++++++--
 .../ozone/om/service/TestKeyLifecycleService.java  | 204 ++++++++++++++++++---
 4 files changed, 300 insertions(+), 43 deletions(-)

diff --git 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/helpers/OmLifecycleScanState.java
 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/helpers/OmLifecycleScanState.java
index 41bc5de16aa..982e239ef4f 100644
--- 
a/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/helpers/OmLifecycleScanState.java
+++ 
b/hadoop-ozone/common/src/main/java/org/apache/hadoop/ozone/om/helpers/OmLifecycleScanState.java
@@ -34,6 +34,7 @@ public class OmLifecycleScanState {
   private String lastScannedKey;
   private String lastScannedDir;
   private String lastScannedDirKey;
+  private String lastScannedMpuKey;
 
   private static final Codec<OmLifecycleScanState> CODEC = new 
DelegatedCodec<>(
       Proto2Codec.get(LifecycleScanState.getDefaultInstance()),
@@ -59,6 +60,7 @@ private OmLifecycleScanState(Builder builder) {
     this.lastScannedKey = builder.lastScannedKey;
     this.lastScannedDir = builder.lastScannedDir;
     this.lastScannedDirKey = builder.lastScannedDirKey;
+    this.lastScannedMpuKey = builder.lastScannedMpuKey;
   }
 
   public String getBucketKey() {
@@ -105,6 +107,10 @@ public String getLastScannedDirKey() {
     return lastScannedDirKey;
   }
 
+  public String getLastScannedMpuKey() {
+    return lastScannedMpuKey;
+  }
+
   public LifecycleScanState getProtobuf() {
     LifecycleScanState.Builder builder = LifecycleScanState.newBuilder()
         .setBucketKey(bucketKey)
@@ -124,6 +130,9 @@ public LifecycleScanState getProtobuf() {
     if (lastScannedDirKey != null) {
       builder.setLastScannedDirKey(lastScannedDirKey);
     }
+    if (lastScannedMpuKey != null) {
+      builder.setLastScannedMpuKey(lastScannedMpuKey);
+    }
     return builder.build();
   }
 
@@ -146,6 +155,9 @@ public static OmLifecycleScanState 
getFromProtobuf(LifecycleScanState proto) {
     if (proto.hasLastScannedDirKey()) {
       builder.setLastScannedDirKey(proto.getLastScannedDirKey());
     }
+    if (proto.hasLastScannedMpuKey()) {
+      builder.setLastScannedMpuKey(proto.getLastScannedMpuKey());
+    }
     return builder.build();
   }
 
@@ -160,6 +172,7 @@ public String toString() {
         ", lastScannedKey='" + lastScannedKey + '\'' +
         ", lastScannedDir='" + lastScannedDir + '\'' +
         ", lastScannedDirKey='" + lastScannedDirKey + '\'' +
+        ", lastScannedMpuKey='" + lastScannedMpuKey + '\'' +
         '}';
   }
 
@@ -172,7 +185,8 @@ public Builder toBuilder() {
         .setScanEndTime(scanEndTime)
         .setLastScannedKey(lastScannedKey)
         .setLastScannedDir(lastScannedDir)
-        .setLastScannedDirKey(lastScannedDirKey);
+        .setLastScannedDirKey(lastScannedDirKey)
+        .setLastScannedMpuKey(lastScannedMpuKey);
   }
 
   /**
@@ -187,6 +201,7 @@ public static class Builder {
     private String lastScannedKey;
     private String lastScannedDir;
     private String lastScannedDirKey;
+    private String lastScannedMpuKey;
 
     public Builder setBucketKey(String bucketKey) {
       this.bucketKey = bucketKey;
@@ -248,6 +263,15 @@ public Builder setLastScannedDirKey(String 
lastScannedDirKey) {
       return this;
     }
 
+    public String getLastScannedMpuKey() {
+      return lastScannedMpuKey;
+    }
+
+    public Builder setLastScannedMpuKey(String multipartInfoTableKey) {
+      this.lastScannedMpuKey = multipartInfoTableKey;
+      return this;
+    }
+
     public OmLifecycleScanState build() {
       return new OmLifecycleScanState(this);
     }
diff --git 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/helpers/TestOmLifecycleScanState.java
 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/helpers/TestOmLifecycleScanState.java
index 59244bb06ce..9ca876f476b 100644
--- 
a/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/helpers/TestOmLifecycleScanState.java
+++ 
b/hadoop-ozone/common/src/test/java/org/apache/hadoop/ozone/om/helpers/TestOmLifecycleScanState.java
@@ -36,6 +36,7 @@ public void testBuilderAndProtobufConversion() {
         .setScanEndTime(123456799L)
         .setLastScannedKey("key1")
         .setLastScannedDir("subDir1")
+        .setLastScannedMpuKey("mpuKey1")
         .build();
 
     assertEquals("/vol1/bucket1", state.getBucketKey());
@@ -43,6 +44,7 @@ public void testBuilderAndProtobufConversion() {
     assertEquals(123456799L, state.getScanEndTime());
     assertEquals("key1", state.getLastScannedKey());
     assertEquals("subDir1", state.getLastScannedDir());
+    assertEquals("mpuKey1", state.getLastScannedMpuKey());
 
     LifecycleScanState proto = state.getProtobuf();
     OmLifecycleScanState decodedState = 
OmLifecycleScanState.getFromProtobuf(proto);
@@ -52,6 +54,8 @@ public void testBuilderAndProtobufConversion() {
     assertEquals(state.getScanEndTime(), decodedState.getScanEndTime());
     assertEquals(state.getLastScannedKey(), decodedState.getLastScannedKey());
     assertEquals(state.getLastScannedDir(), decodedState.getLastScannedDir());
+    assertEquals(state.getLastScannedMpuKey(), 
decodedState.getLastScannedMpuKey());
+    assertEquals(state.getLastScannedMpuKey(), 
state.toBuilder().build().getLastScannedMpuKey());
   }
 
   @Test
@@ -75,5 +79,6 @@ public void 
testBuilderAndProtobufConversionWithoutOptionals() {
     assertNull(decodedState.getScanEndTime());
     assertNull(decodedState.getLastScannedKey());
     assertNull(decodedState.getLastScannedDir());
+    assertNull(decodedState.getLastScannedMpuKey());
   }
 }
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/KeyLifecycleService.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/KeyLifecycleService.java
index cb88822037a..5038737f67b 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/KeyLifecycleService.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/service/KeyLifecycleService.java
@@ -316,15 +316,52 @@ public final class LifecycleActionTask implements 
BackgroundTask {
     private String lastScannedKey;
     private String lastScannedDir;
     private String lastScannedDirKey;
+    private String lastScannedMpuKey;
 
     private long lastStateSaveTime = Time.monotonicNow();
     private long lastStateSaveKeyCount = 0;
     private boolean scanAborted;
     private long stackCapacitySkippedDirectories = 0;
+    private boolean policyChanged;
+
+    /**
+     * Checks whether the bucket's lifecycle configuration was deleted or 
updated after this task was scheduled.
+     * Stop the task if the bucket's lifecycle configuration is deleted or 
updated.
+     */
+    private boolean checkPolicyChange() {
+      if (!policyChanged) {
+        String bucketKey = omMetadataManager.getBucketKey(policy.getVolume(), 
policy.getBucket());
+        try {
+          OmLifecycleConfiguration current = 
omMetadataManager.getLifecycleConfigurationTable().get(bucketKey);
+          policyChanged = current == null || current.getUpdateID() != 
policy.getUpdateID();
+        } catch (IOException e) {
+          LOG.warn("Failed to get lifecycle configuration of bucket {}", 
bucketKey, e);
+          policyChanged = true;
+        }
+        if (policyChanged) {
+          LOG.info("Lifecycle configuration of bucket {} is deleted or 
updated, stopping task", bucketKey);
+        }
+      }
+      return policyChanged;
+    }
+
+    /**
+     * Returns false if the task should stop, either the service is suspended, 
disabled, not leader or about to
+     * restart, or the bucket's lifecycle configuration is deleted or updated.
+     */
+    private boolean shouldContinue(String bucketName) {
+      if (!shouldRun()) {
+        scanAborted = true;
+        LOG.info("KeyLifecycleService is suspended, disabled, leader not 
ready, or about to restart. " +
+            "Stopping task for bucket {}.", bucketName);
+        return false;
+      }
+      return !policyChanged;
+    }
 
     private boolean shouldSaveState() {
       if ((Time.monotonicNow() - lastStateSaveTime) > stateSaveIntervalMs ||
-          (numKeyIterated - lastStateSaveKeyCount) >= 
maxKeysProcessedPerState) {
+          (numKeyIterated + numMultipartUploadIterated - 
lastStateSaveKeyCount) >= maxKeysProcessedPerState) {
         return true;
       }
       return false;
@@ -340,6 +377,7 @@ public int getPriority() {
     }
 
     @Override
+    @SuppressWarnings("checkstyle:MethodLength")
     public BackgroundTaskResult call() {
       EmptyTaskResult result = EmptyTaskResult.newResult();
       String bucketKey = omMetadataManager.getBucketKey(policy.getVolume(), 
policy.getBucket());
@@ -371,6 +409,11 @@ public BackgroundTaskResult call() {
           return result;
         }
 
+        if (checkPolicyChange()) {
+          onSuccess(bucketKey);
+          return result;
+        }
+
         OmLifecycleScanState.Builder scanStateBuilder = null;
         try {
           OmLifecycleScanState scanState = 
omMetadataManager.getLifecycleScanStateTable().get(bucketKey);
@@ -446,7 +489,8 @@ public BackgroundTaskResult call() {
               evaluateBucket(bucket, keyTable, expirationRules, 
expiredKeyList, scanStateBuilder);
             }
 
-            boolean scanFinished = !scanAborted;
+            // With multipart upload rules, the scan finishes after the 
multipart uploads are processed
+            boolean scanFinished = !scanAborted && mpuRules.isEmpty();
             if (expiredKeyList.isEmpty() && expiredDirList.isEmpty()) {
               LOG.info("No expired keys/dirs found/remained for bucket {}", 
bucketKey);
               sendSaveScanStateRequest(scanStateBuilder, scanFinished);
@@ -468,7 +512,8 @@ public BackgroundTaskResult call() {
           }
 
           if (!mpuRules.isEmpty()) {
-            processMultipartUploads(bucket, mpuRules);
+            processMultipartUploads(bucket, mpuRules, scanStateBuilder);
+            sendSaveScanStateRequest(scanStateBuilder, !scanAborted);
           }
         } catch (Throwable e) {
           LOG.error("Failed to evaluate lifecycle configuration for bucket 
{}", bucketKey, e);
@@ -687,10 +732,7 @@ private void evaluateKeyAndDirTable(OmBucketInfo bucket, 
long volumeObjId, Table
 
       HashSet<Long> deletedDirSet = new HashSet<>();
       while (!stack.isEmpty()) {
-        if (!shouldRun()) {
-          scanAborted = true;
-          LOG.info("KeyLifecycleService is suspended, disabled, leader not 
ready, or about to restart. " +
-              "Stopping task for bucket {}.", bucketName);
+        if (!shouldContinue(bucketName)) {
           return;
         }
 
@@ -1033,7 +1075,7 @@ private void flushAndSaveState(OmBucketInfo bucket, 
LimitedExpiredObjectList exp
         sendSaveScanStateRequest(scanStateBuilder, false);
       }
       lastStateSaveTime = Time.monotonicNow();
-      lastStateSaveKeyCount = numKeyIterated;
+      lastStateSaveKeyCount = numKeyIterated + numMultipartUploadIterated;
     }
 
     private void evaluateBucket(OmBucketInfo bucketInfo,
@@ -1052,10 +1094,7 @@ private void evaluateBucket(OmBucketInfo bucketInfo,
         }
 
         while (keyTblItr.hasNext()) {
-          if (!shouldRun()) {
-            scanAborted = true;
-            LOG.info("KeyLifecycleService is suspended, disabled, leader not 
ready, or about to restart. " +
-                "Stopping task for bucket {}.", bucketName);
+          if (!shouldContinue(bucketName)) {
             return;
           }
           if (shouldSaveState()) {
@@ -1110,8 +1149,10 @@ private void processKey(OmBucketInfo bucketInfo, 
OmKeyInfo key, List<OmLCRule> r
      *
      * @param bucketInfo the bucket information
      * @param ruleList list of lifecycle rules with 
AbortIncompleteMultipartUpload action
+     * @param scanStateBuilder scan state to resume from and to save the 
scanned multipart upload pointer to
      */
-    private void processMultipartUploads(OmBucketInfo bucketInfo, 
List<OmLCRule> ruleList) {
+    private void processMultipartUploads(OmBucketInfo bucketInfo, 
List<OmLCRule> ruleList,
+        OmLifecycleScanState.Builder scanStateBuilder) {
       String volumeName = bucketInfo.getVolumeName();
       String bucketName = bucketInfo.getBucketName();
       String bucketPrefix = omMetadataManager.getBucketKeyPrefix(volumeName, 
bucketName);
@@ -1119,18 +1160,30 @@ private void processMultipartUploads(OmBucketInfo 
bucketInfo, List<OmLCRule> rul
       LOG.debug("Processing AbortIncompleteMultipartUpload actions for bucket 
{}/{}", volumeName, bucketName);
 
       PartCountLimitedList expiredUploads = new 
PartCountLimitedList(mpuAbortLimitPerTask);
+      boolean seekPerformed = false;
       try (TableIterator<String, ? extends Table.KeyValue<String, 
OmMultipartKeyInfo>> mpuIterator =
                
omMetadataManager.getMultipartInfoTable().iterator(bucketPrefix)) {
+        String resumeMpuKey = scanStateBuilder == null ? null : 
scanStateBuilder.getLastScannedMpuKey();
+        if (resumeMpuKey != null) {
+          mpuIterator.seek(resumeMpuKey);
+          seekPerformed = true;
+        }
         while (mpuIterator.hasNext()) {
-          if (!shouldRun()) {
-            scanAborted = true;
-            LOG.info("KeyLifecycleService is suspended, disabled, leader not 
ready, or about to restart. " +
-                "Stopping task for bucket {}.", bucketName);
-            return;
+          if (!shouldContinue(bucketName)) {
+            break;
+          }
+          if (shouldSaveState()) {
+            // abort the pending uploads first, so the saved pointer never 
skips an upload that is not aborted
+            abortExpiredMultipartUploadsAndClear(bucketInfo, expiredUploads);
+            flushAndSaveState(bucketInfo, null, null, scanStateBuilder);
           }
           Table.KeyValue<String, OmMultipartKeyInfo> entry = 
mpuIterator.next();
+          if (seekPerformed && entry.getKey().equals(resumeMpuKey)) {
+            continue;
+          }
           OmMultipartKeyInfo mpuKeyInfo = entry.getValue();
           numMultipartUploadIterated++;
+          lastScannedMpuKey = entry.getKey();
 
           OmMultipartUpload upload;
           try {
@@ -1221,8 +1274,8 @@ private void processMultipartUploads(OmBucketInfo 
bucketInfo, List<OmLCRule> rul
               volumeName, bucketName, keyName, upload.getUploadId(), 
uploadedParts);
         }
       } catch (IOException e) {
+        // log failure and continue the process to abort uploads already 
identified in this run
         LOG.warn("Failed to iterate multipartInfoTable for bucket {}/{}", 
volumeName, bucketName, e);
-        return;
       }
 
       if (!expiredUploads.isEmpty()) {
@@ -1311,6 +1364,10 @@ private void 
abortExpiredMultipartUploadsAndClear(OmBucketInfo bucketInfo,
       if (expiredUploads.isEmpty()) {
         return;
       }
+      if (checkPolicyChange()) {
+        expiredUploads.clear();
+        return;
+      }
 
       abortExpiredMultipartUploads(bucketInfo, expiredUploads.getUploads());
       expiredUploads.clear();
@@ -1413,7 +1470,7 @@ private void handleAndClearFullList(OmBucketInfo bucket, 
LimitedExpiredObjectLis
     }
 
     private void sendSaveScanStateRequest(OmLifecycleScanState.Builder 
scanStateBuilder, boolean scanFinished) {
-      if (scanStateBuilder != null) {
+      if (scanStateBuilder != null && !checkPolicyChange()) {
         if (lastScannedDir != null) {
           scanStateBuilder.setLastScannedDir(lastScannedDir);
         }
@@ -1423,6 +1480,9 @@ private void 
sendSaveScanStateRequest(OmLifecycleScanState.Builder scanStateBuil
         if (lastScannedKey != null) {
           scanStateBuilder.setLastScannedKey(lastScannedKey);
         }
+        if (lastScannedMpuKey != null) {
+          scanStateBuilder.setLastScannedMpuKey(lastScannedMpuKey);
+        }
         if (scanFinished) {
           scanStateBuilder.setScanEndTime(System.currentTimeMillis());
         }
@@ -1459,6 +1519,10 @@ private void sendDeleteKeysRequestAndClearList(String 
volume, String bucket, Str
           }
         }
 
+        if (checkPolicyChange()) {
+          return;
+        }
+
         UserGroupInformation ugi = 
UserGroupInformation.createRemoteUser(bucketOwner);
         int batchSize = keyDeleteBatchSize;
         int startIndex = 0;
@@ -1640,6 +1704,10 @@ private void moveToTrash(OmBucketInfo bucket, 
LimitedExpiredObjectList keysList)
       if (keysList.isEmpty()) {
         return;
       }
+      if (checkPolicyChange()) {
+        keysList.clear();
+        return;
+      }
       String volumeName = bucket.getVolumeName();
       String bucketName = bucket.getBucketName();
       String trashRoot = TRASH_PREFIX + OM_KEY_PREFIX + bucket.getOwner();
diff --git 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestKeyLifecycleService.java
 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestKeyLifecycleService.java
index 33e9a661810..3bf4e3d897b 100644
--- 
a/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestKeyLifecycleService.java
+++ 
b/hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/service/TestKeyLifecycleService.java
@@ -667,6 +667,70 @@ void testAbortedScanDoesNotMarkScanComplete(BucketLayout 
bucketLayout, boolean c
       deleteLifecyclePolicy(volumeName, bucketName);
     }
 
+    /**
+     * A task evaluates objects against the lifecycle configuration read when 
it was scheduled, so it must stop
+     * sending requests once the configuration is deleted or updated while it 
runs.
+     */
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    void testPolicyChangedDuringScan(boolean deletePolicy) throws Exception {
+      final String volumeName = getTestName();
+      final String bucketName = uniqueObjectName("bucket");
+      long initialDeletedKeyCount = getDeletedKeyCount();
+      long initialKeyCount = getKeyCount(OBJECT_STORE);
+
+      keyLifecycleService.suspend();
+      List<OmKeyArgs> keyList = createKeys(volumeName, bucketName, 
OBJECT_STORE, KEY_COUNT, 1, "key", null);
+      assertEquals(KEY_COUNT, keyList.size());
+      GenericTestUtils.waitFor(() -> getKeyCount(OBJECT_STORE) - 
initialKeyCount == KEY_COUNT,
+          WAIT_CHECK_INTERVAL, 1000);
+      ZonedDateTime date = 
ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(LONG_EXPIRE_SECONDS);
+      createLifecyclePolicy(volumeName, bucketName, OBJECT_STORE, "key", null, 
date.toString(), true);
+
+      GenericTestUtils.LogCapturer logCapturer = 
GenericTestUtils.LogCapturer.captureLogs(
+          LoggerFactory.getLogger(KeyLifecycleService.class));
+      FaultInjectorImpl taskStart = new FaultInjectorImpl();
+      FaultInjectorImpl beforeDelete = new FaultInjectorImpl();
+      FaultInjectorImpl exceptionInjector = new FaultInjectorImpl();
+      installInjectors(taskStart, beforeDelete, exceptionInjector);
+      keyLifecycleService.resume();
+      taskStart.awaitPaused(10000);
+      // Hold the next task at its start, so it cannot run with the updated 
configuration
+      FaultInjectorImpl nextTaskStart = new FaultInjectorImpl();
+      installInjectors(nextTaskStart, beforeDelete, exceptionInjector);
+      taskStart.release();
+      // The expired keys are found, and the task waits before sending the 
deletion request
+      beforeDelete.awaitPaused(10000);
+      String bucketKey = metadataManager.getBucketKey(volumeName, bucketName);
+      if (deletePolicy) {
+        deleteLifecyclePolicy(bucketKey);
+      } else {
+        OmLifecycleConfiguration policy = 
metadataManager.getLifecycleConfigurationTable().get(bucketKey);
+        putLifecyclePolicy(volumeName, bucketName, 
policy.toBuilder().setUpdateID(policy.getUpdateID() + 1).build(),
+            false);
+      }
+      beforeDelete.release();
+      if (deletePolicy) {
+        GenericTestUtils.waitFor(() -> 
keyLifecycleService.status().getRunningBucketsList().isEmpty(),
+            WAIT_CHECK_INTERVAL, 10000);
+      } else {
+        // BackgroundService waits for the previous batch, so the next task 
reaching its start means the task is done
+        nextTaskStart.awaitPaused(10000);
+      }
+
+      assertThat(logCapturer.getOutput())
+          .contains("Lifecycle configuration of bucket " + bucketKey + " is 
deleted or updated, stopping task");
+      assertEquals(0, getDeletedKeyCount() - initialDeletedKeyCount);
+      assertEquals(KEY_COUNT, getKeyCount(OBJECT_STORE) - initialKeyCount);
+      // A scan state may be saved before the configuration changes, but the 
scan is never saved as finished
+      OmLifecycleScanState scanState = 
metadataManager.getLifecycleScanStateTable().get(bucketKey);
+      assertTrue(scanState == null || scanState.getScanEndTime() == null);
+      if (!deletePolicy) {
+        deleteLifecyclePolicy(bucketKey);
+        nextTaskStart.release();
+      }
+    }
+
     @ParameterizedTest
     @MethodSource("parameters1")
     void testBucketScanWithScanEndTime(BucketLayout bucketLayout, boolean 
createPrefix) throws IOException,
@@ -1394,7 +1458,7 @@ void testCacheOnlyKeyNotSavedAsLastScannedKey() throws 
Exception {
       Table<String, OmLifecycleScanState> spyTable = spy(originalTable);
       tableField.set(metadataManager, spyTable);
       try {
-        runSingleLifecycleScan(volumeName, bucketName, false);
+        runSingleLifecycleScanAndDeleteConfiguration(volumeName, bucketName);
         GenericTestUtils.waitFor(() ->
             (getDeletedKeyCount() - initialDeletedKeyCount) == 3, 
WAIT_CHECK_INTERVAL, 10000);
         assertEquals(0, getKeyCount(FILE_SYSTEM_OPTIMIZED) - initialKeyCount);
@@ -3032,20 +3096,23 @@ void 
testMoveToTrashAbortTaskWhenTrashRootPrepareFails() throws Exception {
               () -> new TrashOzoneFileSystem(om));
       keyLifecycleService.setOzoneTrash(new OzoneTrash(fs, conf, om));
 
+      OmLCRule.Builder ruleBuilder = new OmLCRule.Builder()
+          .setId(String.valueOf(OBJECT_ID_COUNTER.getAndIncrement()))
+          .setPrefix("")
+          .setAction(new OmLCExpiration.Builder()
+              
.setDate(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(EXPIRE_SECONDS).toString())
+              .build());
       OmLifecycleConfiguration policy = new OmLifecycleConfiguration.Builder()
           .setVolume(volumeName)
           .setBucket(bucketName)
           .setBucketLayout(FILE_SYSTEM_OPTIMIZED)
           .setBucketObjectID(bucketObjectID)
-          .setRules(Collections.singletonList(new OmLCRule.Builder()
-              .setId(String.valueOf(OBJECT_ID_COUNTER.getAndIncrement()))
-              .setEnabled(true)
-              .setPrefix("")
-              .setAction(new OmLCExpiration.Builder()
-                  
.setDate(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(EXPIRE_SECONDS).toString())
-                  .build())
-              .build()))
+          
.setRules(Collections.singletonList(ruleBuilder.setEnabled(true).build()))
           .build();
+      // The task stops if its configuration is not stored. The stored copy 
has its rule disabled, so the service
+      // doesn't schedule its own task for this bucket while this test runs 
the task directly.
+      putLifecyclePolicy(volumeName, bucketName, policy.toBuilder()
+          
.setRules(Collections.singletonList(ruleBuilder.setEnabled(false).build())).build(),
 false);
 
       String expectedTrashRoot = new Path(TRASH_PREFIX + OM_KEY_PREFIX + 
bucketOwner, CURRENT).toString();
       OzoneManager omSpy = spy(om);
@@ -3197,6 +3264,104 @@ void testAbortIncompleteMultipartUploadWithFilters() 
throws Exception {
       deleteLifecyclePolicy(volumeName, bucketName);
     }
 
+    @Test
+    void testMultipartUploadScanResume() throws Exception {
+      final String volumeName = getTestName();
+      final String bucketName = uniqueObjectName("bucket");
+      String owner = UserGroupInformation.getCurrentUser().getShortUserName();
+
+      keyLifecycleService.suspend();
+      createVolumeAndBucket(volumeName, bucketName, OBJECT_STORE, owner);
+      long initialMpuCount = getMultipartUploadCount(volumeName, bucketName);
+      int uploadCount = 3;
+      long oldCreationTime = System.currentTimeMillis() - 
TimeUnit.DAYS.toMillis(2);
+      List<String> dbKeys = new ArrayList<>();
+      for (int i = 0; i < uploadCount; i++) {
+        String keyName = "uploads/file" + i;
+        OmMultipartInfo mpuInfo = createTestMultipartUpload(volumeName, 
bucketName, keyName, owner);
+        updateMultipartUploadCreationTime(volumeName, bucketName, keyName, 
mpuInfo.getUploadID(), oldCreationTime);
+        dbKeys.add(metadataManager.getMultipartKey(volumeName, bucketName, 
keyName, mpuInfo.getUploadID()));
+      }
+      Collections.sort(dbKeys);
+      OmLCRule rule = new OmLCRule.Builder()
+          .setId("abort-mpu-uploads")
+          .setEnabled(true)
+          .setFilter(new OmLCFilter.Builder().setPrefix("uploads/").build())
+          .setAction(new 
OmLCAbortIncompleteMultipartUpload.Builder().setDaysAfterInitiation(1).build())
+          .build();
+      createLifecyclePolicy(volumeName, bucketName, OBJECT_STORE, 
Collections.singletonList(rule));
+
+      // inject the resume state, pointing to the 2nd upload
+      String bucketKey = metadataManager.getBucketKey(volumeName, bucketName);
+      OmLifecycleConfiguration policy = 
metadataManager.getLifecycleConfiguration(volumeName, bucketName);
+      OmLifecycleScanState scanState = new OmLifecycleScanState.Builder()
+          .setBucketKey(bucketKey)
+          
.setBucketObjID(metadataManager.getBucketTable().get(bucketKey).getObjectID())
+          .setLifecycleConfigurationUpdateID(policy.getUpdateID())
+          .setScanStartTime(System.currentTimeMillis())
+          .setLastScannedMpuKey(dbKeys.get(1))
+          .build();
+      metadataManager.getLifecycleScanStateTable().put(bucketKey, scanState);
+      metadataManager.getLifecycleScanStateTable().addCacheEntry(new 
CacheKey<>(bucketKey),
+          CacheValue.get(1L, scanState));
+
+      runSingleLifecycleScanAndDeleteConfiguration(volumeName, bucketName);
+
+      // only the upload after the saved pointer is aborted
+      GenericTestUtils.waitFor(() -> getMultipartUploadCount(volumeName, 
bucketName) - initialMpuCount == 2,
+          WAIT_CHECK_INTERVAL, 10000);
+      
assertNotNull(metadataManager.getMultipartInfoTable().get(dbKeys.get(0)));
+      
assertNotNull(metadataManager.getMultipartInfoTable().get(dbKeys.get(1)));
+      assertNull(metadataManager.getMultipartInfoTable().get(dbKeys.get(2)));
+      OmLifecycleScanState savedState = 
metadataManager.getLifecycleScanStateTable().get(bucketKey);
+      assertEquals(dbKeys.get(2), savedState.getLastScannedMpuKey());
+      assertNotNull(savedState.getScanEndTime());
+    }
+
+    @Test
+    void testMultipartUploadScanPeriodicStateSave() throws Exception {
+      assumeTrue(maxKeysProcessedPerState == 1);
+      final String volumeName = getTestName();
+      final String bucketName = uniqueObjectName("bucket");
+      String owner = UserGroupInformation.getCurrentUser().getShortUserName();
+
+      keyLifecycleService.suspend();
+      createVolumeAndBucket(volumeName, bucketName, OBJECT_STORE, owner);
+      int uploadCount = 3;
+      for (int i = 0; i < uploadCount; i++) {
+        String keyName = "keep/file" + i;
+        OmMultipartInfo mpuInfo = createTestMultipartUpload(volumeName, 
bucketName, keyName, owner);
+        awaitMultipartCacheDrained(
+            metadataManager.getMultipartKey(volumeName, bucketName, keyName, 
mpuInfo.getUploadID()));
+      }
+      // no upload matches the rule, so the state is saved periodically 
without any abort request
+      OmLCRule rule = new OmLCRule.Builder()
+          .setId("abort-mpu-uploads")
+          .setEnabled(true)
+          .setFilter(new OmLCFilter.Builder().setPrefix("uploads/").build())
+          .setAction(new 
OmLCAbortIncompleteMultipartUpload.Builder().setDaysAfterInitiation(1).build())
+          .build();
+      createLifecyclePolicy(volumeName, bucketName, OBJECT_STORE, 
Collections.singletonList(rule));
+      String bucketKey = metadataManager.getBucketKey(volumeName, bucketName);
+
+      Field tableField = 
OmMetadataManagerImpl.class.getDeclaredField("lifecycleScanStateTable");
+      tableField.setAccessible(true);
+      Table<String, OmLifecycleScanState> originalTable =
+          (Table<String, OmLifecycleScanState>) 
tableField.get(metadataManager);
+      Table<String, OmLifecycleScanState> spyTable = spy(originalTable);
+      tableField.set(metadataManager, spyTable);
+      try {
+        runSingleLifecycleScanAndDeleteConfiguration(volumeName, bucketName);
+        verify(spyTable, atLeast(uploadCount))
+            .addCacheEntry(argThat(k -> k.getCacheKey().equals(bucketKey)), 
any());
+        OmLifecycleScanState savedState = 
metadataManager.getLifecycleScanStateTable().get(bucketKey);
+        assertNotNull(savedState.getScanEndTime());
+        assertEquals(uploadCount, getMultipartUploadCount(volumeName, 
bucketName));
+      } finally {
+        tableField.set(metadataManager, originalTable);
+      }
+    }
+
     @Test
     void testAbortIncompleteMultipartUploadWithTagFilter() throws Exception {
       final String volumeName = getTestName();
@@ -3843,27 +4008,22 @@ private void cleanUpService() throws Exception {
   // later and deletes the objects the caller expects to remain.
   private void runSingleLifecycleScanAndDeleteConfiguration(String volume, 
String bucket)
       throws IOException, TimeoutException, InterruptedException {
-    runSingleLifecycleScan(volume, bucket, true);
-  }
-
-  /**
-   * @param deletePolicy delete the policy once the task starts, so the bucket 
is not scanned again. Scan state is
-   *     not saved after the policy is deleted, so tests checking the saved 
scan state keep the policy instead.
-   */
-  private void runSingleLifecycleScan(String volume, String bucket, boolean 
deletePolicy)
-      throws IOException, TimeoutException, InterruptedException {
     FaultInjectorImpl taskStart = new FaultInjectorImpl();
     FaultInjectorImpl firstDelete = new FaultInjectorImpl();
     // The third injector is only read for an injected exception, but the scan 
expects it to exist
-    installInjectors(taskStart, firstDelete, new FaultInjectorImpl());
+    FaultInjectorImpl exceptionInjector = new FaultInjectorImpl();
+    installInjectors(taskStart, firstDelete, exceptionInjector);
     keyLifecycleService.resume();
     // The in-flight list is filled at schedule time, so wait for the task to 
reach the injector
     taskStart.awaitPaused(10000);
-    if (deletePolicy) {
-      deleteLifecyclePolicy(volume, bucket);
-    }
+    FaultInjectorImpl nextTaskStart = new FaultInjectorImpl();
+    installInjectors(nextTaskStart, firstDelete, exceptionInjector);
     taskStart.release();
     firstDelete.release();
+    // BackgroundService waits for the previous batch, so the next task 
reaching its start means the scan is done
+    nextTaskStart.awaitPaused(10000);
+    deleteLifecyclePolicy(volume, bucket);
+    nextTaskStart.release();
     GenericTestUtils.waitFor(() -> 
keyLifecycleService.status().getRunningBucketsList().isEmpty(),
         WAIT_CHECK_INTERVAL, 10000);
   }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to