jtao15 commented on a change in pull request #7178:
URL: https://github.com/apache/pinot/pull/7178#discussion_r685448810



##########
File path: 
pinot-plugins/pinot-minion-tasks/pinot-minion-builtin-tasks/src/main/java/org/apache/pinot/plugin/minion/tasks/merge_rollup/MergeRollupTaskGenerator.java
##########
@@ -0,0 +1,491 @@
+/**
+ * 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.pinot.plugin.minion.tasks.merge_rollup;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import org.I0Itec.zkclient.exception.ZkException;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.task.TaskState;
+import org.apache.pinot.common.lineage.SegmentLineage;
+import org.apache.pinot.common.lineage.SegmentLineageUtils;
+import org.apache.pinot.common.metadata.segment.OfflineSegmentZKMetadata;
+import org.apache.pinot.common.minion.MergeRollupTaskMetadata;
+import org.apache.pinot.controller.helix.core.minion.ClusterInfoAccessor;
+import 
org.apache.pinot.controller.helix.core.minion.generator.PinotTaskGenerator;
+import 
org.apache.pinot.controller.helix.core.minion.generator.TaskGeneratorUtils;
+import org.apache.pinot.core.common.MinionConstants;
+import org.apache.pinot.core.common.MinionConstants.MergeRollupTask;
+import org.apache.pinot.core.minion.PinotTaskConfig;
+import org.apache.pinot.spi.annotations.minion.TaskGenerator;
+import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
+import org.apache.pinot.spi.config.table.SegmentPartitionConfig;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.TableTaskConfig;
+import org.apache.pinot.spi.config.table.TableType;
+import org.apache.pinot.spi.utils.IngestionConfigUtils;
+import org.apache.pinot.spi.utils.TimeUtils;
+import org.apache.pinot.spi.utils.builder.TableNameBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A {@link PinotTaskGenerator} implementation for generating tasks of type 
{@link MergeRollupTask}
+ *
+ * TODO: Add the support for realtime table
+ *
+ * Steps:
+ *
+ *  - Pre-select segments:
+ *    - Fetch all segments, select segments based on segment lineage (removing 
segmentsFrom for COMPLETED lineage entry and
+ *      segmentsTo for IN_PROGRESS lineage entry)
+ *    - Sort segments based on startTime and endTime in ascending order
+ *
+ *  For each mergeLevel (from lowest to highest, e.g. Hourly -> Daily -> 
Monthly -> Yearly):
+ *    - Skip scheduling if there's incomplete task for the mergeLevel
+ *    - Calculate merge/rollup window:
+ *      - Read watermarkMs from the {@link MergeRollupTaskMetadata} ZNode
+ *        found at MINION_TASK_METADATA/MergeRollupTask/<tableNameWithType>
+ *        In case of cold-start, no ZNode will exist.
+ *        A new ZNode will be created, with watermarkMs as the smallest time 
found in all segments truncated to the
+ *        closest bucket start time.
+ *      - The execution window for the task is calculated as,
+ *        windowStartMs = watermarkMs, windowEndMs = windowStartMs + 
bucketTimeMs
+ *      - Skip scheduling if the window is invalid:
+ *        - If the execution window is not older than bufferTimeMs, no task 
will be generated
+ *        - The windowEndMs of higher merge level should be less or equal to 
the waterMarkMs of lower level
+ *      - Bump up target window and watermark if needed.
+ *        - If there's no unmerged segments (by checking segment zk metadata 
{mergeRollupTask.mergeLevel: level}) for current window,
+ *          keep bumping up the watermark and target window until unmerged 
segments are found. Else skip the scheduling.
+ *    - Select all segments for the target window
+ *    - Create tasks (per partition for partitioned table) based on 
maxNumRecordsPerTask
+ */
+@TaskGenerator
+public class MergeRollupTaskGenerator implements PinotTaskGenerator {
+  private static final int DEFAULT_MAX_NUM_RECORDS_PER_TASK = 50_000_000;
+  private static final String REFRESH = "REFRESH";
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(MergeRollupTaskGenerator.class);
+
+  private ClusterInfoAccessor _clusterInfoAccessor;
+
+  @Override
+  public void init(ClusterInfoAccessor clusterInfoAccessor) {
+    _clusterInfoAccessor = clusterInfoAccessor;
+  }
+
+  @Override
+  public String getTaskType() {
+    return MergeRollupTask.TASK_TYPE;
+  }
+
+  @Override
+  public List<PinotTaskConfig> generateTasks(List<TableConfig> tableConfigs) {
+    String taskType = MergeRollupTask.TASK_TYPE;
+    List<PinotTaskConfig> pinotTaskConfigs = new ArrayList<>();
+
+    for (TableConfig tableConfig : tableConfigs) {
+      if (!validate(tableConfig, taskType)) {
+        continue;
+      }
+      String offlineTableName = tableConfig.getTableName();
+      LOGGER.info("Start generating task configs for table: {} for task: {}", 
offlineTableName, taskType);
+
+      // Get all segment metadata
+      Set<OfflineSegmentZKMetadata> allSegments =
+          new 
HashSet<>(_clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName));
+
+      // Select current segment snapshot based on lineage
+      SegmentLineage segmentLineage = 
_clusterInfoAccessor.getSegmentLineage(offlineTableName);
+      Set<String> preSelectedSegmentsBasedOnLineage = new HashSet<>();
+      for (OfflineSegmentZKMetadata offlineSegmentZKMetadata : allSegments) {
+        
preSelectedSegmentsBasedOnLineage.add(offlineSegmentZKMetadata.getSegmentName());
+      }
+      
SegmentLineageUtils.filterSegmentsBasedOnLineageInplace(preSelectedSegmentsBasedOnLineage,
 segmentLineage);
+
+      // Sort segments based on startTimeMs, endTimeMs and segmentName in 
ascending order
+      TreeSet<OfflineSegmentZKMetadata> preSelectedSegments = new 
TreeSet<>((a, b) -> {
+        long aStartTime = a.getStartTimeMs();
+        long bStartTime = b.getStartTimeMs();
+        if (aStartTime != bStartTime) {
+          return Long.compare(aStartTime, bStartTime);
+        }
+        long aEndTime = a.getEndTimeMs();
+        long bEndTime = b.getEndTimeMs();
+        return aEndTime != bEndTime ? Long.compare(aEndTime, bEndTime)
+            : a.getSegmentName().compareTo(b.getSegmentName());
+      });
+      for (OfflineSegmentZKMetadata segment : allSegments) {
+        if 
(preSelectedSegmentsBasedOnLineage.contains(segment.getSegmentName())) {
+          preSelectedSegments.add(segment);
+        }
+      }
+
+      if (preSelectedSegments.isEmpty()) {
+        LOGGER.info("Skip generating task: {} for table: {}, no segment is 
found to merge.", taskType,
+            offlineTableName);
+        continue;
+      }
+
+      // Sort merge levels based on bucket time period
+      Map<String, String> taskConfigs = 
tableConfig.getTaskConfig().getConfigsForTaskType(taskType);
+      Map<String, Map<String, String>> mergeLevelToConfigs = 
MergeRollupTaskUtils.getLevelToConfigMap(taskConfigs);
+      List<Map.Entry<String, Map<String, String>>> sortedMergeLevelConfigs =
+          new ArrayList<>(mergeLevelToConfigs.entrySet());
+      sortedMergeLevelConfigs.sort(Comparator.comparingLong(
+          e -> 
TimeUtils.convertPeriodToMillis(e.getValue().get(MinionConstants.MergeTask.BUCKET_TIME_PERIOD_KEY))));
+
+      // Get incomplete merge levels
+      Set<String> inCompleteMergeLevels = new HashSet<>();
+      for (Map.Entry<String, TaskState> entry : 
TaskGeneratorUtils.getIncompleteTasks(taskType, offlineTableName,
+          _clusterInfoAccessor).entrySet()) {
+        for (PinotTaskConfig taskConfig : 
_clusterInfoAccessor.getTaskConfigs(entry.getKey())) {
+          
inCompleteMergeLevels.add(taskConfig.getConfigs().get(MergeRollupTask.MERGE_LEVEL_KEY));
+        }
+      }
+
+      ZNRecord mergeRollupTaskZNRecord = 
_clusterInfoAccessor.getMinionMergeRollupTaskZNRecord(offlineTableName);
+      int expectedVersion = mergeRollupTaskZNRecord != null ? 
mergeRollupTaskZNRecord.getVersion() : -1;
+      MergeRollupTaskMetadata mergeRollupTaskMetadata =
+          mergeRollupTaskZNRecord != null ? 
MergeRollupTaskMetadata.fromZNRecord(mergeRollupTaskZNRecord)
+              : new MergeRollupTaskMetadata(offlineTableName, new TreeMap<>());
+      List<PinotTaskConfig> pinotTaskConfigsForTable = new ArrayList<>();
+
+      // Schedule tasks from lowest to highest merge level (e.g. Hourly -> 
Daily -> Monthly -> Yearly)
+      for (int i = 0; i < sortedMergeLevelConfigs.size(); i++) {
+        String lowerMergeLevel = i > 0 ? sortedMergeLevelConfigs.get(i - 
1).getKey() : null;
+        String mergeLevel = sortedMergeLevelConfigs.get(i).getKey();
+        Map<String, String> mergeConfigs = 
sortedMergeLevelConfigs.get(i).getValue();
+
+        // Skip scheduling if there's incomplete task for current mergeLevel
+        if (inCompleteMergeLevels.contains(mergeLevel)) {
+          LOGGER.info("Found incomplete task of merge level: {} for the same 
table: {}, Skipping task generation: {}",
+              mergeLevel, offlineTableName, taskType);
+          continue;
+        }
+
+        // Get the bucket size and buffer
+        long bucketMs =
+            
TimeUtils.convertPeriodToMillis(mergeConfigs.get(MinionConstants.MergeTask.BUCKET_TIME_PERIOD_KEY));
+        long bufferMs =
+            
TimeUtils.convertPeriodToMillis(mergeConfigs.get(MinionConstants.MergeTask.BUFFER_TIME_PERIOD_KEY));
+
+        // Get watermark from MergeRollupTaskMetadata ZNode
+        // windowStartMs = watermarkMs, windowEndMs = windowStartMs + 
bucketTimeMs
+        long waterMarkMs =
+            getWatermarkMs(preSelectedSegments.first().getStartTimeMs(), 
bucketMs, mergeLevel, mergeRollupTaskMetadata);
+        long windowStartMs = waterMarkMs;
+        long windowEndMs = windowStartMs + bucketMs;
+
+        if (!isValidMergeWindowEndTime(windowEndMs, bufferMs, lowerMergeLevel, 
mergeRollupTaskMetadata)) {
+          LOGGER.info(
+              "Window with start: {} and end: {} of mergeLevel: {} is not a 
valid merge window, Skipping task generation: {}",
+              windowStartMs, windowEndMs, mergeLevel, taskType);
+          continue;
+        }
+
+        // Find all segments overlapping with the merge window, if all 
overlapping segments are merged, bump up the target window
+        List<OfflineSegmentZKMetadata> selectedSegments = new ArrayList<>();
+        boolean hasUnMergedSegments = false;
+        boolean isValidMergeWindow = true;
+
+        // The for loop terminates in following cases:
+        // 1. Found unmerged segments in target merge window, need to bump up 
watermark if windowStartMs > watermarkMs,
+        //    will schedule tasks
+        // 2. All segments are merged in the merge window and we have loop 
through all segments, need to bump up
+        //    watermark to windowStartMs + bucketTimeMs, skip scheduling
+        // 3. Current watermark > endTimeMs of all segments, won't bump up 
watermark, skip scheduling
+        // 4. Merge window is invalid (windowEndMs > 
System.currentTimeMillis() - bufferMs || windowEndMs > waterMark of
+        //    the lower mergeLevel), may need to bump up watermark if 
windowStartMs > watermarkMs, skip scheduling
+        for (OfflineSegmentZKMetadata preSelectedSegment : 
preSelectedSegments) {
+          if (windowStartMs <= preSelectedSegment.getEndTimeMs() && 
preSelectedSegment.getStartTimeMs() < windowEndMs) {
+            // For segments overlapping with current window, add to the result 
list
+            selectedSegments.add(preSelectedSegment);
+            if (!isMergedSegment(preSelectedSegment, mergeLevel)) {
+              hasUnMergedSegments = true;
+            }
+          } else if (windowEndMs <= preSelectedSegment.getStartTimeMs()) {
+            // Has gone through all overlapping segments for current window
+            if (hasUnMergedSegments) {
+              // Found unmerged segments, schedule merge task for current 
window
+              break;
+            } else {
+              // No unmerged segments found, clean up selected segments and 
bump up the merge window
+              // TODO: If there are many small merged segments, we should 
merge them again
+              selectedSegments = new ArrayList<>();
+              selectedSegments.add(preSelectedSegment);
+              if (!isMergedSegment(preSelectedSegment, mergeLevel)) {
+                hasUnMergedSegments = true;
+              }
+              while (windowEndMs <= preSelectedSegment.getStartTimeMs()) {
+                LOGGER.debug("No unmerged segments found for window [{}, {}), 
Update window to: [{}. {})",
+                    windowStartMs, windowEndMs, windowStartMs + bucketMs, 
windowEndMs + bucketMs);
+                windowStartMs += bucketMs;

Review comment:
       Good point, updated.




-- 
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: commits-unsubscr...@pinot.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@pinot.apache.org
For additional commands, e-mail: commits-h...@pinot.apache.org

Reply via email to