Skip to content

Commit

Permalink
Add sampling factor for DeterminePartitionsJob (apache#13840)
Browse files Browse the repository at this point in the history
There are two type of DeterminePartitionsJob:
-  When the input data is not assume grouped, there may be duplicate rows.
In this case, two MR jobs are launched. The first one do group job to remove duplicate rows.
And a second one to perform global sorting to find lower and upper bound for target segments.
- When the input data is assume grouped, we only need to launch the global sorting
MR job to find lower and upper bound for segments.

Sampling strategy:
- If the input data is assume grouped, sample by random at the mapper side of the global sort mr job.
- If the input data is not assume grouped, sample at the mapper of the group job. Use hash on time
and all dimensions and mod by sampling factor to sample, don't use random method because there
may be duplicate rows.
  • Loading branch information
hqx871 authored Aug 11, 2023
1 parent 353f7be commit a0234c4
Show file tree
Hide file tree
Showing 14 changed files with 258 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,8 @@ public HadoopIndexTask createTask(Interval interval, String version, List<DataSe
tuningConfig.isLogParseExceptions(),
tuningConfig.getMaxParseExceptions(),
tuningConfig.isUseYarnRMJobStatusFallback(),
tuningConfig.getAwaitSegmentAvailabilityTimeoutMillis()
tuningConfig.getAwaitSegmentAvailabilityTimeoutMillis(),
HadoopTuningConfig.DEFAULT_DETERMINE_PARTITIONS_SAMPLING_FACTOR
);

// generate granularity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -332,17 +332,30 @@ public String getErrorMessage()
return failureCause;
}

private static DeterminePartitionsJobSampler createSampler(HadoopDruidIndexerConfig config)
{
HadoopTuningConfig tuningConfig = config.getSchema().getTuningConfig();
final DimensionRangePartitionsSpec partitionsSpec = (DimensionRangePartitionsSpec) config.getPartitionsSpec();
return new DeterminePartitionsJobSampler(
tuningConfig.getDeterminePartitionsSamplingFactor(),
config.getTargetPartitionSize(),
partitionsSpec.getMaxRowsPerSegment()
);
}

public static class DeterminePartitionsGroupByMapper extends HadoopDruidIndexerMapper<BytesWritable, NullWritable>
{
@Nullable
private Granularity rollupGranularity = null;
private DeterminePartitionsJobSampler sampler;

@Override
protected void setup(Context context)
throws IOException, InterruptedException
{
super.setup(context);
rollupGranularity = getConfig().getGranularitySpec().getQueryGranularity();
sampler = createSampler(getConfig());
}

@Override
Expand All @@ -355,10 +368,14 @@ protected void innerMap(
rollupGranularity.bucketStart(inputRow.getTimestamp()).getMillis(),
inputRow
);
context.write(
new BytesWritable(HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsBytes(groupKey)),
NullWritable.get()
);

final byte[] groupKeyBytes = HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsBytes(groupKey);
if (sampler.shouldEmitRow(groupKeyBytes)) {
context.write(
new BytesWritable(groupKeyBytes),
NullWritable.get()
);
}

context.getCounter(HadoopDruidIndexerConfig.IndexJobCounters.ROWS_PROCESSED_COUNTER).increment(1);
}
Expand Down Expand Up @@ -413,6 +430,7 @@ public static class DeterminePartitionsDimSelectionAssumeGroupedMapper
extends HadoopDruidIndexerMapper<BytesWritable, Text>
{
private DeterminePartitionsDimSelectionMapperHelper helper;
private DeterminePartitionsJobSampler sampler;

@Override
protected void setup(Context context)
Expand All @@ -421,6 +439,7 @@ protected void setup(Context context)
super.setup(context);
final HadoopDruidIndexerConfig config = HadoopDruidIndexerConfig.fromConfiguration(context.getConfiguration());
helper = new DeterminePartitionsDimSelectionMapperHelper(config);
sampler = createSampler(getConfig());
}

@Override
Expand All @@ -429,11 +448,13 @@ protected void innerMap(
Context context
) throws IOException, InterruptedException
{
final Map<String, Iterable<String>> dims = new HashMap<>();
for (final String dim : inputRow.getDimensions()) {
dims.put(dim, inputRow.getDimension(dim));
if (sampler.shouldEmitRow()) {
final Map<String, Iterable<String>> dims = new HashMap<>();
for (final String dim : inputRow.getDimensions()) {
dims.put(dim, inputRow.getDimension(dim));
}
helper.emitDimValueCounts(context, DateTimes.utc(inputRow.getTimestampFromEpoch()), dims);
}
helper.emitDimValueCounts(context, DateTimes.utc(inputRow.getTimestampFromEpoch()), dims);
}
}

