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


##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -416,19 +459,358 @@ private void 
processEventBatchDirectly(OMUpdateEventBatch events) {
   public boolean hasEventBufferOverflowed() {
     return eventBuffer.getDroppedBatches() > 0;
   }
-  
-  @Override
+
+  /**
+   * Reset the event buffer overflow flag after full snapshot is completed.
+   */
   public void resetEventBufferOverflowFlag() {
     eventBuffer.resetDroppedBatches();
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+
+  /**
+   * Reset the task(s) failure flag after reinitialization is completed.
+   */
+  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.get());
+
+    ReInitializationResult reInitializationResult = 
validateRetryCountAndDelay();
+    if (reInitializationResult == ReInitializationResult.MAX_RETRIES_EXCEEDED) 
{
+      return reInitializationResult;
+    }
+
+    // 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.get() + 1);
+      checkpointedOMMetadataManager = 
createOMCheckpoint(currentOMMetadataManager);
+      LOG.info("Checkpoint creation succeeded");
+    } catch (IOException e) {
+      LOG.error("Checkpoint creation failed: {}", e.getMessage());
+      handleEventFailure();
+      return ReInitializationResult.RETRY_LATER;
+    }
+
+    // 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();
+      // Success - reset retry counters and flags
+      LOG.info("Successfully queued reinitialization event after {} retries", 
eventProcessRetryCount.get() + 1);
+      return ReconTaskController.ReInitializationResult.SUCCESS;
+    }
+    return null;
+  }
+
+  private ReconTaskController.ReInitializationResult 
validateRetryCountAndDelay() {
+    // Check if we should retry based on timing for iteration-based retries
+    long currentTime = System.currentTimeMillis();
+    if (eventProcessRetryCount.get() > 0) {
+      // Check if 2 seconds have passed since last iteration
+      long timeSinceLastRetry = currentTime - lastRetryTimestamp.get();
+      if (timeSinceLastRetry < RETRY_DELAY_MS) {
+        LOG.debug("Skipping retry, only {}ms since last retry attempt (need 
{}ms)",
+            timeSinceLastRetry, RETRY_DELAY_MS);
+        return ReInitializationResult.RETRY_LATER;
+      }
+      LOG.info("Attempting retry (retry attempt count: {}, delay: {}ms)",
+          eventProcessRetryCount.get() + 1, timeSinceLastRetry);
+    }
+    return getEventRetryResult();
+  }
+
+  /**
+   * Handle iteration failure by updating retry counters.
+   */
+  private void handleEventFailure() {
+    long currentTime = System.currentTimeMillis();
+    lastRetryTimestamp.set(currentTime);
+    eventProcessRetryCount.getAndIncrement();
+    LOG.error("Event processing failed {} times.", eventProcessRetryCount);
+  }
+  
+  /**
+   * Determine the appropriate retry result based on current event retry count.
+   */
+  private ReconTaskController.ReInitializationResult getEventRetryResult() {
+    if (eventProcessRetryCount.get() >= MAX_EVENT_PROCESS_RETRIES) {
+      LOG.warn("Maximum iteration retries ({}) exceeded, resetting counters 
and signaling full snapshot fallback",
+          MAX_EVENT_PROCESS_RETRIES);
+      resetRetryCounters();
+      return ReconTaskController.ReInitializationResult.MAX_RETRIES_EXCEEDED;
+    }
+    return null;
+  }
+
+  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");
+    this.currentOMMetadataManager = omMetadataManager;
+  }
+
+  /**
+   * 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
+   */
+  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" + "_" + 
UUID.randomUUID()).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();
+    // Use the checkpointed OM metadata manager for reinitialization to 
prevent data inconsistency
+    ReconOMMetadataManager checkpointedOMMetadataManager = 
event.getCheckpointedOMMetadataManager();
+    try {
+      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 new reinit event 
again.
+          tasksFailed.compareAndSet(false, true);
+          handleEventFailure();
+          LOG.error("Task reinitialization failed, tasksFailed flag set to 
true");
+        } else {
+          resetEventFlags();

Review Comment:
   remove resetEventFlags() here, as there may be next failure waiting. Its 
reset when put to queue is success.



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -416,19 +459,358 @@ private void 
processEventBatchDirectly(OMUpdateEventBatch events) {
   public boolean hasEventBufferOverflowed() {
     return eventBuffer.getDroppedBatches() > 0;
   }
-  
-  @Override
+
+  /**
+   * Reset the event buffer overflow flag after full snapshot is completed.
+   */
   public void resetEventBufferOverflowFlag() {
     eventBuffer.resetDroppedBatches();
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+
+  /**
+   * Reset the task(s) failure flag after reinitialization is completed.
+   */
+  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.get());
+
+    ReInitializationResult reInitializationResult = 
validateRetryCountAndDelay();
+    if (reInitializationResult == ReInitializationResult.MAX_RETRIES_EXCEEDED) 
{
+      return reInitializationResult;
+    }
+
+    // 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.get() + 1);
+      checkpointedOMMetadataManager = 
createOMCheckpoint(currentOMMetadataManager);
+      LOG.info("Checkpoint creation succeeded");
+    } catch (IOException e) {
+      LOG.error("Checkpoint creation failed: {}", e.getMessage());
+      handleEventFailure();
+      return ReInitializationResult.RETRY_LATER;
+    }
+
+    // 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();
+      // Success - reset retry counters and flags
+      LOG.info("Successfully queued reinitialization event after {} retries", 
eventProcessRetryCount.get() + 1);
+      return ReconTaskController.ReInitializationResult.SUCCESS;
+    }
+    return null;
+  }
+
+  private ReconTaskController.ReInitializationResult 
validateRetryCountAndDelay() {
+    // Check if we should retry based on timing for iteration-based retries
+    long currentTime = System.currentTimeMillis();
+    if (eventProcessRetryCount.get() > 0) {
+      // Check if 2 seconds have passed since last iteration
+      long timeSinceLastRetry = currentTime - lastRetryTimestamp.get();
+      if (timeSinceLastRetry < RETRY_DELAY_MS) {
+        LOG.debug("Skipping retry, only {}ms since last retry attempt (need 
{}ms)",
+            timeSinceLastRetry, RETRY_DELAY_MS);
+        return ReInitializationResult.RETRY_LATER;
+      }
+      LOG.info("Attempting retry (retry attempt count: {}, delay: {}ms)",
+          eventProcessRetryCount.get() + 1, timeSinceLastRetry);
+    }
+    return getEventRetryResult();
+  }
+
+  /**
+   * Handle iteration failure by updating retry counters.
+   */
+  private void handleEventFailure() {
+    long currentTime = System.currentTimeMillis();
+    lastRetryTimestamp.set(currentTime);
+    eventProcessRetryCount.getAndIncrement();
+    LOG.error("Event processing failed {} times.", eventProcessRetryCount);
+  }
+  
+  /**
+   * Determine the appropriate retry result based on current event retry count.
+   */
+  private ReconTaskController.ReInitializationResult getEventRetryResult() {
+    if (eventProcessRetryCount.get() >= MAX_EVENT_PROCESS_RETRIES) {
+      LOG.warn("Maximum iteration retries ({}) exceeded, resetting counters 
and signaling full snapshot fallback",
+          MAX_EVENT_PROCESS_RETRIES);
+      resetRetryCounters();
+      return ReconTaskController.ReInitializationResult.MAX_RETRIES_EXCEEDED;
+    }
+    return null;
+  }
+
+  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");

