jtao15 commented on a change in pull request #7178: URL: https://github.com/apache/pinot/pull/7178#discussion_r682318506
########## 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,450 @@ +/** + * 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.Arrays; +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 java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +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.metadata.segment.SegmentZKMetadata; +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.config.table.ingestion.IngestionConfig; +import org.apache.pinot.spi.utils.TimeUtils; +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) + * - Filter out segments already scheduled by checking zk minion task configs + * - Sort segments based on startTime and endTime in ascending order + * + * For each mergeLevel (from lowest to highest, e.g. Hourly -> Daily -> Monthly -> Yearly): + * - Calculate merge/rollup window: + * - Read watermarkMs from the {@link MergeRollupTaskMetadata} ZNode + * found at MINION_TASK_METADATA/MergeRollupTaskMetadata/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 for higher granularity should be less or equal than the waterMarkMs for lower granularity + * - Bump up target window and watermark if needed. + * - If there's no unmerged segments (by checking egment 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 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) { + String offlineTableName = tableConfig.getTableName(); + + if (tableConfig.getTableType() != TableType.OFFLINE) { + LOGGER.warn("Skip generating task: {} for non-OFFLINE table: {}, REALTIME table is not supported yet", taskType, + offlineTableName); + continue; + } + + IngestionConfig ingestionConfig = tableConfig.getIngestionConfig(); + if (ingestionConfig != null && ingestionConfig.getBatchIngestionConfig() != null && "REFRESH".equalsIgnoreCase( + ingestionConfig.getBatchIngestionConfig().getSegmentIngestionType())) { + LOGGER.warn("Skip generating task: {} for non-APPEND table: {}, REFRESH table is not supported", taskType, + offlineTableName); + continue; + } + + LOGGER.info("Start generating task configs for table: {} for task: {}", offlineTableName, taskType); + + TableTaskConfig tableTaskConfig = tableConfig.getTaskConfig(); + Preconditions.checkState(tableTaskConfig != null); + Map<String, String> taskConfigs = tableTaskConfig.getConfigsForTaskType(taskType); + Preconditions.checkState(taskConfigs != null, "Task config shouldn't be null for table: {}", offlineTableName); + + // Get all segment metadata + Set<OfflineSegmentZKMetadata> allSegmentsForOfflineTable = + new HashSet<>(_clusterInfoAccessor.getOfflineSegmentsMetadata(offlineTableName)); + + // Select current segment snapshot based on lineage + SegmentLineage segmentLineageForTable = _clusterInfoAccessor.getSegmentLineage(offlineTableName); + Set<String> selectedSegmentsBasedOnLineage = SegmentLineageUtils.filterSegmentsBasedOnLineage( + allSegmentsForOfflineTable.stream().map(SegmentZKMetadata::getSegmentName).collect(Collectors.toSet()), + segmentLineageForTable); + + // Filter out segments that are already scheduled + Map<String, List<PinotTaskConfig>> inCompleteMergeLevelToTaskConfig = new HashMap<>(); + Set<String> segmentsScheduled = new HashSet<>(); + for (Map.Entry<String, TaskState> entry : TaskGeneratorUtils.getIncompleteTasks(taskType, offlineTableName, + _clusterInfoAccessor).entrySet()) { + for (PinotTaskConfig taskConfig : _clusterInfoAccessor.getTaskConfigs(entry.getKey())) { + inCompleteMergeLevelToTaskConfig.computeIfAbsent(taskConfig.getConfigs().get(MergeRollupTask.MERGE_LEVEL_KEY), + k -> new ArrayList<>()).add(taskConfig); + segmentsScheduled.addAll(Arrays.asList(taskConfig.getConfigs() + .get(MinionConstants.SEGMENT_NAME_KEY) + .split(MinionConstants.SEGMENT_NAME_SEPARATOR))); + } + } + + // Sort segments based on startTimeMs and endTimeMs in ascending order + TreeSet<OfflineSegmentZKMetadata> preSelectedSegmentsForOfflineTable = allSegmentsForOfflineTable.stream() + .filter(m -> selectedSegmentsBasedOnLineage.contains(m.getSegmentName()) && !segmentsScheduled.contains( + m.getSegmentName())) + .collect(Collectors.toCollection(() -> new TreeSet<>((a, b) -> { + long aStartTime = a.getStartTimeMs(); + long bStartTime = b.getStartTimeMs(); + return aStartTime != bStartTime ? Long.compare(aStartTime, bStartTime) + : Long.compare(a.getEndTimeMs(), b.getEndTimeMs()); + }))); + + if (preSelectedSegmentsForOfflineTable.isEmpty()) { + LOGGER.warn("Skip generating task: {} for table: {}, no segment is found to merge.", taskType, + offlineTableName); + continue; + } + + // Sort merge levels based on bucket time period + Map<String, Map<String, String>> mergeLevelToConfigs = MergeRollupTaskUtils.getLevelToConfigMap(taskConfigs); + List<Map.Entry<String, Map<String, String>>> sortedMergeLevelConfigs = mergeLevelToConfigs.entrySet() + .stream() + .sorted(Comparator.comparingLong( + e -> TimeUtils.convertPeriodToMillis(e.getValue().get(MinionConstants.MergeTask.BUCKET_TIME_PERIOD_KEY)))) + .collect(Collectors.toList()); + + // Schedule tasks from lowest to highest merge level + String lowerMergeLevel = null; + long lowerMergeLevelWatermarkMs = -1; + + for (Map.Entry<String, Map<String, String>> entry : sortedMergeLevelConfigs) { + String mergeLevel = entry.getKey(); + Map<String, String> mergeConfig = entry.getValue(); + + // Get the bucket size and buffer + long bucketMs = + TimeUtils.convertPeriodToMillis(mergeConfig.get(MinionConstants.MergeTask.BUCKET_TIME_PERIOD_KEY)); + long bufferMs = + TimeUtils.convertPeriodToMillis(mergeConfig.get(MinionConstants.MergeTask.BUFFER_TIME_PERIOD_KEY)); + + // Get watermark from MergeRollupTaskMetadata ZNode. + // windowStartMs = watermarkMs, windowEndMs = windowStartMs + bucketTimeMs + long waterMarkMs = + getWatermarkMs(offlineTableName, preSelectedSegmentsForOfflineTable.first().getStartTimeMs(), bucketMs, + mergeLevel); + long windowStartMs = waterMarkMs; + long windowEndMs = windowStartMs + bucketMs; + + // Skip scheduling if there's incomplete task for current mergeLevel + if (inCompleteMergeLevelToTaskConfig.containsKey(mergeLevel)) { + LOGGER.info( + "Found incomplete tasks: {} of merge level: {} for the same table: {}, Skipping task generation: {}", + inCompleteMergeLevelToTaskConfig.get(mergeLevel), mergeLevel, offlineTableName, taskType); + lowerMergeLevel = mergeLevel; + lowerMergeLevelWatermarkMs = waterMarkMs; + continue; + } + + if (!isValidMergeWindowEndTime(windowEndMs, bufferMs, lowerMergeLevel, lowerMergeLevelWatermarkMs)) { + LOGGER.warn( + "Window with start: {} and end: {} of mergeLevel: {} is not a valid merge window, Skipping task generation: {}", + windowStartMs, windowEndMs, mergeLevel, taskType); + lowerMergeLevel = mergeLevel; + lowerMergeLevelWatermarkMs = waterMarkMs; + 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; + + for (OfflineSegmentZKMetadata preSelectedSegment : preSelectedSegmentsForOfflineTable) { + 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 + 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; + windowEndMs += bucketMs; + if (!isValidMergeWindowEndTime(windowEndMs, bufferMs, lowerMergeLevel, lowerMergeLevelWatermarkMs)) { + isValidMergeWindow = false; + break; + } + } + + if (!isValidMergeWindow) { + break; + } + } + } + // windowStartMs > preSelectedSegment.getEndTimeMs() + // Haven't find the first overlapping segment, continue to the next segment + } + + if (windowStartMs != waterMarkMs) { + updateWatermarkMs(offlineTableName, mergeLevel, windowStartMs); + } + lowerMergeLevel = mergeLevel; + lowerMergeLevelWatermarkMs = windowStartMs; + + if (!isValidMergeWindow) { + LOGGER.warn( + "Window with start: {} and end: {} of mergeLevel: {} is not a valid merge window, Skipping task generation: {}", + windowStartMs, windowEndMs, mergeLevel, taskType); + continue; + } + + if (!hasUnMergedSegments && !selectedSegments.isEmpty()) { + // If current merge window overlaps with all the newest pre-selected segments, and these segments are all merged, + // we don't have a chance to bump up the watermark in previous for loop, handle the case here. + LOGGER.debug("No unmerged segments found for window [{}, {}), Update window to: [{}. {})", windowStartMs, + windowEndMs, windowStartMs + bucketMs, windowEndMs + bucketMs); + windowStartMs += bucketMs; + updateWatermarkMs(offlineTableName, mergeLevel, windowStartMs); + } + + if (!hasUnMergedSegments) { + LOGGER.info("No unmerged segments found for mergeLevel:{} for table: {}, Skipping task generation: {}", + mergeLevel, offlineTableName, taskType); + continue; + } + + // Create task configs + SegmentPartitionConfig segmentPartitionConfig = tableConfig.getIndexingConfig().getSegmentPartitionConfig(); + if (segmentPartitionConfig == null) { + pinotTaskConfigs.addAll(createPinotTaskConfigs(selectedSegments, offlineTableName, taskConfigs, mergeConfig)); + } else { + // For partitioned table, schedule separate tasks for each partition + Map<String, ColumnPartitionConfig> columnPartitionMap = segmentPartitionConfig.getColumnPartitionMap(); + Preconditions.checkState(columnPartitionMap.size() == 1, "Cannot partition on multiple columns for table: %s", + tableConfig.getTableName()); + Map.Entry<String, ColumnPartitionConfig> partitionEntry = columnPartitionMap.entrySet().iterator().next(); + String partitionColumn = partitionEntry.getKey(); + + Map<Integer, List<OfflineSegmentZKMetadata>> partitionToSegments = new HashMap<>(); + for (OfflineSegmentZKMetadata selectedSegment : selectedSegments) { + Set<Integer> partitions = selectedSegment.getPartitionMetadata().getPartitions(partitionColumn); + Preconditions.checkState(partitions.size() == 1, + "Cannot schedule MergeRollupTask for segment: %s with %s partitions", selectedSegment.getSegmentName(), + partitions.size()); + int partition = selectedSegment.getPartitionMetadata().getPartitions(partitionColumn).iterator().next(); + partitionToSegments.computeIfAbsent(partition, k -> new ArrayList<>()).add(selectedSegment); + } + + for (Map.Entry<Integer, List<OfflineSegmentZKMetadata>> partitionToSegmentsEntry : partitionToSegments.entrySet()) { + pinotTaskConfigs.addAll( + createPinotTaskConfigs(partitionToSegmentsEntry.getValue(), offlineTableName, taskConfigs, + mergeConfig)); + } + } + + LOGGER.info("Finished generating task configs for table: {} for task: {}", offlineTableName, taskType); + } + } + return pinotTaskConfigs; + } + + /** + * Check if the segment is merged for give merge level + */ + private boolean isMergedSegment(OfflineSegmentZKMetadata segmentZKMetadata, String mergeLevel) { + return segmentZKMetadata.getCustomMap() != null && mergeLevel.equalsIgnoreCase( + segmentZKMetadata.getCustomMap().get(MergeRollupTask.SEGMENT_ZK_METADATA_MERGE_LEVEL_KEY)); + } + + /** + * Check if the merge window end time is valid + */ + private boolean isValidMergeWindowEndTime(long windowEndMs, long bufferMs, String lowerMergeLevel, + long lowerMergeLevelWatermarkMs) { + // Check that execution window endTimeMs <= now - bufferTime + if (windowEndMs > System.currentTimeMillis() - bufferMs) { + return false; + } + // Check that execution window endTimeMs <= waterMark of the lower mergeLevel + return lowerMergeLevel == null || windowEndMs <= lowerMergeLevelWatermarkMs; + } + + /** + * Get the watermark from the MergeRollupMetadata ZNode. + * If the znode is null, computes the watermark using the start time from segment metadata + */ + private long getWatermarkMs(String offlineTableName, long minStartTimeMs, long bucketMs, String mergeLevel) { + MergeRollupTaskMetadata mergeRollupTaskMetadata = + _clusterInfoAccessor.getMinionMergeRollupTaskMetadata(offlineTableName); + long watermarkMs; + if (mergeRollupTaskMetadata == null || mergeRollupTaskMetadata.getWatermarkMap() == null + || mergeRollupTaskMetadata.getWatermarkMap().get(mergeLevel) == null) { + // No ZNode exists. Cold-start. + // Round off according to the bucket. This ensures we align the merged segments to proper time boundaries + // For example, if start time millis is 20200813T12:34:59, we want to create the merged segment for window [20200813, 20200814) + watermarkMs = (minStartTimeMs / bucketMs) * bucketMs; + updateWatermarkMs(offlineTableName, mergeLevel, watermarkMs); + } else { + watermarkMs = mergeRollupTaskMetadata.getWatermarkMap().get(mergeLevel); + } + return watermarkMs; + } + + /** + * Update current watermark for mergeLevel + */ + private void updateWatermarkMs(String offlineTableName, String mergeLevel, long newWatermarkMs) { + MergeRollupTaskMetadata mergeRollupTaskMetadata = + _clusterInfoAccessor.getMinionMergeRollupTaskMetadata(offlineTableName); + Map<String, Long> waterMarkMap; + if (mergeRollupTaskMetadata == null || mergeRollupTaskMetadata.getWatermarkMap() == null) { + waterMarkMap = new TreeMap<>(); + } else { + waterMarkMap = mergeRollupTaskMetadata.getWatermarkMap(); + } + Long prevWatermarkMs = waterMarkMap.put(mergeLevel, newWatermarkMs); + LOGGER.info("Update watermark of mergeLevel: {} for table: {} from: {} to: {}", mergeLevel, offlineTableName, + prevWatermarkMs, newWatermarkMs); + _clusterInfoAccessor.setMergeRollupTaskMetadata(new MergeRollupTaskMetadata(offlineTableName, waterMarkMap)); + } + + /** + * Create pinot task configs for selected segments and pconfigs + */ + private List<PinotTaskConfig> createPinotTaskConfigs(List<OfflineSegmentZKMetadata> selectedSegments, + String offlineTableName, Map<String, String> taskConfigs, Map<String, String> mergeConfig) { + int maxNumRecordsPerTask = mergeConfig.get(MergeRollupTask.MAX_NUM_RECORDS_PER_TASK_KEY) != null ? Integer.parseInt( Review comment: Moved the `maxNumRecordsPerTask` to the callers, and pass it in as a parameter. -- 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