Skip to content

Commit 0cfcd90

Browse files
committed
Revert Kinesis changes
1 parent 4665696 commit 0cfcd90

8 files changed

Lines changed: 119 additions & 107 deletions

File tree

external/kinesis-asl/src/main/java/org/apache/spark/examples/streaming/JavaKinesisWordCountASL.java

Lines changed: 48 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -14,31 +14,31 @@
1414
* See the License for the specific language governing permissions and
1515
* limitations under the License.
1616
*/
17-
1817
package org.apache.spark.examples.streaming;
1918

2019
import java.nio.charset.StandardCharsets;
2120
import java.util.ArrayList;
2221
import java.util.Arrays;
22+
import java.util.Iterator;
2323
import java.util.List;
2424
import java.util.regex.Pattern;
2525

26-
import scala.reflect.ClassTag$;
27-
import scala.Tuple2;
28-
29-
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
30-
import com.amazonaws.client.builder.AwsClientBuilder;
31-
import com.amazonaws.services.kinesis.AmazonKinesis;
32-
import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder;
33-
import org.apache.spark.streaming.kinesis.KinesisInitialPositions;
34-
3526
import org.apache.spark.SparkConf;
27+
import org.apache.spark.api.java.function.FlatMapFunction;
28+
import org.apache.spark.api.java.function.Function2;
29+
import org.apache.spark.api.java.function.PairFunction;
3630
import org.apache.spark.storage.StorageLevel;
3731
import org.apache.spark.streaming.Duration;
3832
import org.apache.spark.streaming.api.java.JavaDStream;
3933
import org.apache.spark.streaming.api.java.JavaPairDStream;
4034
import org.apache.spark.streaming.api.java.JavaStreamingContext;
41-
import org.apache.spark.streaming.kinesis.KinesisInputDStream;
35+
import org.apache.spark.streaming.kinesis.KinesisUtils;
36+
37+
import scala.Tuple2;
38+
39+
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
40+
import com.amazonaws.services.kinesis.AmazonKinesisClient;
41+
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream;
4242