Review Comment:
   there will be frequent info log as its called every time in while loop for 
delta update



##########
hadoop-ozone/recon/src/main/java/org/apache/hadoop/ozone/recon/tasks/ReconTaskControllerImpl.java:
##########
@@ -416,19 +459,358 @@ private void 
processEventBatchDirectly(OMUpdateEventBatch events) {
   public boolean hasEventBufferOverflowed() {
     return eventBuffer.getDroppedBatches() > 0;
   }
-  
-  @Override
+
+  /**
+   * Reset the event buffer overflow flag after full snapshot is completed.
+   */
   public void resetEventBufferOverflowFlag() {
     eventBuffer.resetDroppedBatches();
   }
   
   @Override
-  public boolean hasDeltaTasksFailed() {
-    return deltaTasksFailed.get();
+  public boolean hasTasksFailed() {
+    return tasksFailed.get();
+  }
+
+  /**
+   * Reset the task(s) failure flag after reinitialization is completed.
+   */
+  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.get());
+
+    ReInitializationResult reInitializationResult = 
validateRetryCountAndDelay();
+    if (reInitializationResult == ReInitializationResult.MAX_RETRIES_EXCEEDED) 
{

Review Comment:
   it can return retry_later also, if null!= result, then we can return 
reInitializtionResult



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