snleee commented on a change in pull request #6661:
URL: https://github.com/apache/incubator-pinot/pull/6661#discussion_r639475680



##########
File path: 
pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java
##########
@@ -0,0 +1,199 @@
+/**
+ * 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.stream.kinesis;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.apache.pinot.spi.stream.PartitionGroupConsumer;
+import org.apache.pinot.spi.stream.StreamPartitionMsgOffset;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.services.kinesis.KinesisClient;
+import software.amazon.awssdk.services.kinesis.model.ExpiredIteratorException;
+import software.amazon.awssdk.services.kinesis.model.GetRecordsRequest;
+import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse;
+import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest;
+import software.amazon.awssdk.services.kinesis.model.InvalidArgumentException;
+import software.amazon.awssdk.services.kinesis.model.KinesisException;
+import 
software.amazon.awssdk.services.kinesis.model.ProvisionedThroughputExceededException;
+import software.amazon.awssdk.services.kinesis.model.Record;
+import software.amazon.awssdk.services.kinesis.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.kinesis.model.ShardIteratorType;
+
+
+/**
+ * A {@link PartitionGroupConsumer} implementation for the Kinesis stream
+ */
+public class KinesisConsumer extends KinesisConnectionHandler implements 
PartitionGroupConsumer {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(KinesisConsumer.class);
+  private final String _streamTopicName;
+  private final int _numMaxRecordsToFetch;
+  private final ExecutorService _executorService;
+  private final ShardIteratorType _shardIteratorType;
+
+  public KinesisConsumer(KinesisConfig kinesisConfig) {
+    super(kinesisConfig);
+    _streamTopicName = kinesisConfig.getStreamTopicName();
+    _numMaxRecordsToFetch = kinesisConfig.getNumMaxRecordsToFetch();
+    _shardIteratorType = kinesisConfig.getShardIteratorType();
+    _executorService = Executors.newSingleThreadExecutor();
+  }
+
+  @VisibleForTesting
+  public KinesisConsumer(KinesisConfig kinesisConfig, KinesisClient 
kinesisClient) {
+    super(kinesisConfig, kinesisClient);
+    _kinesisClient = kinesisClient;
+    _streamTopicName = kinesisConfig.getStreamTopicName();
+    _numMaxRecordsToFetch = kinesisConfig.getNumMaxRecordsToFetch();
+    _shardIteratorType = kinesisConfig.getShardIteratorType();
+    _executorService = Executors.newSingleThreadExecutor();
+  }
+
+  /**
+   * Fetch records from the Kinesis stream between the start and end 
KinesisCheckpoint
+   */
+  @Override
+  public KinesisRecordsBatch fetchMessages(StreamPartitionMsgOffset 
startCheckpoint,
+      StreamPartitionMsgOffset endCheckpoint, int timeoutMs) {
+    List<Record> recordList = new ArrayList<>();
+    Future<KinesisRecordsBatch> kinesisFetchResultFuture =
+        _executorService.submit(() -> getResult(startCheckpoint, 
endCheckpoint, recordList));
+
+    try {
+      return kinesisFetchResultFuture.get(timeoutMs, TimeUnit.MILLISECONDS);
+    } catch (Exception e) {
+      return handleException((KinesisPartitionGroupOffset) startCheckpoint, 
recordList);
+    }
+  }
+
+  private KinesisRecordsBatch getResult(StreamPartitionMsgOffset start, 
StreamPartitionMsgOffset end,
+      List<Record> recordList) {
+    KinesisPartitionGroupOffset kinesisStartCheckpoint = 
(KinesisPartitionGroupOffset) start;
+
+    try {
+
+      if (_kinesisClient == null) {
+        createConnection();
+      }
+
+      // TODO: iterate upon all the shardIds in the map
+      //  Okay for now, since we have assumed that every partition group 
contains a single shard
+      Map<String, String> shardToStartSequenceMap = 
kinesisStartCheckpoint.getShardToStartSequenceMap();
+      Preconditions.checkState(shardToStartSequenceMap.size() == 1, "Only 1 
shard per consumer supported. Found: %s",
+          shardToStartSequenceMap.keySet());
+      Map.Entry<String, String> shardToSequenceNum = 
shardToStartSequenceMap.entrySet().iterator().next();
+      String shardIterator = getShardIterator(shardToSequenceNum.getKey(), 
shardToSequenceNum.getValue());
+
+      String kinesisEndSequenceNumber = null;
+
+      if (end != null) {
+        KinesisPartitionGroupOffset kinesisEndCheckpoint = 
(KinesisPartitionGroupOffset) end;
+        kinesisEndSequenceNumber = 
kinesisEndCheckpoint.getShardToStartSequenceMap().values().iterator().next();

Review comment:
       Should we add the similar validation as `kinesisStartCheckpoint` 
(checking the map size = 1)

##########
File path: 
pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisStreamMetadataProvider.java
##########
@@ -0,0 +1,189 @@
+/**
+ * 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.stream.kinesis;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+import javax.annotation.Nonnull;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pinot.spi.stream.MessageBatch;
+import org.apache.pinot.spi.stream.OffsetCriteria;
+import org.apache.pinot.spi.stream.PartitionGroupConsumer;
+import org.apache.pinot.spi.stream.PartitionGroupConsumptionStatus;
+import org.apache.pinot.spi.stream.PartitionGroupMetadata;
+import org.apache.pinot.spi.stream.StreamConfig;
+import org.apache.pinot.spi.stream.StreamConsumerFactory;
+import org.apache.pinot.spi.stream.StreamConsumerFactoryProvider;
+import org.apache.pinot.spi.stream.StreamMetadataProvider;
+import org.apache.pinot.spi.stream.StreamPartitionMsgOffset;
+import software.amazon.awssdk.services.kinesis.model.Shard;
+
+
+/**
+ * A {@link StreamMetadataProvider} implementation for the Kinesis stream
+ */
+public class KinesisStreamMetadataProvider implements StreamMetadataProvider {
+  private static final String SHARD_ID_PREFIX = "shardId-";
+  private final KinesisConnectionHandler _kinesisConnectionHandler;
+  private final StreamConsumerFactory _kinesisStreamConsumerFactory;
+  private final String _clientId;
+  private final int _fetchTimeoutMs;
+
+  public KinesisStreamMetadataProvider(String clientId, StreamConfig 
streamConfig) {
+    KinesisConfig kinesisConfig = new KinesisConfig(streamConfig);
+    _kinesisConnectionHandler = new KinesisConnectionHandler(kinesisConfig);
+    _kinesisStreamConsumerFactory = 
StreamConsumerFactoryProvider.create(streamConfig);
+    _clientId = clientId;
+    _fetchTimeoutMs = streamConfig.getFetchTimeoutMillis();
+  }
+
+  public KinesisStreamMetadataProvider(String clientId, StreamConfig 
streamConfig,
+      KinesisConnectionHandler kinesisConnectionHandler, StreamConsumerFactory 
streamConsumerFactory) {
+    _kinesisConnectionHandler = kinesisConnectionHandler;
+    _kinesisStreamConsumerFactory = streamConsumerFactory;
+    _clientId = clientId;
+    _fetchTimeoutMs = streamConfig.getFetchTimeoutMillis();
+  }
+
+  @Override
+  public int fetchPartitionCount(long timeoutMillis) {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public long fetchPartitionOffset(@Nonnull OffsetCriteria offsetCriteria, 
long timeoutMillis) {
+    throw new UnsupportedOperationException();
+  }
+
+  /**
+   * This call returns all active shards, taking into account the consumption 
status for those shards.
+   * {@link PartitionGroupMetadata} is returned for a shard if:
+   * 1. It is a branch new shard AND its parent has been consumed completely
+   * 2. It is still being actively consumed from i.e. the consuming partition 
has not reached the end of the shard
+   */
+  @Override
+  public List<PartitionGroupMetadata> computePartitionGroupMetadata(String 
clientId, StreamConfig streamConfig,
+      List<PartitionGroupConsumptionStatus> partitionGroupConsumptionStatuses, 
int timeoutMillis)
+      throws IOException, TimeoutException {
+
+    List<PartitionGroupMetadata> newPartitionGroupMetadataList = new 
ArrayList<>();
+
+    Map<String, Shard> shardIdToShardMap = 
_kinesisConnectionHandler.getShards().stream()
+        .collect(Collectors.toMap(Shard::shardId, s -> s, (s1, s2) -> s1));
+    Set<String> shardsInCurrent = new HashSet<>();
+    Set<String> shardsEnded = new HashSet<>();
+
+    // TODO: Once we start supporting multiple shards in a PartitionGroup,
+    //  we need to iterate over all shards to check if any of them have 
reached end
+
+    // Process existing shards. Add them to new list if still consuming from 
them
+    for (PartitionGroupConsumptionStatus 
currentPartitionGroupConsumptionStatus : partitionGroupConsumptionStatuses) {
+      KinesisPartitionGroupOffset kinesisStartCheckpoint =
+          (KinesisPartitionGroupOffset) 
currentPartitionGroupConsumptionStatus.getStartOffset();
+      String shardId = 
kinesisStartCheckpoint.getShardToStartSequenceMap().keySet().iterator().next();
+      shardsInCurrent.add(shardId);
+      Shard shard = shardIdToShardMap.get(shardId);
+      if (shard == null) { // Shard has expired
+        shardsEnded.add(shardId);
+        continue;
+        // FIXME: Here we assume that we were done consuming the shard before 
it expired.
+        //  Handle edge case where consumer lags behind, resulting in shard to 
expire before it is all consumed
+      }
+
+      StreamPartitionMsgOffset newStartOffset;
+      StreamPartitionMsgOffset currentEndOffset = 
currentPartitionGroupConsumptionStatus.getEndOffset();
+      if (currentEndOffset != null) { // Segment DONE (committing/committed)
+        String endingSequenceNumber = 
shard.sequenceNumberRange().endingSequenceNumber();
+        if (endingSequenceNumber != null) { // Shard has ended, check if we're 
also done consuming it
+          if (consumedEndOfShard(currentEndOffset, 
currentPartitionGroupConsumptionStatus)) {
+            shardsEnded.add(shardId);
+            continue; // Shard ended and we're done consuming it. Skip
+          }
+        }
+        newStartOffset = currentEndOffset;
+      } else { // Segment IN_PROGRESS
+        newStartOffset = 
currentPartitionGroupConsumptionStatus.getStartOffset();
+      }
+      newPartitionGroupMetadataList.add(
+          new 
PartitionGroupMetadata(currentPartitionGroupConsumptionStatus.getPartitionGroupId(),
 newStartOffset));
+    }
+
+    // Add brand new shards
+    for (Map.Entry<String, Shard> entry : shardIdToShardMap.entrySet()) {
+      // If shard was already in current list, skip
+      String newShardId = entry.getKey();
+      if (shardsInCurrent.contains(newShardId)) {
+        continue;
+      }
+      StreamPartitionMsgOffset newStartOffset;
+      Shard newShard = entry.getValue();
+      String parentShardId = newShard.parentShardId();
+
+      // Add the new shard in the following 3 cases:
+      // 1. Root shards - Parent shardId will be null. Will find this case 
when creating new table.
+      // 2. Parent expired - Parent shardId will not be part of shardIdToShard 
map
+      // 3. Parent reached EOL and completely consumed.
+      if (parentShardId == null || 
!shardIdToShardMap.containsKey(parentShardId) || 
shardsEnded.contains(parentShardId)) {
+        Map<String, String> shardToSequenceNumberMap = new HashMap<>();
+        shardToSequenceNumberMap.put(newShardId, 
newShard.sequenceNumberRange().startingSequenceNumber());
+        newStartOffset = new 
KinesisPartitionGroupOffset(shardToSequenceNumberMap);
+        int partitionGroupId = getPartitionGroupIdFromShardId(newShardId);
+        newPartitionGroupMetadataList.add(new 
PartitionGroupMetadata(partitionGroupId, newStartOffset));
+      }
+    }
+    return newPartitionGroupMetadataList;
+  }
+
+  /**
+   * Converts a shardId string to a partitionGroupId integer by parsing the 
digits of the shardId
+   * e.g. "shardId-000000000001" becomes 1
+   * FIXME: Although practically the shard values follow this format, the 
Kinesis docs don't guarantee it.
+   *  Re-evaluate if this convention needs to be changed.
+   */
+  private int getPartitionGroupIdFromShardId(String shardId) {
+    String shardIdNum = 
StringUtils.stripStart(StringUtils.removeStart(shardId, SHARD_ID_PREFIX), "0");
+    return shardIdNum.isEmpty() ? 0 : Integer.parseInt(shardIdNum);
+  }
+
+  private boolean consumedEndOfShard(StreamPartitionMsgOffset startCheckpoint, 
PartitionGroupConsumptionStatus partitionGroupConsumptionStatus)

Review comment:
       Can you apply the formatting for this class? I believe that this line 
probably runs over the line charact limit.

##########
File path: 
pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java
##########
@@ -0,0 +1,199 @@
+/**
+ * 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.stream.kinesis;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.apache.pinot.spi.stream.PartitionGroupConsumer;
+import org.apache.pinot.spi.stream.StreamPartitionMsgOffset;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.services.kinesis.KinesisClient;
+import software.amazon.awssdk.services.kinesis.model.ExpiredIteratorException;
+import software.amazon.awssdk.services.kinesis.model.GetRecordsRequest;
+import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse;
+import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest;
+import software.amazon.awssdk.services.kinesis.model.InvalidArgumentException;
+import software.amazon.awssdk.services.kinesis.model.KinesisException;
+import 
software.amazon.awssdk.services.kinesis.model.ProvisionedThroughputExceededException;
+import software.amazon.awssdk.services.kinesis.model.Record;
+import software.amazon.awssdk.services.kinesis.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.kinesis.model.ShardIteratorType;
+
+
+/**
+ * A {@link PartitionGroupConsumer} implementation for the Kinesis stream
+ */
+public class KinesisConsumer extends KinesisConnectionHandler implements 
PartitionGroupConsumer {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(KinesisConsumer.class);
+  private final String _streamTopicName;
+  private final int _numMaxRecordsToFetch;
+  private final ExecutorService _executorService;
+  private final ShardIteratorType _shardIteratorType;
+
+  public KinesisConsumer(KinesisConfig kinesisConfig) {
+    super(kinesisConfig);
+    _streamTopicName = kinesisConfig.getStreamTopicName();
+    _numMaxRecordsToFetch = kinesisConfig.getNumMaxRecordsToFetch();
+    _shardIteratorType = kinesisConfig.getShardIteratorType();
+    _executorService = Executors.newSingleThreadExecutor();
+  }
+
+  @VisibleForTesting
+  public KinesisConsumer(KinesisConfig kinesisConfig, KinesisClient 
kinesisClient) {
+    super(kinesisConfig, kinesisClient);
+    _kinesisClient = kinesisClient;
+    _streamTopicName = kinesisConfig.getStreamTopicName();
+    _numMaxRecordsToFetch = kinesisConfig.getNumMaxRecordsToFetch();
+    _shardIteratorType = kinesisConfig.getShardIteratorType();
+    _executorService = Executors.newSingleThreadExecutor();
+  }
+
+  /**
+   * Fetch records from the Kinesis stream between the start and end 
KinesisCheckpoint
+   */
+  @Override
+  public KinesisRecordsBatch fetchMessages(StreamPartitionMsgOffset 
startCheckpoint,
+      StreamPartitionMsgOffset endCheckpoint, int timeoutMs) {
+    List<Record> recordList = new ArrayList<>();
+    Future<KinesisRecordsBatch> kinesisFetchResultFuture =
+        _executorService.submit(() -> getResult(startCheckpoint, 
endCheckpoint, recordList));
+
+    try {
+      return kinesisFetchResultFuture.get(timeoutMs, TimeUnit.MILLISECONDS);
+    } catch (Exception e) {
+      return handleException((KinesisPartitionGroupOffset) startCheckpoint, 
recordList);
+    }
+  }
+
+  private KinesisRecordsBatch getResult(StreamPartitionMsgOffset start, 
StreamPartitionMsgOffset end,
+      List<Record> recordList) {
+    KinesisPartitionGroupOffset kinesisStartCheckpoint = 
(KinesisPartitionGroupOffset) start;
+
+    try {
+

Review comment:
       remove line




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

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