drcrallen commented on a change in pull request #5492: Native parallel batch 
indexing without shuffle
URL: https://github.com/apache/incubator-druid/pull/5492#discussion_r201771117
 
 

 ##########
 File path: 
indexing-service/src/main/java/io/druid/indexing/common/task/ParallelIndexSubTask.java
 ##########
 @@ -0,0 +1,451 @@
+/*
+ * Licensed to Metamarkets Group Inc. (Metamarkets) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. Metamarkets 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 io.druid.indexing.common.task;
+
+import com.fasterxml.jackson.annotation.JacksonInject;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import io.druid.client.indexing.IndexingServiceClient;
+import io.druid.data.input.Firehose;
+import io.druid.data.input.FirehoseFactory;
+import io.druid.data.input.InputRow;
+import io.druid.indexer.TaskStatus;
+import io.druid.indexing.appenderator.ActionBasedSegmentAllocator;
+import io.druid.indexing.appenderator.ActionBasedUsedSegmentChecker;
+import io.druid.indexing.appenderator.CountingActionBasedSegmentAllocator;
+import io.druid.indexing.common.TaskLock;
+import io.druid.indexing.common.TaskLockType;
+import io.druid.indexing.common.TaskToolbox;
+import io.druid.indexing.common.actions.LockListAction;
+import io.druid.indexing.common.actions.LockTryAcquireAction;
+import io.druid.indexing.common.actions.SegmentAllocateAction;
+import io.druid.indexing.common.actions.SurrogateAction;
+import io.druid.indexing.common.actions.TaskActionClient;
+import io.druid.indexing.common.task.IndexTask.IndexIOConfig;
+import io.druid.indexing.firehose.IngestSegmentFirehoseFactory;
+import io.druid.java.util.common.ISE;
+import io.druid.java.util.common.Intervals;
+import io.druid.java.util.common.StringUtils;
+import io.druid.java.util.common.logger.Logger;
+import io.druid.java.util.common.parsers.ParseException;
+import io.druid.query.DruidMetrics;
+import io.druid.segment.indexing.DataSchema;
+import io.druid.segment.indexing.RealtimeIOConfig;
+import io.druid.segment.indexing.granularity.GranularitySpec;
+import io.druid.segment.realtime.FireDepartment;
+import io.druid.segment.realtime.FireDepartmentMetrics;
+import io.druid.segment.realtime.RealtimeMetricsMonitor;
+import io.druid.segment.realtime.appenderator.Appenderator;
+import io.druid.segment.realtime.appenderator.AppenderatorDriverAddResult;
+import io.druid.segment.realtime.appenderator.Appenderators;
+import io.druid.segment.realtime.appenderator.BaseAppenderatorDriver;
+import io.druid.segment.realtime.appenderator.BatchAppenderatorDriver;
+import io.druid.segment.realtime.appenderator.SegmentAllocator;
+import io.druid.segment.realtime.appenderator.SegmentsAndMetadata;
+import io.druid.timeline.DataSegment;
+import org.codehaus.plexus.util.FileUtils;
+import org.joda.time.Interval;
+
+import javax.annotation.Nullable;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.SortedSet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+
+/**
+ * A worker task of {@link ParallelIndexSupervisorTask}. Similar to {@link 
IndexTask}, but this task
+ * generates and pushes segments, and reports them to the {@link 
ParallelIndexSupervisorTask} instead of
+ * publishing on its own.
+ */
+public class ParallelIndexSubTask extends AbstractTask
+{
+  static final String TYPE = "index_sub";
+
+  private static final Logger log = new Logger(ParallelIndexSubTask.class);
+
+  private final int numAttempts;
+  private final ParallelIndexIngestionSpec ingestionSchema;
+  private final String supervisorTaskId;
+  private final IndexingServiceClient indexingServiceClient;
+  private final IndexTaskClientFactory<ParallelIndexTaskClient> 
taskClientFactory;
+
+  @JsonCreator
+  public ParallelIndexSubTask(
+      // id shouldn't be null except when this task is created by 
ParallelIndexSupervisorTask
+      @JsonProperty("id") @Nullable final String id,
+      @JsonProperty("groupId") final String groupId,
+      @JsonProperty("resource") final TaskResource taskResource,
+      @JsonProperty("supervisorTaskId") final String supervisorTaskId,
+      @JsonProperty("numAttempts") final int numAttempts, // zero-based 
counting
+      @JsonProperty("spec") final ParallelIndexIngestionSpec ingestionSchema,
+      @JsonProperty("context") final Map<String, Object> context,
+      @JacksonInject IndexingServiceClient indexingServiceClient,
+      @JacksonInject IndexTaskClientFactory<ParallelIndexTaskClient> 
taskClientFactory
+  )
+  {
+    super(
+        getOrMakeId(id, TYPE, ingestionSchema.getDataSchema().getDataSource()),
+        groupId,
+        taskResource,
+        ingestionSchema.getDataSchema().getDataSource(),
+        context
+    );
+
+    if (ingestionSchema.getTuningConfig().isForceGuaranteedRollup()) {
+      throw new UnsupportedOperationException("Guaranteed rollup is not 
supported");
+    }
+
+    this.numAttempts = numAttempts;
+    this.ingestionSchema = ingestionSchema;
+    this.supervisorTaskId = supervisorTaskId;
+    this.indexingServiceClient = indexingServiceClient;
+    this.taskClientFactory = taskClientFactory;
+  }
+
+  @Override
+  public int getPriority()
+  {
+    return getContextValue(Tasks.PRIORITY_KEY, 
Tasks.DEFAULT_BATCH_INDEX_TASK_PRIORITY);
+  }
+
+  @Override
+  public String getType()
+  {
+    return TYPE;
+  }
+
+  @Override
+  public boolean isReady(TaskActionClient taskActionClient)
+  {
+    final Optional<SortedSet<Interval>> intervals = 
ingestionSchema.getDataSchema()
+                                                                   
.getGranularitySpec()
+                                                                   
.bucketIntervals();
+
+    return !intervals.isPresent() || checkLockAcquired(taskActionClient, 
intervals.get());
+  }
+
+  private boolean checkLockAcquired(TaskActionClient actionClient, 
SortedSet<Interval> intervals)
+  {
+    try {
+      tryAcquireExclusiveSurrogateLocks(actionClient, intervals);
+      return true;
+    }
+    catch (Exception e) {
+      log.error(e, "Failed to acquire locks for intervals[%s]", intervals);
+      return false;
+    }
+  }
+
+  @JsonProperty
+  public int getNumAttempts()
+  {
+    return numAttempts;
+  }
+
+  @JsonProperty("spec")
+  public ParallelIndexIngestionSpec getIngestionSchema()
+  {
+    return ingestionSchema;
+  }
+
+  @JsonProperty
+  public String getSupervisorTaskId()
+  {
+    return supervisorTaskId;
+  }
+
+  @Override
+  public TaskStatus run(final TaskToolbox toolbox) throws Exception
+  {
+    final boolean explicitIntervals = ingestionSchema.getDataSchema()
+                                                     .getGranularitySpec()
+                                                     .bucketIntervals()
+                                                     .isPresent();
+
+    final FirehoseFactory firehoseFactory = 
ingestionSchema.getIOConfig().getFirehoseFactory();
+
+    if (firehoseFactory instanceof IngestSegmentFirehoseFactory) {
+      // pass toolbox to Firehose
+      ((IngestSegmentFirehoseFactory) firehoseFactory).setTaskToolbox(toolbox);
+    }
+
+    final File firehoseTempDir = toolbox.getFirehoseTemporaryDir();
+    // Firehose temporary directory is automatically removed when this 
IndexTask completes.
+    FileUtils.forceMkdir(firehoseTempDir);
+
+    final DataSchema dataSchema = ingestionSchema.getDataSchema();
+    final Map<Interval, String> versions;
+
+    if (explicitIntervals) {
+      versions = toolbox.getTaskActionClient().submit(new 
SurrogateAction<>(supervisorTaskId, new LockListAction()))
+                        .stream()
+                        .collect(Collectors.toMap(TaskLock::getInterval, 
TaskLock::getVersion));
+    } else {
+      versions = null;
+    }
+
+    final List<DataSegment> pushedSegments = generateAndPushSegments(
+        toolbox,
+        dataSchema,
+        versions,
+        firehoseFactory,
+        firehoseTempDir
+    );
+    final ParallelIndexTaskClient taskClient = taskClientFactory.build(
+        new ClientBasedTaskInfoProvider(indexingServiceClient),
+        getId(),
+        1, // always use a single http thread
+        ingestionSchema.getTuningConfig().getChatHandlerTimeout(),
+        ingestionSchema.getTuningConfig().getChatHandlerNumRetries()
+    );
+    taskClient.report(supervisorTaskId, pushedSegments);
+
+    return TaskStatus.success(getId());
+  }
+
+  private Map<Interval, TaskLock> tryAcquireExclusiveSurrogateLocks(
+      TaskActionClient client,
+      SortedSet<Interval> intervals
+  )
+      throws IOException
+  {
+    final Map<Interval, TaskLock> lockMap = new HashMap<>();
+    for (Interval interval : Tasks.computeCompactIntervals(intervals)) {
+      final TaskLock lock = Preconditions.checkNotNull(
+          client.submit(
+              new SurrogateAction<>(supervisorTaskId, new 
LockTryAcquireAction(TaskLockType.EXCLUSIVE, interval))
+          ),
+          "Cannot acquire a lock for interval[%s]", interval
+      );
+      lockMap.put(interval, lock);
+    }
+    return lockMap;
+  }
+
+  /**
+   * This method reads input data row by row and adds the read row to a proper 
segment using {@link BaseAppenderatorDriver}.
+   * If there is no segment for the row, a new one is created.  Segments can 
be published in the middle of reading inputs
+   * if one of below conditions are satisfied.
+   *
+   * <ul>
+   * <li>
+   * If the number of rows in a segment exceeds {@link 
ParallelIndexTuningConfig#targetPartitionSize}
+   * </li>
+   * <li>
+   * If the number of rows added to {@link BaseAppenderatorDriver} so far 
exceeds {@link ParallelIndexTuningConfig#maxTotalRows}
+   * </li>
+   * </ul>
+   *
+   * At the end of this method, all the remaining segments are published.
+   *
+   * @return true if generated segments are successfully published, otherwise 
false
+   */
+  private List<DataSegment> generateAndPushSegments(
+      final TaskToolbox toolbox,
+      final DataSchema dataSchema,
+      @Nullable final Map<Interval, String> versions,
+      final FirehoseFactory firehoseFactory,
+      final File firehoseTempDir
+  ) throws IOException, InterruptedException
+  {
+    final GranularitySpec granularitySpec = dataSchema.getGranularitySpec();
+    final FireDepartment fireDepartmentForMetrics = new FireDepartment(
+        dataSchema, new RealtimeIOConfig(null, null, null), null
+    );
+    final FireDepartmentMetrics fireDepartmentMetrics = 
fireDepartmentForMetrics.getMetrics();
+
+    if (toolbox.getMonitorScheduler() != null) {
+      toolbox.getMonitorScheduler().addMonitor(
+          new RealtimeMetricsMonitor(
+              ImmutableList.of(fireDepartmentForMetrics),
 
 Review comment:
   `Collections.singletonList`

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

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

Reply via email to