sumitagrawl commented on code in PR #8962:
URL: https://github.com/apache/ozone/pull/8962#discussion_r2318802159


##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/recovery/ReconOmMetadataManagerImpl.java:
##########
@@ -72,6 +74,29 @@ public ReconOmMetadataManagerImpl(OzoneConfiguration 
configuration,
     this.ozoneConfiguration = configuration;
   }
 
+  private ReconOmMetadataManagerImpl(OzoneConfiguration configuration, File 
dir, String name) throws IOException {

Review Comment:
   Need set reconUtils for completeness of constructor if used later on to 
avoid issue.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/spi/impl/OzoneManagerServiceProviderImpl.java:
##########
@@ -663,30 +665,45 @@ public boolean syncDataFromOM() {
               
fullSnapshotReconTaskUpdater.setLastUpdatedSeqNumber(getCurrentOMDBSequenceNumber());
               deltaReconTaskStatusUpdater.recordRunCompletion();
               fullSnapshotReconTaskUpdater.updateDetails();
+              // Update the current OM metadata manager in task controller
+              reconTaskController.updateOMMetadataManager(omMetadataManager);

Review Comment:
   this call cleanup existing checkpoint also, but to be done only first time 
on startup, and its already done in ControllerImpl.start(). need change its 
implementation to remove this cleanup.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskController.java:
##########
@@ -78,14 +91,60 @@ void consumeOMEvents(OMUpdateEventBatch events,
   void resetEventBufferOverflowFlag();
 
   /**
-   * Check if delta tasks have failed and need reinitialization.
+   * Check if task(s) have failed and need reinitialization.
    * 
-   * @return true if delta tasks failed after retry
+   * @return true if task(s) failed after retry
+   */
+  boolean hasTasksFailed();
+
+  /**
+   * Reset the task(s) failure flag after reinitialization is completed.
    */
-  boolean hasDeltaTasksFailed();
+  void resetTasksFailureFlag();
 
   /**
-   * Reset the delta tasks failure flag after reinitialization is completed.
+   * Queue a task reinitialization event to be processed asynchronously.
+   * This method creates a checkpoint of the current OM metadata manager,
+   * clears the event buffer and queues a reinitialization event.
+   * Includes internal retry logic with timing controls for checkpoint 
creation.
+   * 
+   * @param reason the reason for reinitialization
+   * @return ReInitializationResult indicating success, retry needed, or max 
retries exceeded
+   */
+  ReInitializationResult 
queueReInitializationEvent(ReconTaskReInitializationEvent.ReInitializationReason
 reason);
+
+  /**
+   * Create a checkpoint of the current OM metadata manager.
+   * This method creates a snapshot of the current OM database state 
+   * to prevent data inconsistency during reinitialization.
+   * 
+   * @param omMetaManager the OM metadata manager to checkpoint
+   * @return a checkpointed ReconOMMetadataManager instance
+   * @throws IOException if checkpoint creation fails
    */
-  void resetDeltaTasksFailureFlag();
+  ReconOMMetadataManager createOMCheckpoint(ReconOMMetadataManager 
omMetaManager) throws IOException;
+  
+  /**
+   * Update the current OM metadata manager reference for reinitialization.
+   * 
+   * @param omMetadataManager the current OM metadata manager
+   */
+  void updateOMMetadataManager(ReconOMMetadataManager omMetadataManager);
+  
+  /**
+   * Get the current size of the event buffer.
+   * 
+   * @return the number of events currently in the buffer
+   */
+  @VisibleForTesting
+  int getEventBufferSize();
+  
+  /**
+   * Get the number of batches that have been dropped due to buffer overflow.
+   * This is used by the overflow detection logic.
+   * 
+   * @return the number of dropped batches
+   */
+  long getDroppedBatches();

Review Comment:
   this also not required to be exposed



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -71,7 +76,15 @@ public class ReconTaskControllerImpl implements 
ReconTaskController {
   private final ReconTaskStatusUpdaterManager taskStatusUpdaterManager;
   private final OMUpdateEventBuffer eventBuffer;
   private ExecutorService eventProcessingExecutor;
-  private final AtomicBoolean deltaTasksFailed = new AtomicBoolean(false);
+  private final AtomicBoolean tasksFailed = new AtomicBoolean(false);
+  private volatile ReconOMMetadataManager currentOMMetadataManager;
+  private final OzoneConfiguration configuration;
+  
+  // Retry logic for checkpoint creation
+  private int eventProcessRetryCount = 0;

Review Comment:
   This needs to be AtomicInteger, as well as timestamp.,



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -423,12 +463,348 @@ public void resetEventBufferOverflowFlag() {
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+  
+  @Override
+  public void resetTasksFailureFlag() {
+    tasksFailed.compareAndSet(true, false);
+  }
+
+  @Override
+  public synchronized ReconTaskController.ReInitializationResult 
queueReInitializationEvent(
+      ReconTaskReInitializationEvent.ReInitializationReason reason) {
+    LOG.info("Queueing task reinitialization event due to: {} (retry attempt 
count: {})", reason,
+        eventProcessRetryCount);
+
+    Long currentTime = validateRetryCountAndDelay();
+    if (currentTime == null) {
+      return ReInitializationResult.RETRY_LATER;
+    }
+
+    // Drain all events in buffer and cleanup any existing checkpoints before 
falling back to full snapshot.
+    // Events can be present in queue when reinit checkpoint creation fails 
multiple times because only after
+    // successful creation of checkpoint, we are clearing the event buffer.
+    drainEventBufferAndCleanExistingCheckpoints();
+
+    // Try checkpoint creation (single attempt per iteration)
+    ReconOMMetadataManager checkpointedOMMetadataManager = null;
+    
+    try {
+      LOG.info("Attempting checkpoint creation (retry attempt: {})", 
eventProcessRetryCount + 1);
+      checkpointedOMMetadataManager = 
createOMCheckpoint(currentOMMetadataManager);
+      LOG.info("Checkpoint creation succeeded");
+    } catch (IOException e) {
+      LOG.error("Checkpoint creation failed: {}", e.getMessage());
+      handleEventFailure(currentTime);
+      return getEventRetryResult();
+    }
+
+    // Create and queue the reinitialization event with checkpointed metadata 
manager
+    ReconTaskReInitializationEvent reinitEvent =
+        new ReconTaskReInitializationEvent(reason, 
checkpointedOMMetadataManager);
+    boolean queued = eventBuffer.offer(reinitEvent);
+    // If reinitialization event queued successfully, reset event buffer 
overflow flag and task failure flag,
+    // so that we can resume queuing the delta events.
+    if (queued) {
+      resetEventFlags();
+      resetRetryCounters();
+      // Success - reset retry counters and flags
+      LOG.info("Successfully queued reinitialization event after {} retries", 
eventProcessRetryCount + 1);
+      return ReconTaskController.ReInitializationResult.SUCCESS;
+    }
+    return null;
+  }
+
+  private Long validateRetryCountAndDelay() {
+    // Check if we should retry based on timing for iteration-based retries
+    long currentTime = System.currentTimeMillis();
+    if (eventProcessRetryCount > 0) {
+      // Check if 2 seconds have passed since last iteration
+      long timeSinceLastRetry = currentTime - lastCheckpointRetryTimestamp;
+      if (timeSinceLastRetry < RETRY_DELAY_MS) {
+        LOG.debug("Skipping checkpoint creation retry, only {}ms since last 
retry attempt (need {}ms)",
+            timeSinceLastRetry, RETRY_DELAY_MS);
+        return null;
+      }
+      LOG.info("Attempting retry for checkpoint creation (retry attempt count: 
{}, delay: {}ms)",
+          eventProcessRetryCount + 1, timeSinceLastRetry);
+    }
+    return currentTime;
+  }
+
+  /**
+   * Handle iteration failure by updating retry counters.
+   */
+  private void handleEventFailure(long currentTime) {
+    eventProcessRetryCount++;
+    lastCheckpointRetryTimestamp = currentTime;
+    LOG.error("Event processing failed {} times.", eventProcessRetryCount);
+  }
+  
+  /**
+   * Determine the appropriate retry result based on current event retry count.
+   */
+  private ReconTaskController.ReInitializationResult getEventRetryResult() {
+    if (eventProcessRetryCount >= MAX_EVENT_PROCESS_RETRIES) {
+      LOG.warn("Maximum iteration retries ({}) exceeded, resetting counters 
and signaling full snapshot fallback",
+          MAX_EVENT_PROCESS_RETRIES);
+      eventProcessRetryCount = 0;

Review Comment:
   call resetRetryCounters() here also to have common place update



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -423,12 +463,348 @@ public void resetEventBufferOverflowFlag() {
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+  
+  @Override
+  public void resetTasksFailureFlag() {
+    tasksFailed.compareAndSet(true, false);
+  }
+
+  @Override
+  public synchronized ReconTaskController.ReInitializationResult 
queueReInitializationEvent(
+      ReconTaskReInitializationEvent.ReInitializationReason reason) {
+    LOG.info("Queueing task reinitialization event due to: {} (retry attempt 
count: {})", reason,
+        eventProcessRetryCount);
+
+    Long currentTime = validateRetryCountAndDelay();
+    if (currentTime == null) {
+      return ReInitializationResult.RETRY_LATER;
+    }
+
+    // Drain all events in buffer and cleanup any existing checkpoints before 
falling back to full snapshot.
+    // Events can be present in queue when reinit checkpoint creation fails 
multiple times because only after
+    // successful creation of checkpoint, we are clearing the event buffer.
+    drainEventBufferAndCleanExistingCheckpoints();
+
+    // Try checkpoint creation (single attempt per iteration)
+    ReconOMMetadataManager checkpointedOMMetadataManager = null;
+    
+    try {
+      LOG.info("Attempting checkpoint creation (retry attempt: {})", 
eventProcessRetryCount + 1);
+      checkpointedOMMetadataManager = 
createOMCheckpoint(currentOMMetadataManager);
+      LOG.info("Checkpoint creation succeeded");
+    } catch (IOException e) {
+      LOG.error("Checkpoint creation failed: {}", e.getMessage());
+      handleEventFailure(currentTime);
+      return getEventRetryResult();
+    }
+
+    // Create and queue the reinitialization event with checkpointed metadata 
manager
+    ReconTaskReInitializationEvent reinitEvent =
+        new ReconTaskReInitializationEvent(reason, 
checkpointedOMMetadataManager);
+    boolean queued = eventBuffer.offer(reinitEvent);
+    // If reinitialization event queued successfully, reset event buffer 
overflow flag and task failure flag,
+    // so that we can resume queuing the delta events.
+    if (queued) {
+      resetEventFlags();
+      resetRetryCounters();

Review Comment:
   we should update resetRetryCounters() only when reprocess is completed 
successfully, not here.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskController.java:
##########
@@ -78,14 +91,60 @@ void consumeOMEvents(OMUpdateEventBatch events,
   void resetEventBufferOverflowFlag();
 
   /**
-   * Check if delta tasks have failed and need reinitialization.
+   * Check if task(s) have failed and need reinitialization.
    * 
-   * @return true if delta tasks failed after retry
+   * @return true if task(s) failed after retry
+   */
+  boolean hasTasksFailed();
+
+  /**
+   * Reset the task(s) failure flag after reinitialization is completed.
    */
-  boolean hasDeltaTasksFailed();
+  void resetTasksFailureFlag();
 
   /**
-   * Reset the delta tasks failure flag after reinitialization is completed.
+   * Queue a task reinitialization event to be processed asynchronously.
+   * This method creates a checkpoint of the current OM metadata manager,
+   * clears the event buffer and queues a reinitialization event.
+   * Includes internal retry logic with timing controls for checkpoint 
creation.
+   * 
+   * @param reason the reason for reinitialization
+   * @return ReInitializationResult indicating success, retry needed, or max 
retries exceeded
+   */
+  ReInitializationResult 
queueReInitializationEvent(ReconTaskReInitializationEvent.ReInitializationReason
 reason);
+
+  /**
+   * Create a checkpoint of the current OM metadata manager.
+   * This method creates a snapshot of the current OM database state 
+   * to prevent data inconsistency during reinitialization.
+   * 
+   * @param omMetaManager the OM metadata manager to checkpoint
+   * @return a checkpointed ReconOMMetadataManager instance
+   * @throws IOException if checkpoint creation fails
    */
-  void resetDeltaTasksFailureFlag();
+  ReconOMMetadataManager createOMCheckpoint(ReconOMMetadataManager 
omMetaManager) throws IOException;

Review Comment:
   this may not be exposed



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskController.java:
##########
@@ -78,14 +91,60 @@ void consumeOMEvents(OMUpdateEventBatch events,
   void resetEventBufferOverflowFlag();
 
   /**
-   * Check if delta tasks have failed and need reinitialization.
+   * Check if task(s) have failed and need reinitialization.
    * 
-   * @return true if delta tasks failed after retry
+   * @return true if task(s) failed after retry
+   */
+  boolean hasTasksFailed();
+
+  /**
+   * Reset the task(s) failure flag after reinitialization is completed.
    */
-  boolean hasDeltaTasksFailed();
+  void resetTasksFailureFlag();

Review Comment:
   resetTasksFailureFlag may not required to be exposed, and also 
resetEventBufferOverflowFlag



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -423,12 +463,348 @@ public void resetEventBufferOverflowFlag() {
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+  
+  @Override
+  public void resetTasksFailureFlag() {
+    tasksFailed.compareAndSet(true, false);
+  }
+
+  @Override
+  public synchronized ReconTaskController.ReInitializationResult 
queueReInitializationEvent(
+      ReconTaskReInitializationEvent.ReInitializationReason reason) {
+    LOG.info("Queueing task reinitialization event due to: {} (retry attempt 
count: {})", reason,
+        eventProcessRetryCount);
+
+    Long currentTime = validateRetryCountAndDelay();
+    if (currentTime == null) {
+      return ReInitializationResult.RETRY_LATER;
+    }
+
+    // Drain all events in buffer and cleanup any existing checkpoints before 
falling back to full snapshot.
+    // Events can be present in queue when reinit checkpoint creation fails 
multiple times because only after
+    // successful creation of checkpoint, we are clearing the event buffer.
+    drainEventBufferAndCleanExistingCheckpoints();
+
+    // Try checkpoint creation (single attempt per iteration)
+    ReconOMMetadataManager checkpointedOMMetadataManager = null;
+    
+    try {
+      LOG.info("Attempting checkpoint creation (retry attempt: {})", 
eventProcessRetryCount + 1);
+      checkpointedOMMetadataManager = 
createOMCheckpoint(currentOMMetadataManager);
+      LOG.info("Checkpoint creation succeeded");
+    } catch (IOException e) {
+      LOG.error("Checkpoint creation failed: {}", e.getMessage());
+      handleEventFailure(currentTime);
+      return getEventRetryResult();
+    }
+
+    // Create and queue the reinitialization event with checkpointed metadata 
manager
+    ReconTaskReInitializationEvent reinitEvent =
+        new ReconTaskReInitializationEvent(reason, 
checkpointedOMMetadataManager);
+    boolean queued = eventBuffer.offer(reinitEvent);
+    // If reinitialization event queued successfully, reset event buffer 
overflow flag and task failure flag,
+    // so that we can resume queuing the delta events.
+    if (queued) {
+      resetEventFlags();
+      resetRetryCounters();
+      // Success - reset retry counters and flags
+      LOG.info("Successfully queued reinitialization event after {} retries", 
eventProcessRetryCount + 1);
+      return ReconTaskController.ReInitializationResult.SUCCESS;
+    }
+    return null;
+  }
+
+  private Long validateRetryCountAndDelay() {
+    // Check if we should retry based on timing for iteration-based retries
+    long currentTime = System.currentTimeMillis();
+    if (eventProcessRetryCount > 0) {
+      // Check if 2 seconds have passed since last iteration
+      long timeSinceLastRetry = currentTime - lastCheckpointRetryTimestamp;
+      if (timeSinceLastRetry < RETRY_DELAY_MS) {
+        LOG.debug("Skipping checkpoint creation retry, only {}ms since last 
retry attempt (need {}ms)",
+            timeSinceLastRetry, RETRY_DELAY_MS);
+        return null;
+      }
+      LOG.info("Attempting retry for checkpoint creation (retry attempt count: 
{}, delay: {}ms)",
+          eventProcessRetryCount + 1, timeSinceLastRetry);
+    }
+    return currentTime;
+  }
+
+  /**
+   * Handle iteration failure by updating retry counters.
+   */
+  private void handleEventFailure(long currentTime) {
+    eventProcessRetryCount++;
+    lastCheckpointRetryTimestamp = currentTime;
+    LOG.error("Event processing failed {} times.", eventProcessRetryCount);
+  }
+  
+  /**
+   * Determine the appropriate retry result based on current event retry count.
+   */
+  private ReconTaskController.ReInitializationResult getEventRetryResult() {
+    if (eventProcessRetryCount >= MAX_EVENT_PROCESS_RETRIES) {
+      LOG.warn("Maximum iteration retries ({}) exceeded, resetting counters 
and signaling full snapshot fallback",
+          MAX_EVENT_PROCESS_RETRIES);
+      eventProcessRetryCount = 0;
+      lastCheckpointRetryTimestamp = 0;
+      return ReconTaskController.ReInitializationResult.MAX_RETRIES_EXCEEDED;
+    } else {
+      return ReconTaskController.ReInitializationResult.RETRY_LATER;
+    }
+  }
+
+  public void drainEventBufferAndCleanExistingCheckpoints() {
+    // First drain all events to check for any ReconTaskReInitializationEvent 
that need checkpoint cleanup
+    List<ReconEvent> drainedEvents = new ArrayList<>();
+    int drainedCount = eventBuffer.drainTo(drainedEvents);
+    
+    if (drainedCount > 0) {
+      LOG.info("Drained {} events from buffer before clearing. Checking for 
checkpoint cleanup.", drainedCount);
+      
+      // Check for any ReconTaskReInitializationEvent and cleanup their 
checkpoints
+      for (ReconEvent event : drainedEvents) {
+        if (event instanceof ReconTaskReInitializationEvent) {
+          ReconTaskReInitializationEvent reinitEvent = 
(ReconTaskReInitializationEvent) event;
+          ReconOMMetadataManager checkpointedManager = 
reinitEvent.getCheckpointedOMMetadataManager();
+          if (checkpointedManager != null) {
+            LOG.info("Cleaning up unprocessed checkpoint from drained 
ReconTaskReInitializationEvent");
+            cleanupCheckpoint(checkpointedManager);
+          }
+        }
+      }
+    }
+  }
+
+  @Override
+  public void updateOMMetadataManager(ReconOMMetadataManager 
omMetadataManager) {
+    LOG.info("Updating OM metadata manager");
+    
+    // Clean up any pre-existing checkpoint directories when setting new 
manager
+    if (omMetadataManager != null) {
+      cleanupPreExistingCheckpoints();
+    }
+    
+    this.currentOMMetadataManager = omMetadataManager;
+  }
+
+  @Override
+  public ReconOMMetadataManager createOMCheckpoint(ReconOMMetadataManager 
omMetaManager) 
+      throws IOException {
+    // Create temporary directory for checkpoint
+    String parentPath = cleanTempCheckPointPath(omMetaManager);
+    
+    // Create checkpoint
+    DBCheckpoint checkpoint = 
omMetaManager.getStore().getCheckpoint(parentPath, true);
+    
+    return omMetaManager.createCheckpointReconMetadataManager(configuration, 
checkpoint);
+  }
+
+  /**
+   * Clean and prepare temporary checkpoint path.
+   * Similar to QuotaRepairTask.cleanTempCheckPointPath.
+   * 
+   * @param omMetaManager the OM metadata manager
+   * @return path to temporary checkpoint directory
+   * @throws IOException if directory operations fail
+   */
+  private String cleanTempCheckPointPath(ReconOMMetadataManager omMetaManager) 
throws IOException {
+    File dbLocation = omMetaManager.getStore().getDbLocation();
+    if (dbLocation == null) {
+      throw new NullPointerException("OM DB location is null");
+    }
+    String tempData = dbLocation.getParent();
+    if (tempData == null) {
+      throw new NullPointerException("Parent OM DB dir is null");
+    }
+    File reinitTmpPath =
+        Paths.get(tempData, "temp-recon-reinit-checkpoint" + "_" + 
System.currentTimeMillis()).toFile();

Review Comment:
   time based checkpoint dir can fail, if trigger is quick. it does not ensure 
uniqueness



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -423,12 +463,348 @@ public void resetEventBufferOverflowFlag() {
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+  
+  @Override
+  public void resetTasksFailureFlag() {
+    tasksFailed.compareAndSet(true, false);
+  }
+
+  @Override
+  public synchronized ReconTaskController.ReInitializationResult 
queueReInitializationEvent(
+      ReconTaskReInitializationEvent.ReInitializationReason reason) {
+    LOG.info("Queueing task reinitialization event due to: {} (retry attempt 
count: {})", reason,
+        eventProcessRetryCount);
+
+    Long currentTime = validateRetryCountAndDelay();
+    if (currentTime == null) {
+      return ReInitializationResult.RETRY_LATER;
+    }
+
+    // Drain all events in buffer and cleanup any existing checkpoints before 
falling back to full snapshot.
+    // Events can be present in queue when reinit checkpoint creation fails 
multiple times because only after
+    // successful creation of checkpoint, we are clearing the event buffer.
+    drainEventBufferAndCleanExistingCheckpoints();
+
+    // Try checkpoint creation (single attempt per iteration)
+    ReconOMMetadataManager checkpointedOMMetadataManager = null;
+    
+    try {
+      LOG.info("Attempting checkpoint creation (retry attempt: {})", 
eventProcessRetryCount + 1);
+      checkpointedOMMetadataManager = 
createOMCheckpoint(currentOMMetadataManager);
+      LOG.info("Checkpoint creation succeeded");
+    } catch (IOException e) {
+      LOG.error("Checkpoint creation failed: {}", e.getMessage());
+      handleEventFailure(currentTime);
+      return getEventRetryResult();
+    }
+
+    // Create and queue the reinitialization event with checkpointed metadata 
manager
+    ReconTaskReInitializationEvent reinitEvent =
+        new ReconTaskReInitializationEvent(reason, 
checkpointedOMMetadataManager);
+    boolean queued = eventBuffer.offer(reinitEvent);
+    // If reinitialization event queued successfully, reset event buffer 
overflow flag and task failure flag,
+    // so that we can resume queuing the delta events.
+    if (queued) {
+      resetEventFlags();
+      resetRetryCounters();
+      // Success - reset retry counters and flags
+      LOG.info("Successfully queued reinitialization event after {} retries", 
eventProcessRetryCount + 1);
+      return ReconTaskController.ReInitializationResult.SUCCESS;
+    }
+    return null;
+  }
+
+  private Long validateRetryCountAndDelay() {
+    // Check if we should retry based on timing for iteration-based retries
+    long currentTime = System.currentTimeMillis();
+    if (eventProcessRetryCount > 0) {
+      // Check if 2 seconds have passed since last iteration
+      long timeSinceLastRetry = currentTime - lastCheckpointRetryTimestamp;
+      if (timeSinceLastRetry < RETRY_DELAY_MS) {
+        LOG.debug("Skipping checkpoint creation retry, only {}ms since last 
retry attempt (need {}ms)",
+            timeSinceLastRetry, RETRY_DELAY_MS);
+        return null;
+      }
+      LOG.info("Attempting retry for checkpoint creation (retry attempt count: 
{}, delay: {}ms)",
+          eventProcessRetryCount + 1, timeSinceLastRetry);
+    }
+    return currentTime;
+  }
+
+  /**
+   * Handle iteration failure by updating retry counters.
+   */
+  private void handleEventFailure(long currentTime) {
+    eventProcessRetryCount++;
+    lastCheckpointRetryTimestamp = currentTime;
+    LOG.error("Event processing failed {} times.", eventProcessRetryCount);
+  }
+  
+  /**
+   * Determine the appropriate retry result based on current event retry count.
+   */
+  private ReconTaskController.ReInitializationResult getEventRetryResult() {
+    if (eventProcessRetryCount >= MAX_EVENT_PROCESS_RETRIES) {
+      LOG.warn("Maximum iteration retries ({}) exceeded, resetting counters 
and signaling full snapshot fallback",
+          MAX_EVENT_PROCESS_RETRIES);
+      eventProcessRetryCount = 0;
+      lastCheckpointRetryTimestamp = 0;
+      return ReconTaskController.ReInitializationResult.MAX_RETRIES_EXCEEDED;
+    } else {
+      return ReconTaskController.ReInitializationResult.RETRY_LATER;
+    }
+  }
+
+  public void drainEventBufferAndCleanExistingCheckpoints() {
+    // First drain all events to check for any ReconTaskReInitializationEvent 
that need checkpoint cleanup
+    List<ReconEvent> drainedEvents = new ArrayList<>();
+    int drainedCount = eventBuffer.drainTo(drainedEvents);
+    
+    if (drainedCount > 0) {
+      LOG.info("Drained {} events from buffer before clearing. Checking for 
checkpoint cleanup.", drainedCount);
+      
+      // Check for any ReconTaskReInitializationEvent and cleanup their 
checkpoints
+      for (ReconEvent event : drainedEvents) {
+        if (event instanceof ReconTaskReInitializationEvent) {
+          ReconTaskReInitializationEvent reinitEvent = 
(ReconTaskReInitializationEvent) event;
+          ReconOMMetadataManager checkpointedManager = 
reinitEvent.getCheckpointedOMMetadataManager();
+          if (checkpointedManager != null) {
+            LOG.info("Cleaning up unprocessed checkpoint from drained 
ReconTaskReInitializationEvent");
+            cleanupCheckpoint(checkpointedManager);
+          }
+        }
+      }
+    }
+  }
+
+  @Override
+  public void updateOMMetadataManager(ReconOMMetadataManager 
omMetadataManager) {
+    LOG.info("Updating OM metadata manager");
+    
+    // Clean up any pre-existing checkpoint directories when setting new 
manager
+    if (omMetadataManager != null) {
+      cleanupPreExistingCheckpoints();
+    }
+    
+    this.currentOMMetadataManager = omMetadataManager;
+  }
+
+  @Override
+  public ReconOMMetadataManager createOMCheckpoint(ReconOMMetadataManager 
omMetaManager) 
+      throws IOException {
+    // Create temporary directory for checkpoint
+    String parentPath = cleanTempCheckPointPath(omMetaManager);
+    
+    // Create checkpoint
+    DBCheckpoint checkpoint = 
omMetaManager.getStore().getCheckpoint(parentPath, true);
+    
+    return omMetaManager.createCheckpointReconMetadataManager(configuration, 
checkpoint);
+  }
+
+  /**
+   * Clean and prepare temporary checkpoint path.
+   * Similar to QuotaRepairTask.cleanTempCheckPointPath.
+   * 
+   * @param omMetaManager the OM metadata manager
+   * @return path to temporary checkpoint directory
+   * @throws IOException if directory operations fail
+   */
+  private String cleanTempCheckPointPath(ReconOMMetadataManager omMetaManager) 
throws IOException {
+    File dbLocation = omMetaManager.getStore().getDbLocation();
+    if (dbLocation == null) {
+      throw new NullPointerException("OM DB location is null");
+    }
+    String tempData = dbLocation.getParent();
+    if (tempData == null) {
+      throw new NullPointerException("Parent OM DB dir is null");
+    }
+    File reinitTmpPath =
+        Paths.get(tempData, "temp-recon-reinit-checkpoint" + "_" + 
System.currentTimeMillis()).toFile();
+    FileUtils.deleteDirectory(reinitTmpPath);
+    FileUtils.forceMkdir(reinitTmpPath);
+    return reinitTmpPath.toString();
+  }
+  
+  /**
+   * Process a task reinitialization event asynchronously.
+   */
+  private void processReInitializationEvent(ReconTaskReInitializationEvent 
event) {
+    LOG.info("Processing reinitialization event: reason={}, timestamp={}", 
+        event.getReason(), event.getTimestamp());
+    resetTasksFailureFlag();
+    try {
+      // Use the checkpointed OM metadata manager for reinitialization to 
prevent data inconsistency
+      ReconOMMetadataManager checkpointedOMMetadataManager = 
event.getCheckpointedOMMetadataManager();
+      if (checkpointedOMMetadataManager != null) {
+        LOG.info("Starting async task reinitialization with checkpointed OM 
metadata manager due to: {}",
+                 event.getReason());
+        boolean isRunSuccessful = 
reInitializeTasks(checkpointedOMMetadataManager, null);
+        if (!isRunSuccessful) {
+          // Setting this taskFailed flag as true here will block consuming 
delta events and stop buffering events
+          // in eventBuffer until we successfully queue a reinit event and 
also reprocess all the tasks of
+          // the reinit event succeed.
+          tasksFailed.compareAndSet(false, true);
+          LOG.error("Task reinitialization failed, tasksFailed flag set to 
true");
+        } else {
+          resetEventFlags();
+          resetRetryCounters();
+          LOG.info("Completed async task reinitialization");
+        }
+        
+        // Clean up the checkpointed metadata manager and its files after use
+        cleanupCheckpoint(checkpointedOMMetadataManager);

Review Comment:
   cleanup checkpoint in finally for all cases



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -423,12 +463,348 @@ public void resetEventBufferOverflowFlag() {
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+  
+  @Override
+  public void resetTasksFailureFlag() {
+    tasksFailed.compareAndSet(true, false);
+  }
+
+  @Override
+  public synchronized ReconTaskController.ReInitializationResult 
queueReInitializationEvent(
+      ReconTaskReInitializationEvent.ReInitializationReason reason) {
+    LOG.info("Queueing task reinitialization event due to: {} (retry attempt 
count: {})", reason,
+        eventProcessRetryCount);
+
+    Long currentTime = validateRetryCountAndDelay();
+    if (currentTime == null) {
+      return ReInitializationResult.RETRY_LATER;
+    }
+
+    // Drain all events in buffer and cleanup any existing checkpoints before 
falling back to full snapshot.
+    // Events can be present in queue when reinit checkpoint creation fails 
multiple times because only after
+    // successful creation of checkpoint, we are clearing the event buffer.
+    drainEventBufferAndCleanExistingCheckpoints();
+
+    // Try checkpoint creation (single attempt per iteration)
+    ReconOMMetadataManager checkpointedOMMetadataManager = null;
+    
+    try {
+      LOG.info("Attempting checkpoint creation (retry attempt: {})", 
eventProcessRetryCount + 1);
+      checkpointedOMMetadataManager = 
createOMCheckpoint(currentOMMetadataManager);
+      LOG.info("Checkpoint creation succeeded");
+    } catch (IOException e) {
+      LOG.error("Checkpoint creation failed: {}", e.getMessage());
+      handleEventFailure(currentTime);

Review Comment:
   I think failure count is handled for for checkpoint creation, not for 
continuous reprocess failure. Adding that need have this before 
create-checkpoint itself.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to