Expand Down Expand Up @@ -705,6 +726,7 @@ protected void innerReduce(Context context, SortableBytes keyBytes, Iterable<Dim
// We'll store possible partitions in here
final Map<List<String>, DimPartitions> dimPartitionss = new HashMap<>();
final DimensionRangePartitionsSpec partitionsSpec = (DimensionRangePartitionsSpec) config.getPartitionsSpec();
final DeterminePartitionsJobSampler sampler = createSampler(config);

while (iterator.hasNext()) {
final DimValueCount dvc = iterator.next();
Expand All @@ -728,7 +750,7 @@ protected void innerReduce(Context context, SortableBytes keyBytes, Iterable<Dim
}

// See if we need to cut a new partition ending immediately before this dimension value
if (currentDimPartition.rows > 0 && currentDimPartition.rows + dvc.numRows > config.getTargetPartitionSize()) {
if (currentDimPartition.rows > 0 && currentDimPartition.rows + dvc.numRows > sampler.getSampledTargetPartitionSize()) {
final ShardSpec shardSpec = createShardSpec(
partitionsSpec instanceof SingleDimensionPartitionsSpec,
currentDimPartitions.dims,
Expand Down Expand Up @@ -764,7 +786,7 @@ protected void innerReduce(Context context, SortableBytes keyBytes, Iterable<Dim
// One more shard to go
final ShardSpec shardSpec;

if (currentDimPartition.rows < config.getTargetPartitionSize() * SHARD_COMBINE_THRESHOLD &&
if (currentDimPartition.rows < sampler.getSampledTargetPartitionSize() * SHARD_COMBINE_THRESHOLD &&
!currentDimPartitions.partitions.isEmpty()) {
// Combine with previous shard if it exists and the current shard is small enough
final DimPartition previousDimPartition = currentDimPartitions.partitions.remove(
Expand Down Expand Up @@ -850,7 +872,7 @@ protected void innerReduce(Context context, SortableBytes keyBytes, Iterable<Dim
// Make sure none of these shards are oversized
boolean oversized = false;
for (final DimPartition partition : dimPartitions.partitions) {
if (partition.rows > partitionsSpec.getMaxRowsPerSegment()) {
if (partition.rows > sampler.getSampledMaxRowsPerSegment()) {
log.info("Dimension[%s] has an oversized shard: %s", dimPartitions.dims, partition.shardSpec);
oversized = true;
}
Expand All @@ -861,7 +883,7 @@ protected void innerReduce(Context context, SortableBytes keyBytes, Iterable<Dim
}

final int cardinality = dimPartitions.getCardinality();
final long distance = dimPartitions.getDistanceSquaredFromTarget(config.getTargetPartitionSize());
final long distance = dimPartitions.getDistanceSquaredFromTarget(sampler.getSampledTargetPartitionSize());

if (cardinality > maxCardinality) {
maxCardinality = cardinality;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* 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.druid.indexer;

import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

import java.util.concurrent.ThreadLocalRandom;

public class DeterminePartitionsJobSampler
{
private static final HashFunction HASH_FUNCTION = Hashing.murmur3_32();

private final int samplingFactor;

private final int sampledTargetPartitionSize;

private final int sampledMaxRowsPerSegment;

public DeterminePartitionsJobSampler(int samplingFactor, int targetPartitionSize, int maxRowsPerSegment)
{
this.samplingFactor = Math.max(samplingFactor, 1);
this.sampledTargetPartitionSize = targetPartitionSize / this.samplingFactor;
this.sampledMaxRowsPerSegment = maxRowsPerSegment / this.samplingFactor;
}

/**
* If input rows is duplicate, we can use hash and mod to do sample. As we hash on whole group key,
* there will not likely data skew if the hash function is balanced enough.
*/
boolean shouldEmitRow(byte[] groupKeyBytes)
{
return samplingFactor == 1 || HASH_FUNCTION.hashBytes(groupKeyBytes).asInt() % samplingFactor == 0;
}

/**
* If input rows is not duplicate, we can sample at random.
*/
boolean shouldEmitRow()
{
return samplingFactor == 1 || ThreadLocalRandom.current().nextInt(samplingFactor) == 0;
}

public int getSampledTargetPartitionSize()
{
return sampledTargetPartitionSize;
}

public int getSampledMaxRowsPerSegment()
{
return sampledMaxRowsPerSegment;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
@JsonTypeName("hadoop")
public class HadoopTuningConfig implements TuningConfig
{
public static final int DEFAULT_DETERMINE_PARTITIONS_SAMPLING_FACTOR = 1;

private static final DimensionBasedPartitionsSpec DEFAULT_PARTITIONS_SPEC = HashedPartitionsSpec.defaultSpec();
private static final Map<Long, List<HadoopyShardSpec>> DEFAULT_SHARD_SPECS = ImmutableMap.of();
private static final IndexSpec DEFAULT_INDEX_SPEC = IndexSpec.DEFAULT;
Expand Down Expand Up @@ -74,7 +76,8 @@ public static HadoopTuningConfig makeDefaultTuningConfig()
null,
null,
null,
null
null,
DEFAULT_DETERMINE_PARTITIONS_SAMPLING_FACTOR
);
}
@Nullable
Expand Down Expand Up @@ -102,6 +105,15 @@ public static HadoopTuningConfig makeDefaultTuningConfig()
private final int maxParseExceptions;
private final boolean useYarnRMJobStatusFallback;
private final long awaitSegmentAvailabilityTimeoutMillis;
// The sample parameter is only used for range partition spec now. When using range
// partition spec, we need launch many mapper and one reducer to do global sorting and
// find the upper and lower bound for every segment. This mr job may cost a lot of time
// if the input data is large. So we can sample the input data and make the mr job run
// faster. After all, we don't need a segment size which exactly equals targetRowsPerSegment.
// For example, if we ingest 10,000,000,000 rows and the targetRowsPerSegment is 5,000,000,
// we can sample by 500, so the mr job need only process 20,000,000 rows, this helps save
// a lot of time.
private final int determinePartitionsSamplingFactor;

@JsonCreator
public HadoopTuningConfig(
Expand Down Expand Up @@ -130,7 +142,8 @@ public HadoopTuningConfig(
final @JsonProperty("logParseExceptions") @Nullable Boolean logParseExceptions,
final @JsonProperty("maxParseExceptions") @Nullable Integer maxParseExceptions,
final @JsonProperty("useYarnRMJobStatusFallback") @Nullable Boolean useYarnRMJobStatusFallback,
final @JsonProperty("awaitSegmentAvailabilityTimeoutMillis") @Nullable Long awaitSegmentAvailabilityTimeoutMillis
final @JsonProperty("awaitSegmentAvailabilityTimeoutMillis") @Nullable Long awaitSegmentAvailabilityTimeoutMillis,
final @JsonProperty("determinePartitionsSamplingFactor") @Nullable Integer determinePartitionsSamplingFactor
)
{
this.workingPath = workingPath;
Expand Down Expand Up @@ -182,6 +195,11 @@ public HadoopTuningConfig(
} else {
this.awaitSegmentAvailabilityTimeoutMillis = awaitSegmentAvailabilityTimeoutMillis;
}
if (determinePartitionsSamplingFactor == null || determinePartitionsSamplingFactor < 1) {
this.determinePartitionsSamplingFactor = 1;
} else {
this.determinePartitionsSamplingFactor = determinePartitionsSamplingFactor;
}
}

@Nullable
Expand Down Expand Up @@ -336,6 +354,12 @@ public long getAwaitSegmentAvailabilityTimeoutMillis()
return awaitSegmentAvailabilityTimeoutMillis;
}

@JsonProperty
public int getDeterminePartitionsSamplingFactor()
{
return determinePartitionsSamplingFactor;
}

public HadoopTuningConfig withWorkingPath(String path)
{
return new HadoopTuningConfig(
Expand Down Expand Up @@ -363,7 +387,8 @@ public HadoopTuningConfig withWorkingPath(String path)
logParseExceptions,
maxParseExceptions,
useYarnRMJobStatusFallback,
awaitSegmentAvailabilityTimeoutMillis
awaitSegmentAvailabilityTimeoutMillis,
determinePartitionsSamplingFactor
);
}

Expand Down Expand Up @@ -394,7 +419,8 @@ public HadoopTuningConfig withVersion(String ver)
logParseExceptions,
maxParseExceptions,
useYarnRMJobStatusFallback,
awaitSegmentAvailabilityTimeoutMillis
awaitSegmentAvailabilityTimeoutMillis,
determinePartitionsSamplingFactor
);
}

Expand Down Expand Up @@ -425,7 +451,8 @@ public HadoopTuningConfig withShardSpecs(Map<Long, List<HadoopyShardSpec>> specs
logParseExceptions,
maxParseExceptions,
useYarnRMJobStatusFallback,
awaitSegmentAvailabilityTimeoutMillis
awaitSegmentAvailabilityTimeoutMillis,
determinePartitionsSamplingFactor
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,8 @@ private HadoopDruidIndexerConfig makeHadoopDruidIndexerConfig(
null,
null,
null,
null
null,
1
)
)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,8 @@ public DetermineHashedPartitionsJobTest(
null,
null,
null,
null
null,
1
)
);
this.indexerConfig = new HadoopDruidIndexerConfig(ingestionSpec);
Expand Down
Loading

0 comments on commit a0234c4

Please sign in to comment.