4343
/**
4444
* Consumes messages from a Amazon Kinesis streams and does wordcount.
@@ -105,22 +105,25 @@ public static void main(String[] args) throws Exception {
105105
String endpointUrl = args[2];
106106

107107
// Create a Kinesis client in order to determine the number of shards for the given stream
108-
AmazonKinesis kinesisClient = AmazonKinesisClientBuilder.standard()
109-
.withCredentials(new DefaultAWSCredentialsProviderChain())
110-
.withEndpointConfiguration(
111-
new AwsClientBuilder.EndpointConfiguration(endpointUrl, "us-east-1"))
112-
.build();
108+
AmazonKinesisClient kinesisClient =
109+
new AmazonKinesisClient(new DefaultAWSCredentialsProviderChain());
110+
kinesisClient.setEndpoint(endpointUrl);
111+
int numShards =
112+
kinesisClient.describeStream(streamName).getStreamDescription().getShards().size();
113+
113114

114115
// In this example, we're going to create 1 Kinesis Receiver/input DStream for each shard.
115116
// This is not a necessity; if there are less receivers/DStreams than the number of shards,
116117
// then the shards will be automatically distributed among the receivers and each receiver
117118
// will receive data from multiple shards.
118-
int numStreams =
119-
kinesisClient.describeStream(streamName).getStreamDescription().getShards().size();
119+
int numStreams = numShards;
120120

121-
// Spark Streaming batch interval. Same as Kinesis checkpoint interval.
121+
// Spark Streaming batch interval
122122
Duration batchInterval = new Duration(2000);
123123

124+
// Kinesis checkpoint interval. Same as batchInterval for this example.
125+
Duration kinesisCheckpointInterval = batchInterval;
126+
124127
// Get the region name from the endpoint URL to save Kinesis Client Library metadata in
125128
// DynamoDB of the same region as the Kinesis stream
126129
String regionName = KinesisExampleUtils.getRegionNameByEndpoint(endpointUrl);
@@ -133,35 +136,46 @@ public static void main(String[] args) throws Exception {
133136
List<JavaDStream<byte[]>> streamsList = new ArrayList<>(numStreams);
134137
for (int i = 0; i < numStreams; i++) {
135138
streamsList.add(
136-
JavaDStream.fromDStream(KinesisInputDStream.builder()
137-
.streamingContext(jssc)
138-
.checkpointAppName(kinesisAppName).streamName(streamName)
139-
.endpointUrl(endpointUrl).regionName(regionName)
140-
.initialPosition(new KinesisInitialPositions.Latest())
141-
.checkpointInterval(batchInterval).storageLevel(StorageLevel.MEMORY_AND_DISK_2())
142-
.build(), ClassTag$.MODULE$.apply(byte[].class)));
139+
KinesisUtils.createStream(jssc, kinesisAppName, streamName, endpointUrl, regionName,
140+
InitialPositionInStream.LATEST, kinesisCheckpointInterval,
141+
StorageLevel.MEMORY_AND_DISK_2())
142+
);
143143
}
144144

145145
// Union all the streams if there is more than 1 stream
146146
JavaDStream<byte[]> unionStreams;
147147
if (streamsList.size() > 1) {
148-
@SuppressWarnings("unchecked")
149-
JavaDStream<byte[]>[] array = (JavaDStream<byte[]>[]) streamsList.toArray();
150-
unionStreams = jssc.union(array);
148+
unionStreams = jssc.union(streamsList.toArray(new JavaDStream[0]));
151149
} else {
152150
// Otherwise, just use the 1 stream
153151
unionStreams = streamsList.get(0);
154152
}
155153

156154
// Convert each line of Array[Byte] to String, and split into words
157-
JavaDStream<String> words = unionStreams.flatMap(line -> {
158-
String s = new String(line, StandardCharsets.UTF_8);
159-
return Arrays.asList(WORD_SEPARATOR.split(s)).iterator();
155+
JavaDStream<String> words = unionStreams.flatMap(new FlatMapFunction<byte[], String>() {
156+
@Override
157+
public Iterator<String> call(byte[] line) {
158+
String s = new String(line, StandardCharsets.UTF_8);
159+
return Arrays.asList(WORD_SEPARATOR.split(s)).iterator();
160+
}
160161
});
161162

162163
// Map each word to a (word, 1) tuple so we can reduce by key to count the words
163-
JavaPairDStream<String, Integer> wordCounts =
164-
words.mapToPair(s -> new Tuple2<>(s, 1)).reduceByKey((i1, i2) -> i1 + i2);
164+
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
165+
new PairFunction<String, String, Integer>() {
166+
@Override
167+
public Tuple2<String, Integer> call(String s) {
168+
return new Tuple2<>(s, 1);
169+
}
170+
}
171+
).reduceByKey(
172+
new Function2<Integer, Integer, Integer>() {
173+
@Override
174+
public Integer call(Integer i1, Integer i2) {
175+
return i1 + i2;
176+
}
177+
}
178+
);
165179

166180
// Print the first 10 wordCounts
167181
wordCounts.print();

external/kinesis-asl/src/main/scala/org/apache/spark/examples/streaming/KinesisWordCountASL.scala

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ import java.nio.ByteBuffer
2323
import scala.util.Random
2424

2525
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain
26-
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
27-
import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder
26+
import com.amazonaws.services.kinesis.AmazonKinesisClient
2827
import com.amazonaws.services.kinesis.model.PutRecordRequest
2928
import org.apache.log4j.{Level, Logger}
3029

@@ -101,14 +100,12 @@ object KinesisWordCountASL extends Logging {
101100

102101
// Determine the number of shards from the stream using the low-level Kinesis Client
103102
// from the AWS Java SDK.
104-
val provider = new DefaultAWSCredentialsProviderChain()
105-
require(provider.getCredentials != null,
103+
val credentials = new DefaultAWSCredentialsProviderChain().getCredentials()
104+
require(credentials != null,
106105
"No AWS credentials found. Please specify credentials using one of the methods specified " +
107106
"in http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/credentials.html")
108-
val kinesisClient = AmazonKinesisClientBuilder.standard()
109-
.withCredentials(provider)
110-
.withEndpointConfiguration(new EndpointConfiguration(endpointUrl, "us-east-1"))
111-
.build()
107+
val kinesisClient = new AmazonKinesisClient(credentials)
108+
kinesisClient.setEndpoint(endpointUrl)
112109
val numShards = kinesisClient.describeStream(streamName).getStreamDescription().getShards().size
113110

114111

@@ -223,10 +220,8 @@ object KinesisWordProducerASL {
223220
val totals = scala.collection.mutable.Map[String, Int]()
224221

225222
// Create the low-level Kinesis Client from the AWS Java SDK.
226-
val kinesisClient = AmazonKinesisClientBuilder.standard()
227-
.withCredentials(new DefaultAWSCredentialsProviderChain())
228-
.withEndpointConfiguration(new EndpointConfiguration(endpoint, "us-east-1"))
229-
.build()
223+
val kinesisClient = new AmazonKinesisClient(new DefaultAWSCredentialsProviderChain())
224+
kinesisClient.setEndpoint(endpoint)
230225

231226
println(s"Putting records onto stream $stream and endpoint $endpoint at a rate of" +
232227
s" $recordsPerSecond records per second and $wordsPerRecord words per record")

external/kinesis-asl/src/main/scala/org/apache/spark/streaming/kinesis/KinesisBackedBlockRDD.scala

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@ import scala.collection.JavaConverters._
2121
import scala.reflect.ClassTag
2222
import scala.util.control.NonFatal
2323

24-
import com.amazonaws.auth.AWSCredentialsProvider
25-
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
26-
import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder
24+
import com.amazonaws.auth.AWSCredentials
25+
import com.amazonaws.services.kinesis.AmazonKinesisClient
2726
import com.amazonaws.services.kinesis.clientlibrary.types.UserRecord
2827
import com.amazonaws.services.kinesis.model._
2928

@@ -110,8 +109,9 @@ class KinesisBackedBlockRDD[T: ClassTag](
110109
}
111110

112111
def getBlockFromKinesis(): Iterator[T] = {
112+
val credentials = kinesisCreds.provider.getCredentials
113113
partition.seqNumberRanges.ranges.iterator.flatMap { range =>
114-
new KinesisSequenceRangeIterator(kinesisCreds.provider, endpointUrl, regionName,
114+
new KinesisSequenceRangeIterator(credentials, endpointUrl, regionName,
115115
range, kinesisReadConfigs).map(messageHandler)
116116
}
117117
}
@@ -131,17 +131,13 @@ class KinesisBackedBlockRDD[T: ClassTag](
131131
*/
132132
private[kinesis]
133133
class KinesisSequenceRangeIterator(
134-
credentialsProvider: AWSCredentialsProvider,
134+
credentials: AWSCredentials,
135135
endpointUrl: String,
136136
regionId: String,
137137
range: SequenceNumberRange,
138138
kinesisReadConfigs: KinesisReadConfigurations) extends NextIterator[Record] with Logging {
139139

140-
private val client = AmazonKinesisClientBuilder.standard().
141-
withCredentials(credentialsProvider).
142-
withEndpointConfiguration(new EndpointConfiguration(endpointUrl, regionId)).
143-
build()
144-
140+
private val client = new AmazonKinesisClient(credentials)
145141
private val streamName = range.streamName
146142
private val shardId = range.shardId
147143
// AWS limits to maximum of 10k records per get call
@@ -151,6 +147,8 @@ class KinesisSequenceRangeIterator(
151147
private var lastSeqNumber: String = null
152148
private var internalIterator: Iterator[Record] = null
153149

150+
client.setEndpoint(endpointUrl)
151+
154152
override protected def getNext(): Record = {
155153
var nextRecord: Record = null
156154
if (toSeqNumberReceived) {
@@ -218,7 +216,7 @@ class KinesisSequenceRangeIterator(
218216
shardIterator: String,
219217
recordCount: Int): (Iterator[Record], String) = {
220218
val getRecordsRequest = new GetRecordsRequest
221-
getRecordsRequest.setRequestCredentialsProvider(credentialsProvider)
219+
getRecordsRequest.setRequestCredentials(credentials)
222220
getRecordsRequest.setShardIterator(shardIterator)
223221
getRecordsRequest.setLimit(Math.min(recordCount, this.maxGetRecordsLimit))
224222
val getRecordsResult = retryOrTimeout[GetRecordsResult](
@@ -239,7 +237,7 @@ class KinesisSequenceRangeIterator(
239237
iteratorType: ShardIteratorType,
240238
sequenceNumber: String): String = {
241239
val getShardIteratorRequest = new GetShardIteratorRequest
242-
getShardIteratorRequest.setRequestCredentialsProvider(credentialsProvider)
240+
getShardIteratorRequest.setRequestCredentials(credentials)
243241
getShardIteratorRequest.setStreamName(streamName)
244242
getShardIteratorRequest.setShardId(shardId)
245243
getShardIteratorRequest.setShardIteratorType(iteratorType.toString)

external/kinesis-asl/src/main/scala/org/apache/spark/streaming/kinesis/KinesisInputDStream.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ private[kinesis] class KinesisInputDStream[T: ClassTag](
4747
val cloudWatchCreds: Option[SparkAWSCredentials]
4848
) extends ReceiverInputDStream[T](_ssc) {
4949

50+
import KinesisReadConfigurations._
51+
5052
private[streaming]
5153
override def createBlockRDD(time: Time, blockInfos: Seq[ReceivedBlockInfo]): RDD[T] = {
5254

@@ -235,7 +237,7 @@ object KinesisInputDStream {
235237

236238
/**
237239
* Sets the [[SparkAWSCredentials]] to use for authenticating to the AWS Kinesis
238-
* endpoint. Defaults to `DefaultCredentialsProvider` if no custom value is specified.
240+
* endpoint. Defaults to [[DefaultCredentialsProvider]] if no custom value is specified.
239241
*
240242
* @param credentials [[SparkAWSCredentials]] to use for Kinesis authentication
241243
*/

external/kinesis-asl/src/main/scala/org/apache/spark/streaming/kinesis/KinesisTestUtils.scala

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@ import scala.collection.mutable
2626
import scala.collection.mutable.ArrayBuffer
2727
import scala.util.{Failure, Random, Success, Try}
2828

29-
import com.amazonaws.auth.{AWSCredentialsProvider, DefaultAWSCredentialsProviderChain}
30-
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
29+
import com.amazonaws.auth.{AWSCredentials, DefaultAWSCredentialsProviderChain}
3130
import com.amazonaws.regions.RegionUtils
32-
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder
33-
import com.amazonaws.services.kinesis.{AmazonKinesis, AmazonKinesisClientBuilder}
31+
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient
32+
import com.amazonaws.services.dynamodbv2.document.DynamoDB
33+
import com.amazonaws.services.kinesis.{AmazonKinesis, AmazonKinesisClient}
3434
import com.amazonaws.services.kinesis.model._
3535

3636
import org.apache.spark.internal.Logging
@@ -55,18 +55,15 @@ private[kinesis] class KinesisTestUtils(streamShardCount: Int = 2) extends Loggi
5555
private var _streamName: String = _
5656

5757
protected lazy val kinesisClient = {
58-
AmazonKinesisClientBuilder.standard().
59-
withCredentials(KinesisTestUtils.getAWSCredentials()).
60-
withEndpointConfiguration(new EndpointConfiguration(
61-
endpointUrl, KinesisTestUtils.getRegionNameByEndpoint(endpointUrl))).
62-
build()
58+
val client = new AmazonKinesisClient(KinesisTestUtils.getAWSCredentials())
59+
client.setEndpoint(endpointUrl)
60+
client
6361
}
6462

6563
private lazy val dynamoDB = {
66-
AmazonDynamoDBClientBuilder.standard().
67-
withCredentials(new DefaultAWSCredentialsProviderChain()).
68-
withRegion(regionName).
69-
build()
64+
val dynamoDBClient = new AmazonDynamoDBClient(new DefaultAWSCredentialsProviderChain())
65+
dynamoDBClient.setRegion(RegionUtils.getRegion(regionName))
66+
new DynamoDB(dynamoDBClient)
7067
}
7168

7269
protected def getProducer(aggregate: Boolean): KinesisDataGenerator = {
@@ -133,7 +130,7 @@ private[kinesis] class KinesisTestUtils(streamShardCount: Int = 2) extends Loggi
133130
val producer = getProducer(aggregate)
134131
val shardIdToSeqNumbers = producer.sendData(streamName, testData)
135132
logInfo(s"Pushed $testData:\n\t ${shardIdToSeqNumbers.mkString("\n\t")}")
136-
shardIdToSeqNumbers
133+
shardIdToSeqNumbers.toMap
137134
}
138135

139136
/**
@@ -156,7 +153,9 @@ private[kinesis] class KinesisTestUtils(streamShardCount: Int = 2) extends Loggi
156153

157154
def deleteDynamoDBTable(tableName: String): Unit = {
158155
try {
159-
dynamoDB.deleteTable(tableName)
156+
val table = dynamoDB.getTable(tableName)
157+
table.delete()
158+
table.waitForDelete()
160159
} catch {
161160
case e: Exception =>
162161
logWarning(s"Could not delete DynamoDB table $tableName")
@@ -249,13 +248,12 @@ private[kinesis] object KinesisTestUtils {
249248
Try { new DefaultAWSCredentialsProviderChain().getCredentials() }.isSuccess
250249
}
251250

252-
def getAWSCredentials(): AWSCredentialsProvider = {
251+
def getAWSCredentials(): AWSCredentials = {
253252
assert(shouldRunTests,
254253
"Kinesis test not enabled, should not attempt to get AWS credentials")
255-
val provider = new DefaultAWSCredentialsProviderChain()
256-
Try { provider.getCredentials() } match {
257-
case Success(_) => provider
258-
case Failure(_) =>
254+
Try { new DefaultAWSCredentialsProviderChain().getCredentials() } match {
255+
case Success(cred) => cred
256+
case Failure(e) =>
259257
throw new Exception(
260258
s"""
261259
|Kinesis tests enabled using environment variable $envVarNameForEnablingTests
@@ -274,7 +272,7 @@ private[kinesis] trait KinesisDataGenerator {
274272
}
275273

276274
private[kinesis] class SimpleDataGenerator(
277-
client: AmazonKinesis) extends KinesisDataGenerator {
275+
client: AmazonKinesisClient) extends KinesisDataGenerator {
278276
override def sendData(streamName: String, data: Seq[Int]): Map[String, Seq[(Int, String)]] = {
279277
val shardIdToSeqNumbers = new mutable.HashMap[String, ArrayBuffer[(Int, String)]]()
280278
data.foreach { num =>

0 commit comments

Comments
 (0)