snleee commented on a change in pull request #6661: URL: https://github.com/apache/incubator-pinot/pull/6661#discussion_r612080251
########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConnectionHandler.java ########## @@ -0,0 +1,76 @@ +/** + * 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.util.List; +import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kinesis.KinesisClient; +import software.amazon.awssdk.services.kinesis.model.ListShardsRequest; +import software.amazon.awssdk.services.kinesis.model.ListShardsResponse; +import software.amazon.awssdk.services.kinesis.model.Shard; + + +/** + * Manages the Kinesis stream connection, given the stream name and aws region + */ +public class KinesisConnectionHandler { + protected KinesisClient _kinesisClient; + private final String _stream; + private final String _awsRegion; + + public KinesisConnectionHandler(String stream, String awsRegion) { + _stream = stream; + _awsRegion = awsRegion; + createConnection(); + } + + public KinesisConnectionHandler(String stream, String awsRegion, KinesisClient kinesisClient) { + _stream = stream; + _awsRegion = awsRegion; + _kinesisClient = kinesisClient; + } + + /** + * Lists all shards of the stream + */ + public List<Shard> getShards() { + ListShardsResponse listShardsResponse = + _kinesisClient.listShards(ListShardsRequest.builder().streamName(_stream).build()); + return listShardsResponse.shards(); + } + + /** + * Creates a Kinesis client for the stream + */ + public void createConnection() { + if (_kinesisClient == null) { + _kinesisClient = + KinesisClient.builder().region(Region.of(_awsRegion)).credentialsProvider(DefaultCredentialsProvider.create()) Review comment: `S3PinotFS` has a way of reading `accessKey` and `secretKey` from the config. Do we need a similar thing or `DefaultCredentialsProvider.create()` will be enough? ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisPartitionGroupOffset.java ########## @@ -0,0 +1,75 @@ +/** + * 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.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.io.IOException; +import java.util.Map; +import org.apache.pinot.spi.stream.StreamPartitionMsgOffset; +import org.apache.pinot.spi.utils.JsonUtils; + + +/** + * A {@link StreamPartitionMsgOffset} implementation for the Kinesis partition group consumption + * A partition group consists of 1 or more shards. The KinesisCheckpoint maintains a Map of shards to the sequenceNumber + */ +public class KinesisPartitionGroupOffset implements StreamPartitionMsgOffset { + private final Map<String, String> _shardToStartSequenceMap; + + public KinesisPartitionGroupOffset(Map<String, String> shardToStartSequenceMap) { + _shardToStartSequenceMap = shardToStartSequenceMap; + } + + public KinesisPartitionGroupOffset(String offsetStr) + throws IOException { + _shardToStartSequenceMap = JsonUtils.stringToObject(offsetStr, new TypeReference<Map<String, String>>() { + }); + } + + public Map<String, String> getShardToStartSequenceMap() { + return _shardToStartSequenceMap; + } + + @Override + public String toString() { + try { + return JsonUtils.objectToString(_shardToStartSequenceMap); + } catch (JsonProcessingException e) { + throw new IllegalStateException( + "Caught exception when converting KinesisCheckpoint to string: " + _shardToStartSequenceMap); + } + } + + @Override + public KinesisPartitionGroupOffset fromString(String kinesisCheckpointStr) { + try { + return new KinesisPartitionGroupOffset(kinesisCheckpointStr); + } catch (IOException e) { + throw new IllegalStateException( + "Caught exception when converting string to KinesisCheckpoint: " + kinesisCheckpointStr); + } + } + + @Override + public int compareTo(Object o) { Review comment: @npawar Where do we use `compareTo` for the `StreamPartitionOffset`? ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisPartitionGroupOffset.java ########## @@ -0,0 +1,75 @@ +/** + * 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.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.io.IOException; +import java.util.Map; +import org.apache.pinot.spi.stream.StreamPartitionMsgOffset; +import org.apache.pinot.spi.utils.JsonUtils; + + +/** + * A {@link StreamPartitionMsgOffset} implementation for the Kinesis partition group consumption + * A partition group consists of 1 or more shards. The KinesisCheckpoint maintains a Map of shards to the sequenceNumber + */ +public class KinesisPartitionGroupOffset implements StreamPartitionMsgOffset { + private final Map<String, String> _shardToStartSequenceMap; + + public KinesisPartitionGroupOffset(Map<String, String> shardToStartSequenceMap) { + _shardToStartSequenceMap = shardToStartSequenceMap; + } + + public KinesisPartitionGroupOffset(String offsetStr) + throws IOException { + _shardToStartSequenceMap = JsonUtils.stringToObject(offsetStr, new TypeReference<Map<String, String>>() { + }); + } + + public Map<String, String> getShardToStartSequenceMap() { + return _shardToStartSequenceMap; + } + + @Override + public String toString() { + try { + return JsonUtils.objectToString(_shardToStartSequenceMap); + } catch (JsonProcessingException e) { + throw new IllegalStateException( + "Caught exception when converting KinesisCheckpoint to string: " + _shardToStartSequenceMap); + } + } + + @Override + public KinesisPartitionGroupOffset fromString(String kinesisCheckpointStr) { + try { + return new KinesisPartitionGroupOffset(kinesisCheckpointStr); + } catch (IOException e) { + throw new IllegalStateException( + "Caught exception when converting string to KinesisCheckpoint: " + kinesisCheckpointStr); + } + } + + @Override + public int compareTo(Object o) { + return this._shardToStartSequenceMap.values().iterator().next() Review comment: Do we handle null or empty maps correctly? ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisStreamMetadataProvider.java ########## @@ -0,0 +1,177 @@ +/** + * 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 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.getStream(), kinesisConfig.getAwsRegion()); + _kinesisStreamConsumerFactory = StreamConsumerFactoryProvider.create(streamConfig); + _clientId = clientId; + _fetchTimeoutMs = streamConfig.getFetchTimeoutMillis(); + } + + public KinesisStreamMetadataProvider(String clientId, StreamConfig streamConfig, + KinesisConnectionHandler kinesisConnectionHandler, StreamConsumerFactory streamConsumerFactory) { + KinesisConfig kinesisConfig = new KinesisConfig(streamConfig); + _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> newPartitionGroupMetadatas = new ArrayList<>(); Review comment: `newPartitionGroupMetadatas` -> `newPartitionGroupMetadataList` ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java ########## @@ -0,0 +1,194 @@ +/** + * 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.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 final Logger LOG = LoggerFactory.getLogger(KinesisConsumer.class); Review comment: Let's rename `LOG` -> `LOGGER` to keep the convention ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConfig.java ########## @@ -0,0 +1,68 @@ +/** + * 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.util.Map; +import org.apache.pinot.spi.stream.StreamConfig; +import org.apache.pinot.spi.stream.StreamConfigProperties; +import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; + + +/** + * Kinesis stream specific config + */ +public class KinesisConfig { + public static final String STREAM_TYPE = "kinesis"; + public static final String SHARD_ITERATOR_TYPE = "shard-iterator-type"; + public static final String AWS_REGION = "aws-region"; + public static final String MAX_RECORDS_TO_FETCH = "max-records-to-fetch"; + public static final String DEFAULT_AWS_REGION = "us-central-1"; + public static final String DEFAULT_MAX_RECORDS = "20"; Review comment: Is this some random number or it's based on some observation or experiment? If we simply put a rough number to begin with, let's add `TODO` comment on finding the good default number for this. ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConfig.java ########## @@ -0,0 +1,68 @@ +/** + * 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.util.Map; +import org.apache.pinot.spi.stream.StreamConfig; +import org.apache.pinot.spi.stream.StreamConfigProperties; +import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; + + +/** + * Kinesis stream specific config + */ +public class KinesisConfig { + public static final String STREAM_TYPE = "kinesis"; + public static final String SHARD_ITERATOR_TYPE = "shard-iterator-type"; + public static final String AWS_REGION = "aws-region"; + public static final String MAX_RECORDS_TO_FETCH = "max-records-to-fetch"; + public static final String DEFAULT_AWS_REGION = "us-central-1"; + public static final String DEFAULT_MAX_RECORDS = "20"; + public static final String DEFAULT_SHARD_ITERATOR_TYPE = ShardIteratorType.LATEST.toString(); + private final Map<String, String> _props; + + public KinesisConfig(StreamConfig streamConfig) { + _props = streamConfig.getStreamConfigsMap(); + } + + public KinesisConfig(Map<String, String> props) { + _props = props; + } + + public String getStream() { + return _props + .get(StreamConfigProperties.constructStreamProperty(STREAM_TYPE, StreamConfigProperties.STREAM_TOPIC_NAME)); + } + + public String getAwsRegion() { + return _props.getOrDefault(AWS_REGION, DEFAULT_AWS_REGION); + } + + public Integer maxRecordsToFetch() { Review comment: Rename to `getNumMaxRecordsToFecth()` to keep the convention ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConfig.java ########## @@ -0,0 +1,68 @@ +/** + * 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.util.Map; +import org.apache.pinot.spi.stream.StreamConfig; +import org.apache.pinot.spi.stream.StreamConfigProperties; +import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; + + +/** + * Kinesis stream specific config + */ +public class KinesisConfig { + public static final String STREAM_TYPE = "kinesis"; + public static final String SHARD_ITERATOR_TYPE = "shard-iterator-type"; + public static final String AWS_REGION = "aws-region"; + public static final String MAX_RECORDS_TO_FETCH = "max-records-to-fetch"; + public static final String DEFAULT_AWS_REGION = "us-central-1"; Review comment: I think that we should not put the default value for the region because we cannot make the assumption that the kinesis topic is available in the `us-central-1`. It's better to throw the exception and make this config as `the required field` when using a kinesis based consumer. ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/pom.xml ########## @@ -0,0 +1,177 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + 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. + +--> +<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <artifactId>pinot-stream-ingestion</artifactId> + <groupId>org.apache.pinot</groupId> + <version>0.7.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <artifactId>pinot-kinesis</artifactId> + <name>Pinot Kinesis</name> + <url>https://pinot.apache.org/</url> + <properties> + <pinot.root>${basedir}/../../..</pinot.root> + <phase.prop>package</phase.prop> + <aws.version>2.14.28</aws.version> Review comment: Is there a particular reason on why we are pinning the specific versions here instead of the main pom file? In my understanding, we pin the versions in the top level pom file. ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConfig.java ########## @@ -0,0 +1,68 @@ +/** + * 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.util.Map; +import org.apache.pinot.spi.stream.StreamConfig; +import org.apache.pinot.spi.stream.StreamConfigProperties; +import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; + + +/** + * Kinesis stream specific config + */ +public class KinesisConfig { + public static final String STREAM_TYPE = "kinesis"; + public static final String SHARD_ITERATOR_TYPE = "shard-iterator-type"; + public static final String AWS_REGION = "aws-region"; + public static final String MAX_RECORDS_TO_FETCH = "max-records-to-fetch"; + public static final String DEFAULT_AWS_REGION = "us-central-1"; + public static final String DEFAULT_MAX_RECORDS = "20"; + public static final String DEFAULT_SHARD_ITERATOR_TYPE = ShardIteratorType.LATEST.toString(); + private final Map<String, String> _props; + + public KinesisConfig(StreamConfig streamConfig) { + _props = streamConfig.getStreamConfigsMap(); + } + + public KinesisConfig(Map<String, String> props) { + _props = props; + } + + public String getStream() { Review comment: `getStream()-> getStreamTopicName()` ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConnectionHandler.java ########## @@ -0,0 +1,76 @@ +/** + * 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.util.List; +import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kinesis.KinesisClient; +import software.amazon.awssdk.services.kinesis.model.ListShardsRequest; +import software.amazon.awssdk.services.kinesis.model.ListShardsResponse; +import software.amazon.awssdk.services.kinesis.model.Shard; + + +/** + * Manages the Kinesis stream connection, given the stream name and aws region + */ +public class KinesisConnectionHandler { + protected KinesisClient _kinesisClient; + private final String _stream; + private final String _awsRegion; + + public KinesisConnectionHandler(String stream, String awsRegion) { Review comment: We need the validation for `stream topic name` and `aws region` somewhere (probably kinesis config is the good place) ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConnectionHandler.java ########## @@ -0,0 +1,76 @@ +/** + * 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.util.List; +import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kinesis.KinesisClient; +import software.amazon.awssdk.services.kinesis.model.ListShardsRequest; +import software.amazon.awssdk.services.kinesis.model.ListShardsResponse; +import software.amazon.awssdk.services.kinesis.model.Shard; + + +/** + * Manages the Kinesis stream connection, given the stream name and aws region + */ +public class KinesisConnectionHandler { + protected KinesisClient _kinesisClient; + private final String _stream; + private final String _awsRegion; + + public KinesisConnectionHandler(String stream, String awsRegion) { + _stream = stream; + _awsRegion = awsRegion; + createConnection(); + } + + public KinesisConnectionHandler(String stream, String awsRegion, KinesisClient kinesisClient) { Review comment: Why do we need the constructor that would pass the `kinesisClient`? I thought the main purpose of this connection handler is to create the client object by creating a connection? ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java ########## @@ -0,0 +1,194 @@ +/** + * 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.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 final Logger LOG = LoggerFactory.getLogger(KinesisConsumer.class); + private final String _stream; Review comment: `_stream -> _streamTopicName or _streamName` ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java ########## @@ -0,0 +1,194 @@ +/** + * 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.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 final Logger LOG = LoggerFactory.getLogger(KinesisConsumer.class); + private final String _stream; + private final int _maxRecords; Review comment: `_numMaxRecordsToFetch` ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java ########## @@ -0,0 +1,194 @@ +/** + * 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.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 final Logger LOG = LoggerFactory.getLogger(KinesisConsumer.class); + private final String _stream; + private final int _maxRecords; + private final ExecutorService _executorService; Review comment: Why do we need to create the executor service? ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisPartitionGroupOffset.java ########## @@ -0,0 +1,75 @@ +/** + * 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.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.io.IOException; +import java.util.Map; +import org.apache.pinot.spi.stream.StreamPartitionMsgOffset; +import org.apache.pinot.spi.utils.JsonUtils; + + +/** + * A {@link StreamPartitionMsgOffset} implementation for the Kinesis partition group consumption + * A partition group consists of 1 or more shards. The KinesisCheckpoint maintains a Map of shards to the sequenceNumber Review comment: Can you add more description of `sequenceNumber`? I guess that the sequence number is the Kinesis specific term. Can you add a bit more explanation? Also, is this sequence number inclusive or exclusive? e.g. Let's say that we have a check point,`streamA : 123`. Does this mean that `we have consumed all records from streamA up to the sequence number 123 (inclusive)`? Als ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConfig.java ########## @@ -0,0 +1,68 @@ +/** + * 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.util.Map; +import org.apache.pinot.spi.stream.StreamConfig; +import org.apache.pinot.spi.stream.StreamConfigProperties; +import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; + + +/** + * Kinesis stream specific config + */ +public class KinesisConfig { + public static final String STREAM_TYPE = "kinesis"; + public static final String SHARD_ITERATOR_TYPE = "shard-iterator-type"; + public static final String AWS_REGION = "aws-region"; + public static final String MAX_RECORDS_TO_FETCH = "max-records-to-fetch"; + public static final String DEFAULT_AWS_REGION = "us-central-1"; + public static final String DEFAULT_MAX_RECORDS = "20"; + public static final String DEFAULT_SHARD_ITERATOR_TYPE = ShardIteratorType.LATEST.toString(); + private final Map<String, String> _props; + + public KinesisConfig(StreamConfig streamConfig) { + _props = streamConfig.getStreamConfigsMap(); + } + + public KinesisConfig(Map<String, String> props) { + _props = props; + } + + public String getStream() { + return _props + .get(StreamConfigProperties.constructStreamProperty(STREAM_TYPE, StreamConfigProperties.STREAM_TOPIC_NAME)); + } + + public String getAwsRegion() { + return _props.getOrDefault(AWS_REGION, DEFAULT_AWS_REGION); + } + + public Integer maxRecordsToFetch() { + return Integer.parseInt(_props.getOrDefault(MAX_RECORDS_TO_FETCH, DEFAULT_MAX_RECORDS)); + } + + public ShardIteratorType getShardIteratorType() { + return ShardIteratorType.fromValue(_props.getOrDefault(SHARD_ITERATOR_TYPE, DEFAULT_SHARD_ITERATOR_TYPE)); + } + + public void setMaxRecordsToFetch(int maxRecordsToFetch){ Review comment: Why do we need the setter here? For the config, I think that we should keep this to be read-only. If you need to change this value for testing, you can create the new KinesisConfig object. ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java ########## @@ -0,0 +1,194 @@ +/** + * 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.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 final Logger LOG = LoggerFactory.getLogger(KinesisConsumer.class); + private final String _stream; + private final int _maxRecords; + private final ExecutorService _executorService; + private final ShardIteratorType _shardIteratorType; + + public KinesisConsumer(KinesisConfig kinesisConfig) { + super(kinesisConfig.getStream(), kinesisConfig.getAwsRegion()); + _stream = kinesisConfig.getStream(); + _maxRecords = kinesisConfig.maxRecordsToFetch(); + _shardIteratorType = kinesisConfig.getShardIteratorType(); + _executorService = Executors.newSingleThreadExecutor(); + } + + public KinesisConsumer(KinesisConfig kinesisConfig, KinesisClient kinesisClient) { + super(kinesisConfig.getStream(), kinesisConfig.getAwsRegion(), kinesisClient); + _kinesisClient = kinesisClient; + _stream = kinesisConfig.getStream(); + _maxRecords = kinesisConfig.maxRecordsToFetch(); + _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.Entry<String, String> shardToSequenceNum = + kinesisStartCheckpoint.getShardToStartSequenceMap().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(); + } + + String nextStartSequenceNumber = null; + boolean isEndOfShard = false; + + while (shardIterator != null) { + GetRecordsRequest getRecordsRequest = GetRecordsRequest.builder().shardIterator(shardIterator).build(); + GetRecordsResponse getRecordsResponse = _kinesisClient.getRecords(getRecordsRequest); + + if (getRecordsResponse.records().size() > 0) { + recordList.addAll(getRecordsResponse.records()); + nextStartSequenceNumber = recordList.get(recordList.size() - 1).sequenceNumber(); + + if (kinesisEndSequenceNumber != null && kinesisEndSequenceNumber.compareTo(nextStartSequenceNumber) <= 0) { + nextStartSequenceNumber = kinesisEndSequenceNumber; + break; + } + + if (recordList.size() >= _maxRecords) { + break; + } + } + + if (getRecordsResponse.hasChildShards()) { + //This statement returns true only when end of current shard has reached. + isEndOfShard = true; + break; + } + + shardIterator = getRecordsResponse.nextShardIterator(); + } + + return new KinesisRecordsBatch(recordList, shardToSequenceNum.getKey(), isEndOfShard); + } catch (IllegalStateException e) { + LOG.warn("Illegal state exception, connection is broken", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (ProvisionedThroughputExceededException e) { + LOG.warn("The request rate for the stream is too high", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (ExpiredIteratorException e) { + LOG.warn("ShardIterator expired while trying to fetch records", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (ResourceNotFoundException | InvalidArgumentException e) { + // aws errors + LOG.error("Encountered AWS error while attempting to fetch records", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (KinesisException e) { + LOG.warn("Encountered unknown unrecoverable AWS exception", e); + throw new RuntimeException(e); + } catch (Throwable e) { + // non transient errors + LOG.error("Unknown fetchRecords exception", e); + throw new RuntimeException(e); + } + } + + private KinesisRecordsBatch handleException(KinesisPartitionGroupOffset start, List<Record> recordList) { + String shardId = start.getShardToStartSequenceMap().entrySet().iterator().next().getKey(); + + if (recordList.size() > 0) { + String nextStartSequenceNumber = recordList.get(recordList.size() - 1).sequenceNumber(); + Map<String, String> newCheckpoint = new HashMap<>(start.getShardToStartSequenceMap()); + newCheckpoint.put(newCheckpoint.keySet().iterator().next(), nextStartSequenceNumber); + } + return new KinesisRecordsBatch(recordList, shardId, false); + } + + private String getShardIterator(String shardId, String sequenceNumber) { + Review comment: remove line ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java ########## @@ -0,0 +1,194 @@ +/** + * 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.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 final Logger LOG = LoggerFactory.getLogger(KinesisConsumer.class); + private final String _stream; + private final int _maxRecords; + private final ExecutorService _executorService; + private final ShardIteratorType _shardIteratorType; + + public KinesisConsumer(KinesisConfig kinesisConfig) { + super(kinesisConfig.getStream(), kinesisConfig.getAwsRegion()); + _stream = kinesisConfig.getStream(); + _maxRecords = kinesisConfig.maxRecordsToFetch(); + _shardIteratorType = kinesisConfig.getShardIteratorType(); + _executorService = Executors.newSingleThreadExecutor(); + } + + public KinesisConsumer(KinesisConfig kinesisConfig, KinesisClient kinesisClient) { + super(kinesisConfig.getStream(), kinesisConfig.getAwsRegion(), kinesisClient); + _kinesisClient = kinesisClient; + _stream = kinesisConfig.getStream(); + _maxRecords = kinesisConfig.maxRecordsToFetch(); + _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.Entry<String, String> shardToSequenceNum = + kinesisStartCheckpoint.getShardToStartSequenceMap().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(); + } + + String nextStartSequenceNumber = null; + boolean isEndOfShard = false; + + while (shardIterator != null) { + GetRecordsRequest getRecordsRequest = GetRecordsRequest.builder().shardIterator(shardIterator).build(); + GetRecordsResponse getRecordsResponse = _kinesisClient.getRecords(getRecordsRequest); + + if (getRecordsResponse.records().size() > 0) { + recordList.addAll(getRecordsResponse.records()); + nextStartSequenceNumber = recordList.get(recordList.size() - 1).sequenceNumber(); + + if (kinesisEndSequenceNumber != null && kinesisEndSequenceNumber.compareTo(nextStartSequenceNumber) <= 0) { + nextStartSequenceNumber = kinesisEndSequenceNumber; Review comment: After you assign the new value to `nextStartSequenceNumber`, it will never be accessed. So, I think that this line is redundant. ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisConsumer.java ########## @@ -0,0 +1,194 @@ +/** + * 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.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 final Logger LOG = LoggerFactory.getLogger(KinesisConsumer.class); + private final String _stream; + private final int _maxRecords; + private final ExecutorService _executorService; + private final ShardIteratorType _shardIteratorType; + + public KinesisConsumer(KinesisConfig kinesisConfig) { + super(kinesisConfig.getStream(), kinesisConfig.getAwsRegion()); + _stream = kinesisConfig.getStream(); + _maxRecords = kinesisConfig.maxRecordsToFetch(); + _shardIteratorType = kinesisConfig.getShardIteratorType(); + _executorService = Executors.newSingleThreadExecutor(); + } + + public KinesisConsumer(KinesisConfig kinesisConfig, KinesisClient kinesisClient) { + super(kinesisConfig.getStream(), kinesisConfig.getAwsRegion(), kinesisClient); + _kinesisClient = kinesisClient; + _stream = kinesisConfig.getStream(); + _maxRecords = kinesisConfig.maxRecordsToFetch(); + _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.Entry<String, String> shardToSequenceNum = + kinesisStartCheckpoint.getShardToStartSequenceMap().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(); + } + + String nextStartSequenceNumber = null; + boolean isEndOfShard = false; + + while (shardIterator != null) { + GetRecordsRequest getRecordsRequest = GetRecordsRequest.builder().shardIterator(shardIterator).build(); + GetRecordsResponse getRecordsResponse = _kinesisClient.getRecords(getRecordsRequest); + + if (getRecordsResponse.records().size() > 0) { + recordList.addAll(getRecordsResponse.records()); + nextStartSequenceNumber = recordList.get(recordList.size() - 1).sequenceNumber(); + + if (kinesisEndSequenceNumber != null && kinesisEndSequenceNumber.compareTo(nextStartSequenceNumber) <= 0) { + nextStartSequenceNumber = kinesisEndSequenceNumber; + break; + } + + if (recordList.size() >= _maxRecords) { + break; + } + } + + if (getRecordsResponse.hasChildShards()) { + //This statement returns true only when end of current shard has reached. + isEndOfShard = true; + break; + } + + shardIterator = getRecordsResponse.nextShardIterator(); + } + + return new KinesisRecordsBatch(recordList, shardToSequenceNum.getKey(), isEndOfShard); + } catch (IllegalStateException e) { + LOG.warn("Illegal state exception, connection is broken", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (ProvisionedThroughputExceededException e) { + LOG.warn("The request rate for the stream is too high", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (ExpiredIteratorException e) { + LOG.warn("ShardIterator expired while trying to fetch records", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (ResourceNotFoundException | InvalidArgumentException e) { + // aws errors + LOG.error("Encountered AWS error while attempting to fetch records", e); + return handleException(kinesisStartCheckpoint, recordList); + } catch (KinesisException e) { + LOG.warn("Encountered unknown unrecoverable AWS exception", e); + throw new RuntimeException(e); + } catch (Throwable e) { + // non transient errors + LOG.error("Unknown fetchRecords exception", e); + throw new RuntimeException(e); + } + } + + private KinesisRecordsBatch handleException(KinesisPartitionGroupOffset start, List<Record> recordList) { + String shardId = start.getShardToStartSequenceMap().entrySet().iterator().next().getKey(); + + if (recordList.size() > 0) { + String nextStartSequenceNumber = recordList.get(recordList.size() - 1).sequenceNumber(); + Map<String, String> newCheckpoint = new HashMap<>(start.getShardToStartSequenceMap()); + newCheckpoint.put(newCheckpoint.keySet().iterator().next(), nextStartSequenceNumber); + } + return new KinesisRecordsBatch(recordList, shardId, false); + } + + private String getShardIterator(String shardId, String sequenceNumber) { + + GetShardIteratorRequest.Builder requestBuilder = + GetShardIteratorRequest.builder().streamName(_stream).shardId(shardId).shardIteratorType(_shardIteratorType); + + if (sequenceNumber != null && _shardIteratorType.toString().contains("SEQUENCE")) { Review comment: Let's check the exact string against `ShardIteratorType.AT_SEQUENCE_NUMBER` and `ShardIteratorType.AFTER_SEQUENCE_NUMBER` ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisStreamMetadataProvider.java ########## @@ -0,0 +1,177 @@ +/** + * 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 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.getStream(), kinesisConfig.getAwsRegion()); + _kinesisStreamConsumerFactory = StreamConsumerFactoryProvider.create(streamConfig); + _clientId = clientId; + _fetchTimeoutMs = streamConfig.getFetchTimeoutMillis(); + } + + public KinesisStreamMetadataProvider(String clientId, StreamConfig streamConfig, + KinesisConnectionHandler kinesisConnectionHandler, StreamConsumerFactory streamConsumerFactory) { + KinesisConfig kinesisConfig = new KinesisConfig(streamConfig); + _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> newPartitionGroupMetadatas = 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(); + Shard shard = shardIdToShardMap.get(shardId); + shardsInCurrent.add(shardId); + + 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(); + } + newPartitionGroupMetadatas.add( + new PartitionGroupMetadata(currentPartitionGroupConsumptionStatus.getPartitionGroupId(), newStartOffset)); + } + + // Add new shards. Parent should be null (new table case, very first shards) + // OR it should be flagged as reached EOL and completely consumed. + for (Map.Entry<String, Shard> entry : shardIdToShardMap.entrySet()) { + String newShardId = entry.getKey(); + if (shardsInCurrent.contains(newShardId)) { + continue; + } + StreamPartitionMsgOffset newStartOffset; + Shard newShard = entry.getValue(); + String parentShardId = newShard.parentShardId(); + + if (parentShardId == null || shardsEnded.contains(parentShardId)) { + Map<String, String> shardToSequenceNumberMap = new HashMap<>(); + shardToSequenceNumberMap.put(newShardId, newShard.sequenceNumberRange().startingSequenceNumber()); + newStartOffset = new KinesisPartitionGroupOffset(shardToSequenceNumberMap); + int partitionGroupId = getPartitionGroupIdFromShardId(newShardId); + newPartitionGroupMetadatas.add(new PartitionGroupMetadata(partitionGroupId, newStartOffset)); + } + } + return newPartitionGroupMetadatas; + } + + /** + * Converts a shardId string to a partitionGroupId integer by parsing the digits of the shardId + * e.g. "shardId-000000000001" becomes 1 Review comment: Is shardId guaranteed to be like the above format? It looks that we probably can assume the convention but the official documentation does not guarantee this specific format. https://docs.aws.amazon.com/kinesis/latest/APIReference/API_Shard.html The safer approach can be keeping the mapping from shardId to the partition group Id not to depend on the conversion of shardId returned by Kinesis. ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisStreamMetadataProvider.java ########## @@ -0,0 +1,177 @@ +/** + * 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 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.getStream(), kinesisConfig.getAwsRegion()); + _kinesisStreamConsumerFactory = StreamConsumerFactoryProvider.create(streamConfig); + _clientId = clientId; + _fetchTimeoutMs = streamConfig.getFetchTimeoutMillis(); + } + + public KinesisStreamMetadataProvider(String clientId, StreamConfig streamConfig, + KinesisConnectionHandler kinesisConnectionHandler, StreamConsumerFactory streamConsumerFactory) { + KinesisConfig kinesisConfig = new KinesisConfig(streamConfig); + _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> newPartitionGroupMetadatas = 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(); + Shard shard = shardIdToShardMap.get(shardId); + shardsInCurrent.add(shardId); + + 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(); + } + newPartitionGroupMetadatas.add( + new PartitionGroupMetadata(currentPartitionGroupConsumptionStatus.getPartitionGroupId(), newStartOffset)); + } + + // Add new shards. Parent should be null (new table case, very first shards) + // OR it should be flagged as reached EOL and completely consumed. + for (Map.Entry<String, Shard> entry : shardIdToShardMap.entrySet()) { + String newShardId = entry.getKey(); + if (shardsInCurrent.contains(newShardId)) { + continue; + } + StreamPartitionMsgOffset newStartOffset; + Shard newShard = entry.getValue(); + String parentShardId = newShard.parentShardId(); + + if (parentShardId == null || shardsEnded.contains(parentShardId)) { Review comment: Can there be an edge case for this check? (e.g. Segments with the parent shard id got deleted due to retention before we reach this code path) ########## File path: pinot-plugins/pinot-stream-ingestion/pinot-kinesis/src/main/java/org/apache/pinot/plugin/stream/kinesis/KinesisStreamMetadataProvider.java ########## @@ -0,0 +1,177 @@ +/** + * 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 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.getStream(), kinesisConfig.getAwsRegion()); + _kinesisStreamConsumerFactory = StreamConsumerFactoryProvider.create(streamConfig); + _clientId = clientId; + _fetchTimeoutMs = streamConfig.getFetchTimeoutMillis(); + } + + public KinesisStreamMetadataProvider(String clientId, StreamConfig streamConfig, + KinesisConnectionHandler kinesisConnectionHandler, StreamConsumerFactory streamConsumerFactory) { + KinesisConfig kinesisConfig = new KinesisConfig(streamConfig); + _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> newPartitionGroupMetadatas = 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(); + Shard shard = shardIdToShardMap.get(shardId); + shardsInCurrent.add(shardId); + + 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(); + } + newPartitionGroupMetadatas.add( + new PartitionGroupMetadata(currentPartitionGroupConsumptionStatus.getPartitionGroupId(), newStartOffset)); + } + + // Add new shards. Parent should be null (new table case, very first shards) + // OR it should be flagged as reached EOL and completely consumed. + for (Map.Entry<String, Shard> entry : shardIdToShardMap.entrySet()) { + String newShardId = entry.getKey(); + if (shardsInCurrent.contains(newShardId)) { + continue; + } + StreamPartitionMsgOffset newStartOffset; + Shard newShard = entry.getValue(); + String parentShardId = newShard.parentShardId(); + + if (parentShardId == null || shardsEnded.contains(parentShardId)) { + Map<String, String> shardToSequenceNumberMap = new HashMap<>(); + shardToSequenceNumberMap.put(newShardId, newShard.sequenceNumberRange().startingSequenceNumber()); + newStartOffset = new KinesisPartitionGroupOffset(shardToSequenceNumberMap); + int partitionGroupId = getPartitionGroupIdFromShardId(newShardId); + newPartitionGroupMetadatas.add(new PartitionGroupMetadata(partitionGroupId, newStartOffset)); + } + } + return newPartitionGroupMetadatas; + } + + /** + * Converts a shardId string to a partitionGroupId integer by parsing the digits of the shardId + * e.g. "shardId-000000000001" becomes 1 + */ + private int getPartitionGroupIdFromShardId(String shardId) { + String shardIdNum = StringUtils.stripStart(StringUtils.removeStart(shardId, "shardId-"), "0"); Review comment: let's use static variable for `shardId-` -- 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