-
Notifications
You must be signed in to change notification settings - Fork 29.3k
[SPARK-18682][SS] Batch Source for Kafka #16686
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 9 commits
d371758
b6c3055
4c81812
ab02a4c
e6b57ed
ff94ed8
f8fd34c
41271e2
74d96fc
d31fc81
1db1649
3b0d48b
a5b0269
c08c01f
79d335e
b597cf1
2487a72
789d3af
5b48fc6
5776009
aef89bc
4e56f8c
3bc7c4c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| org.apache.spark.sql.kafka010.KafkaSourceProvider | ||
| org.apache.spark.sql.kafka010.KafkaProvider | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,376 @@ | ||
| /* | ||
| * 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.spark.sql.kafka010 | ||
|
|
||
| import java.{util => ju} | ||
| import java.util.concurrent.{Executor, LinkedBlockingQueue} | ||
|
|
||
| import scala.collection.JavaConverters._ | ||
| import scala.concurrent.{ExecutionContext, Future} | ||
| import scala.concurrent.duration.Duration | ||
| import scala.util.control.NonFatal | ||
|
|
||
| import org.apache.kafka.clients.consumer.{Consumer, ConsumerConfig, KafkaConsumer} | ||
| import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener | ||
| import org.apache.kafka.common.TopicPartition | ||
|
|
||
| import org.apache.spark.internal.Logging | ||
| import org.apache.spark.sql.kafka010.KafkaOffsetReader.ConsumerStrategy | ||
| import org.apache.spark.sql.types._ | ||
| import org.apache.spark.util.{ThreadUtils, UninterruptibleThread} | ||
|
|
||
|
|
||
| private[kafka010] trait KafkaOffsetReader { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. scala docs.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this trait a little weird. |
||
|
|
||
| def close() | ||
|
|
||
| def fetchSpecificStartingOffsets( | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: could you add comments for these methods? |
||
| partitionOffsets: Map[TopicPartition, Long]): Map[TopicPartition, Long] | ||
|
|
||
| def fetchEarliestOffsets(): Map[TopicPartition, Long] | ||
|
|
||
| def fetchLatestOffsets(): Map[TopicPartition, Long] | ||
|
|
||
| def fetchNewPartitionEarliestOffsets( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what is the meaning of new in this context? this a trait which has no other context. why not just be |
||
| newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] | ||
| } | ||
|
|
||
| /** | ||
| * This class uses Kafka's own [[KafkaConsumer]] API to read data offsets from Kafka. | ||
| * | ||
| * - The [[ConsumerStrategy]] class defines which Kafka topics and partitions should be read | ||
| * by this source. These strategies directly correspond to the different consumption options | ||
| * in . This class is designed to return a configured [[KafkaConsumer]] that is used by the | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: extra space.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and why a single bullet point?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. would be good to mention that this class is not threadsafe. i see a lot of vars and all. |
||
| * [[KafkaSource]] to query for the offsets. See the docs on | ||
| * [[org.apache.spark.sql.kafka010.KafkaOffsetReader.ConsumerStrategy]] for more details. | ||
| */ | ||
| private[kafka010] class KafkaOffsetReaderImpl( | ||
| consumerStrategy: ConsumerStrategy, | ||
| driverKafkaParams: ju.Map[String, Object], | ||
| readerOptions: Map[String, String], | ||
| driverGroupIdPrefix: String) | ||
| extends KafkaOffsetReader with Logging { | ||
|
|
||
| /** | ||
| * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the | ||
| * offsets and never commits them. | ||
| */ | ||
| protected var consumer = createConsumer() | ||
|
|
||
| private val maxOffsetFetchAttempts = | ||
| readerOptions.getOrElse("fetchOffset.numRetries", "3").toInt | ||
|
|
||
| private val offsetFetchAttemptIntervalMs = | ||
| readerOptions.getOrElse("fetchOffset.retryIntervalMs", "1000").toLong | ||
|
|
||
| private var groupId: String = null | ||
|
|
||
| private var nextId = 0 | ||
|
|
||
| private def nextGroupId(): String = { | ||
| groupId = driverGroupIdPrefix + "-" + nextId | ||
| nextId += 1 | ||
| groupId | ||
| } | ||
|
|
||
| override def toString(): String = consumerStrategy.toString | ||
|
|
||
| def close(): Unit = consumer.close() | ||
|
|
||
| /** | ||
| * Set consumer position to specified offsets, making sure all assignments are set. | ||
| */ | ||
| def fetchSpecificStartingOffsets( | ||
| partitionOffsets: Map[TopicPartition, Long]): Map[TopicPartition, Long] = | ||
| withRetriesWithoutInterrupt { | ||
| // Poll to get the latest assigned partitions | ||
| consumer.poll(0) | ||
| val partitions = consumer.assignment() | ||
| consumer.pause(partitions) | ||
| assert(partitions.asScala == partitionOffsets.keySet, | ||
| "If startingOffsets contains specific offsets, you must specify all TopicPartitions.\n" + | ||
| "Use -1 for latest, -2 for earliest, if you don't care.\n" + | ||
| s"Specified: ${partitionOffsets.keySet} Assigned: ${partitions.asScala}") | ||
| logDebug(s"Partitions assigned to consumer: $partitions. Seeking to $partitionOffsets") | ||
|
|
||
| partitionOffsets.foreach { | ||
| case (tp, -1) => consumer.seekToEnd(ju.Arrays.asList(tp)) | ||
| case (tp, -2) => consumer.seekToBeginning(ju.Arrays.asList(tp)) | ||
| case (tp, off) => consumer.seek(tp, off) | ||
| } | ||
| partitionOffsets.map { | ||
| case (tp, _) => tp -> consumer.position(tp) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the earliest offsets of partitions. | ||
| */ | ||
| def fetchEarliestOffsets(): Map[TopicPartition, Long] = withRetriesWithoutInterrupt { | ||
| // Poll to get the latest assigned partitions | ||
| consumer.poll(0) | ||
| val partitions = consumer.assignment() | ||
| consumer.pause(partitions) | ||
| logDebug(s"Partitions assigned to consumer: $partitions. Seeking to the beginning") | ||
|
|
||
| consumer.seekToBeginning(partitions) | ||
| val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap | ||
| logDebug(s"Got earliest offsets for partition : $partitionOffsets") | ||
| partitionOffsets | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the latest offset of partitions. | ||
| */ | ||
| def fetchLatestOffsets(): Map[TopicPartition, Long] = withRetriesWithoutInterrupt { | ||
| // Poll to get the latest assigned partitions | ||
| consumer.poll(0) | ||
| val partitions = consumer.assignment() | ||
| consumer.pause(partitions) | ||
| logDebug(s"Partitions assigned to consumer: $partitions. Seeking to the end.") | ||
|
|
||
| consumer.seekToEnd(partitions) | ||
| val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap | ||
| logDebug(s"Got latest offsets for partition : $partitionOffsets") | ||
| partitionOffsets | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the earliest offsets for newly discovered partitions. The return result may not contain | ||
| * some partitions if they are deleted. | ||
| */ | ||
| def fetchNewPartitionEarliestOffsets( | ||
| newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = { | ||
| if (newPartitions.isEmpty) { | ||
| Map.empty[TopicPartition, Long] | ||
| } else { | ||
| withRetriesWithoutInterrupt { | ||
| // Poll to get the latest assigned partitions | ||
| consumer.poll(0) | ||
| val partitions = consumer.assignment() | ||
| consumer.pause(partitions) | ||
| logDebug(s"\tPartitions assigned to consumer: $partitions") | ||
|
|
||
| // Get the earliest offset of each partition | ||
| consumer.seekToBeginning(partitions) | ||
| val partitionOffsets = newPartitions.filter { p => | ||
| // When deleting topics happen at the same time, some partitions may not be in | ||
| // `partitions`. So we need to ignore them | ||
| partitions.contains(p) | ||
| }.map(p => p -> consumer.position(p)).toMap | ||
| logDebug(s"Got earliest offsets for new partitions: $partitionOffsets") | ||
| partitionOffsets | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Helper function that does multiple retries on the a body of code that returns offsets. | ||
| * Retries are needed to handle transient failures. For e.g. race conditions between getting | ||
| * assignment and getting position while topics/partitions are deleted can cause NPEs. | ||
| * | ||
| * This method also makes sure `body` won't be interrupted to workaround a potential issue in | ||
| * `KafkaConsumer.poll`. (KAFKA-1894) | ||
| */ | ||
| private def withRetriesWithoutInterrupt( | ||
| body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = { | ||
| // Make sure `KafkaConsumer.poll` won't be interrupted (KAFKA-1894) | ||
| assert(Thread.currentThread().isInstanceOf[UninterruptibleThread]) | ||
|
|
||
| synchronized { | ||
| var result: Option[Map[TopicPartition, Long]] = None | ||
| var attempt = 1 | ||
| var lastException: Throwable = null | ||
| while (result.isEmpty && attempt <= maxOffsetFetchAttempts | ||
| && !Thread.currentThread().isInterrupted) { | ||
| Thread.currentThread match { | ||
| case ut: UninterruptibleThread => | ||
| // "KafkaConsumer.poll" may hang forever if the thread is interrupted (E.g., the query | ||
| // is stopped)(KAFKA-1894). Hence, we just make sure we don't interrupt it. | ||
| // | ||
| // If the broker addresses are wrong, or Kafka cluster is down, "KafkaConsumer.poll" may | ||
| // hang forever as well. This cannot be resolved in KafkaSource until Kafka fixes the | ||
| // issue. | ||
| ut.runUninterruptibly { | ||
| try { | ||
| result = Some(body) | ||
| } catch { | ||
| case NonFatal(e) => | ||
| lastException = e | ||
| logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e) | ||
| attempt += 1 | ||
| Thread.sleep(offsetFetchAttemptIntervalMs) | ||
| resetConsumer() | ||
| } | ||
| } | ||
| case _ => | ||
| throw new IllegalStateException( | ||
| "Kafka APIs must be executed on a o.a.spark.util.UninterruptibleThread") | ||
| } | ||
| } | ||
| if (Thread.interrupted()) { | ||
| throw new InterruptedException() | ||
| } | ||
| if (result.isEmpty) { | ||
| assert(attempt > maxOffsetFetchAttempts) | ||
| assert(lastException != null) | ||
| throw lastException | ||
| } | ||
| result.get | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Create a consumer using the new generated group id. We always use a new consumer to avoid | ||
| * just using a broken consumer to retry on Kafka errors, which likely will fail again. | ||
| */ | ||
| private def createConsumer(): Consumer[Array[Byte], Array[Byte]] = synchronized { | ||
| val newKafkaParams = new ju.HashMap[String, Object](driverKafkaParams) | ||
| newKafkaParams.put(ConsumerConfig.GROUP_ID_CONFIG, nextGroupId()) | ||
| consumerStrategy.createConsumer(newKafkaParams) | ||
| } | ||
|
|
||
| private def resetConsumer(): Unit = synchronized { | ||
| consumer.close() | ||
| consumer = createConsumer() | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * The Kafka Consumer must be called in an UninterruptibleThread. This naturally occurs | ||
| * in Spark Streaming, but not in Spark SQL, which will use this call to communicate | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: |
||
| * with Kafak for obtaining offsets. | ||
| * | ||
| * @param kafkaOffsetReader Basically in instance of [[KafkaOffsetReaderImpl]] that | ||
| * this class wraps and executes in an [[UninterruptibleThread]] | ||
| */ | ||
| private[kafka010] class UninterruptibleKafkaOffsetReader(kafkaOffsetReader: KafkaOffsetReader) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why does this need a separate class? Can the Then all methods in
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In that case you wont need the separation of KafkaOffsetReader trait and a KafkaOffsetReaderImpl |
||
| extends KafkaOffsetReader with Logging { | ||
|
|
||
| private class KafkaOffsetReaderThread extends UninterruptibleThread("Kafka Offset Reader") { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This must be a daemon thread. Actually, you can create the ExecutionContext using the following simple codes: val kafkaReaderThread = Executors.newSingleThreadExecutor(new ThreadFactory {
override def newThread(r: Runnable): Thread = {
val t = new UninterruptibleThread("Kafka Offset Reader")
t.setDaemon(true)
t
}
})
val execContext = ExecutionContext.fromExecutorService(kafkaReaderThread)
// Close
kafkaReaderThread.shutdownNow() |
||
| override def run(): Unit = { | ||
| while (this.isInterrupted == false) { | ||
| val runnable = queue.take() | ||
| runnable.run() | ||
| } | ||
| } | ||
| } | ||
| private val readerThread = new KafkaOffsetReaderThread | ||
|
|
||
| private val queue = new LinkedBlockingQueue[Runnable]() | ||
|
|
||
| private val execContext = ExecutionContext.fromExecutor(new Executor { | ||
| override def execute(runnable: Runnable): Unit = { | ||
| if (readerThread.isAlive == false) readerThread.start() | ||
| queue.add(runnable) | ||
| } | ||
| }) | ||
|
|
||
|
|
||
| override def close(): Unit = { | ||
| kafkaOffsetReader.close() | ||
| readerThread.interrupt() | ||
| queue.add(new Runnable() { | ||
| override def run(): Unit = { } | ||
| }) | ||
| } | ||
|
|
||
| override def fetchSpecificStartingOffsets( | ||
| partitionOffsets: Map[TopicPartition, Long]): Map[TopicPartition, Long] = { | ||
| val future = Future { | ||
| kafkaOffsetReader.fetchSpecificStartingOffsets(partitionOffsets) | ||
| }(execContext) | ||
| ThreadUtils.awaitResult(future, Duration.Inf) | ||
| } | ||
|
|
||
| override def fetchEarliestOffsets(): Map[TopicPartition, Long] = { | ||
| val future = Future { | ||
| kafkaOffsetReader.fetchEarliestOffsets() | ||
| }(execContext) | ||
| ThreadUtils.awaitResult(future, Duration.Inf) | ||
| } | ||
|
|
||
| override def fetchLatestOffsets(): Map[TopicPartition, Long] = { | ||
| val future = Future { | ||
| kafkaOffsetReader.fetchLatestOffsets() | ||
| }(execContext) | ||
| ThreadUtils.awaitResult(future, Duration.Inf) | ||
| } | ||
|
|
||
| override def fetchNewPartitionEarliestOffsets( | ||
| newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = { | ||
| val future = Future { | ||
| kafkaOffsetReader.fetchNewPartitionEarliestOffsets(newPartitions) | ||
| }(execContext) | ||
| ThreadUtils.awaitResult(future, Duration.Inf) | ||
|
|
||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: empty line |
||
| } | ||
| } | ||
|
|
||
| private[kafka010] object KafkaOffsetReader { | ||
|
|
||
| def kafkaSchema: StructType = StructType(Seq( | ||
| StructField("key", BinaryType), | ||
| StructField("value", BinaryType), | ||
| StructField("topic", StringType), | ||
| StructField("partition", IntegerType), | ||
| StructField("offset", LongType), | ||
| StructField("timestamp", TimestampType), | ||
| StructField("timestampType", IntegerType) | ||
| )) | ||
|
|
||
| sealed trait ConsumerStrategy { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Put consumer strategy in a different file. this file is too big. |
||
| def createConsumer(kafkaParams: ju.Map[String, Object]): Consumer[Array[Byte], Array[Byte]] | ||
| } | ||
|
|
||
| case class AssignStrategy(partitions: Array[TopicPartition]) extends ConsumerStrategy { | ||
| override def createConsumer( | ||
| kafkaParams: ju.Map[String, Object]): Consumer[Array[Byte], Array[Byte]] = { | ||
| val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams) | ||
| consumer.assign(ju.Arrays.asList(partitions: _*)) | ||
| consumer | ||
| } | ||
|
|
||
| override def toString: String = s"Assign[${partitions.mkString(", ")}]" | ||
| } | ||
|
|
||
| case class SubscribeStrategy(topics: Seq[String]) extends ConsumerStrategy { | ||
| override def createConsumer( | ||
| kafkaParams: ju.Map[String, Object]): Consumer[Array[Byte], Array[Byte]] = { | ||
| val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams) | ||
| consumer.subscribe(topics.asJava) | ||
| consumer | ||
| } | ||
|
|
||
| override def toString: String = s"Subscribe[${topics.mkString(", ")}]" | ||
| } | ||
|
|
||
| case class SubscribePatternStrategy(topicPattern: String) | ||
| extends ConsumerStrategy { | ||
| override def createConsumer( | ||
| kafkaParams: ju.Map[String, Object]): Consumer[Array[Byte], Array[Byte]] = { | ||
| val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams) | ||
| consumer.subscribe( | ||
| ju.regex.Pattern.compile(topicPattern), | ||
| new NoOpConsumerRebalanceListener()) | ||
| consumer | ||
| } | ||
|
|
||
| override def toString: String = s"SubscribePattern[$topicPattern]" | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,11 +22,11 @@ import org.apache.kafka.common.TopicPartition | |
| /* | ||
| * Values that can be specified for config startingOffsets | ||
| */ | ||
| private[kafka010] sealed trait StartingOffsets | ||
| private[kafka010] sealed trait KafkaOffsets | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The more I think, I feel that its weird to name this generic "KafkaOffsets". Let's brainstorm on this.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How about
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I went with KafkaOffsetRangeLimit |
||
|
|
||
| private[kafka010] case object EarliestOffsets extends StartingOffsets | ||
| private[kafka010] case object EarliestOffsets extends KafkaOffsets | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. docs. |
||
|
|
||
| private[kafka010] case object LatestOffsets extends StartingOffsets | ||
| private[kafka010] case object LatestOffsets extends KafkaOffsets | ||
|
|
||
| private[kafka010] case class SpecificOffsets( | ||
| partitionOffsets: Map[TopicPartition, Long]) extends StartingOffsets | ||
| partitionOffsets: Map[TopicPartition, Long]) extends KafkaOffsets | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. incorrect indent. i believe 4 indents on continuation of param list. |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @tcondie, I just happened to look at this PR. I just wonder if this breaks existing codes that use
.format("org.apache.spark.sql.kafka010.KafkaSourceProvider")although almost no users use this by that name.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's true, but revised Provider not only provides a Source but also a Relation, hence the decision to rename to something more general. Not clear if this outweighs the risks you've pointed out. @tdas @zsxwing
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The cost of keeping the class name is pretty low. Just discussed with @marmbrus @tdas offline and we agreed to not change the name.