You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by zsxwing <gi...@git.apache.org> on 2016/09/14 21:25:40 UTC

[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

GitHub user zsxwing opened a pull request:

    https://github.com/apache/spark/pull/15102

    [SPARK-17346][SQL] Add Kafka source for Structured Streaming

    ## What changes were proposed in this pull request?
    
    This PR adds a new project ` external/kafka-0-10-sql` for Structured Streaming Kafka source.
    
    It's based on the design doc: https://docs.google.com/document/d/19t2rWe51x7tq2e5AOfrsM9qb8_m7BRuv9fel9i0PqR8/edit?usp=sharing
    
    @tdas did most of work and part of them was inspired by @koeninger's work.
    
    ## How was this patch tested?
    
    The new unit tests.


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/zsxwing/spark kafka-source

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/spark/pull/15102.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #15102
    
----
commit 985cfa9625cdce900e187f8708a832c1262f14b5
Author: Tathagata Das <ta...@gmail.com>
Date:   2016-09-14T00:04:05Z

    Kafka source project

commit c4db857d745e8814892c9ef8076d8752f6cb4e19
Author: Shixiong Zhu <sh...@databricks.com>
Date:   2016-09-14T21:21:02Z

    Add more columns inspired by Cody's work

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81661726
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    --- End diff --
    
    Added group id into logs.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > "I want to be able to add a topicpartition mid stream, but I don't want to start it from the beginning."
    
    I see, I was thinking only of new topics that appear that match your pattern.  I agree that if/when we add that ability to add existing partitions midstream we'd probably need to add two offsets in to the SQL offset for new partitions.
    
    > I think consistency in using json for any non-scalar values is worth 2 extra characters per topic and 4 at the ends.
    
    I'd also support JSON here, but I would not mandate it (i.e. try json parsing and fall back to comma separation).  Its not ambiguous, supports consistent usage, and doesn't penalize the simple use cases.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Source.getOffset returns an sql Offset, not a kafka offset.  At this point
    the current plan is to remove the ordering requirement for sql Offset,
    which makes the whole discussion of comparing ordering for kafka offsets
    irrelevant.  The order is the order in which the driver thread saw sql
    Offsets as it called getOffset.
    
    On Fri, Sep 23, 2016 at 1:24 PM, Jay White Bear <no...@github.com>
    wrote:
    
    > Which offset does getOffset() return one from the partition or something
    > you created? Because it looked like when you were hashing them, you were
    > returning partition offsets.
    >
    > \u2014
    > You are receiving this because you were mentioned.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15102#issuecomment-249266737>, or mute
    > the thread
    > <https://github.com/notifications/unsubscribe-auth/AAGABzXhKpBRDeRAoSIroXJJA_HzEZRXks5qtBlxgaJpZM4J9QvR>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    @koeninger
    I did some independent brainstorming with @zsxwing on topic deletion, and yeah I agree with you that attempting to account for deleted topics in the offset in the KafkaSourceOffset such that compareTo is satisfied is more complicated than just eliminating compareTo. That said, there are still a few corner case - of the same topic being deleted and recreated. I am not familiar with how often this can happen (let us know your thoughts). But the general idea we can implement that that we attach a unique id to the topic in the KafkaSourceOffset. Whenever the new topic is detected (while running or across query restarts), generate a unique id so that it is consider as a new topic. Here are the options
    
    **Option 1: When getOffset detects new topic, if the topic existed in previous offset, create new (topic, unique id)**
    - Pro: Simple
    - Con: Cannot detect if topic gets deleted+recreated between triggers (possibly, across query restarts), 
    
    **Option 2: Use RebalanceListener to know when topic has been deleted**
    - Pro: Handles topic deletion+recreation between triggers while query is active
    - Con: Misses deletion+recreation during query restarts
    - Con: Listener called on different thread, so possible race conditions
    
    **Option 3: Use the creation time / cZxid of topic info stored in ZK to disambiguate**
    - Pro: Zookeeper maintains uniques ness across any component restarts
    - Con: Requires depending on full Kafka + ZK, 
    - Con: Requires knowing the exact ZK path where topics are saved, but this can be tested and made sure that it never fails when we upgrade Kafka
    
    I feel that we should just keep it simple for now, and go for Option 1. What do you think?
    
    
    
    



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    I'm not concerned about people deleting partitions before messages have
    been processed, because they can take care of that problem themselves, by
    not deleting things until consuming has caught up. This is fairly intuitive
    IMHO.
    
    I am concerned about shipping an implementation that can't handle partition
    changes at all, because that's a big step backwards.
    
    On Sep 18, 2016 11:41 PM, "Shixiong Zhu" <no...@github.com> wrote:
    
    > We do need to handle it comparing completely different topicpartitions,
    > because it's entirely possible to have a job with a single topicpartition
    > A, which is deleted or unsubscribed, and then single topicpartition B is
    > added, in the space of one batch.
    >
    > Yeah, it's also possible that when a batch is running, a single
    > topicpartition C is created then deleted. But the Kafka source doesn't even
    > know C. The root issue is currently the approach is polling metadata, and
    > any metadata changes between two pollings are missing.
    >
    > \u2014
    > You are receiving this because you were mentioned.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15102#issuecomment-247910429>, or mute
    > the thread
    > <https://github.com/notifications/unsubscribe-auth/AAGAB4dbMY6oP4EYl062Dd3chUtOk520ks5qrhKQgaJpZM4J9QvR>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65404 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65404/consoleFull)** for PR 15102 at commit [`51d251f`](https://github.com/apache/spark/commit/51d251f742454a835b996ddb7a7d4c226629f4d2).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65401 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65401/consoleFull)** for PR 15102 at commit [`c4db857`](https://github.com/apache/spark/commit/c4db857d745e8814892c9ef8076d8752f6cb4e19).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66285 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66285/consoleFull)** for PR 15102 at commit [`ccadd81`](https://github.com/apache/spark/commit/ccadd81d08f56e45bbe5970656960578ee291bb5).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81850342
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    --- End diff --
    
    +1


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81851594
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when metadata is corrupt (e.g., topics are deleted, or offsets are 
    +  out of range), which may lost data.</td>
    +</tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>(none)</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be 
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>(none)</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern" 
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.consumer.poll.timeoutMs</td>
    +  <td>long</td>
    +  <td>512</td>
    +  <td>The timeout in milliseconds to poll data from Kafka in executors.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.numRetries</td>
    +  <td>int</td>
    +  <td>3</td>
    +  <td>Number of times to retry before giving up fatch Kafka latest offsets.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.retry.intervalMs</td>
    +  <td>long</td>
    --- End diff --
    
    nit: can keep this as int.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > We do need to handle it comparing completely different topicpartitions, because it's entirely possible to have a job with a single topicpartition A, which is deleted or unsubscribed, and then single topicpartition B is added, in the space of one batch.
    
    Yeah, it's also possible that when a batch is running, a single topicpartition C is created then deleted. But the Kafka source doesn't even know C. The root issue is currently the approach is polling metadata, and any metadata changes between two pollings are missing.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81927094
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    +  private lazy val initialPartitionOffsets = {
    +    val metadataLog = new HDFSMetadataLog[KafkaSourceOffset](sqlContext.sparkSession, metadataPath)
    +    metadataLog.get(0).getOrElse {
    +      val offsets = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = false))
    +      metadataLog.add(0, offsets)
    +      logInfo(s"Initial offsets: $offsets")
    +      offsets
    +    }.partitionToOffsets
    +  }
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets
    +   * [`start.get.partitionToOffsets`, `end.partitionToOffsets`), i.e. end.partitionToOffsets is
    +   * exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      reportDataLoss(
    +        s"Cannot find earliest offsets of ${deletedPartitions}. Some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      reportDataLoss(
    +        s"Added partition $p starts from $o instead of 0. Some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"$deletedPartitions are gone. Some data may have been missed")
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val topicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      // Ignore partitions that we don't know the from offsets.
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq
    +    logDebug("TopicPartitions: " + topicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = topicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        // This allows cached KafkaConsumers in the executors to be re-used to read the same
    +        // partition in every batch.
    +        Some(sortedExecutors(floorMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        reportDataLoss(s"Partition ${range.topicPartition}'s offset was changed from " +
    +          s"${range.fromOffset} to ${range.untilOffset}, some data may have been missed")
    +        false
    +      } else {
    +        true
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges, pollTimeoutMs).map { cr =>
    +      Row(cr.key, cr.value, cr.topic, cr.partition, cr.offset, cr.timestamp, cr.timestampType.id)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either seek to the latest offsets or use the current offsets
    +   * in the consumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToEnd: Boolean): Map[TopicPartition, Long] = withRetriesWithoutInterrupt {
    +    // Make sure `KafkaConsumer.poll` won't be interrupted (KAFKA-1894)
    +    assert(Thread.currentThread().isInstanceOf[StreamExecutionThread])
    +    // Poll to get the latest assigned partitions
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"Partitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToEnd) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("Seeked to the end")
    +    }
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /**
    +   * Fetch the earliest offsets for newly discovered partitions. The return results may not contain
    --- End diff --
    
    nit: return results --> result


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66396/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80747895
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    --- End diff --
    
    `groupId` can be read via `kafkaParams.get(ConsumerConfig.GROUP_ID_CONFIG)`.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81878240
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,282 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    require(schema.isEmpty, "Kafka source has a fixed schema and cannot be set with a custom one")
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    // Each running query should use its own group id. Otherwise, the query may be only assigned
    +    // partial data since Kafka will assign partitions to multiple consumers having the same group
    +    // id. Hence, we should generate a unique id for each query.
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // Make sure executors do only what the driver tells them.
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    val failOnDataLoss =
    +      caseInsensitiveParams.getOrElse(FAIL_ON_DATA_LOSS_OPTION_KEY, "true").toBoolean
    +
    +    new KafkaSource(
    +      sqlContext,
    +      strategy,
    +      kafkaParamsForExecutors,
    +      parameters,
    +      metadataPath,
    +      failOnDataLoss)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. Structured Streaming manages which offsets are consumed
    +           |internally, rather than relying on the kafka Consumer to do it. This will ensure that no
    --- End diff --
    
    Done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65401/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80613155
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    --- End diff --
    
    At the very least put the app name or something in there so that people have some hope of knowing what's going on.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65405 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65405/consoleFull)** for PR 15102 at commit [`d3c0754`](https://github.com/apache/spark/commit/d3c0754c9b5c9aa2c29b0d3ca0b28ddae041b054).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65640 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65640/consoleFull)** for PR 15102 at commit [`b64d104`](https://github.com/apache/spark/commit/b64d1046a13ce3b03b2598f13dd2d1aeb1219048).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81926721
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    +  private lazy val initialPartitionOffsets = {
    +    val metadataLog = new HDFSMetadataLog[KafkaSourceOffset](sqlContext.sparkSession, metadataPath)
    +    metadataLog.get(0).getOrElse {
    +      val offsets = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = false))
    +      metadataLog.add(0, offsets)
    +      logInfo(s"Initial offsets: $offsets")
    +      offsets
    +    }.partitionToOffsets
    +  }
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets
    +   * [`start.get.partitionToOffsets`, `end.partitionToOffsets`), i.e. end.partitionToOffsets is
    +   * exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      reportDataLoss(
    +        s"Cannot find earliest offsets of ${deletedPartitions}. Some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      reportDataLoss(
    +        s"Added partition $p starts from $o instead of 0. Some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"$deletedPartitions are gone. Some data may have been missed")
    --- End diff --
    
    Shouldnt this be reportDataLoss instead of logWarning?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81875168
  
    --- Diff: docs/structured-streaming-programming-guide.md ---
    @@ -1126,6 +1126,12 @@ aggDF \
     </div>
     </div>
     
    +## Advanced Sources
    --- End diff --
    
    Discussed offline. Best to move it to the same location where the File and socket sources are discussed. Insert a subheading called Input Sources to mirror the subheading Output Sinks.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030561
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,239 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +The following options should be set for the Kafka source.
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80599175
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    --- End diff --
    
    Actually, I dont even know if these are useful. In fact, in our case, size we are treating them as byte arrays, getting the size is trivial. so we probably dont need these columns right now.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80612619
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        logWarning(s"Partition ${range.topicPartition} was deleted and then added, " +
    +          "some data may have been missed")
    +        false
    +      } else {
    +        true
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(partitions)
    +    val partitionToOffsets = 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 offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Throwable = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case NonFatal(e) =>
    +          lastException = e
    +          e.printStackTrace()
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    +    def createConsumer(): Consumer[Array[Byte], Array[Byte]]
    +  }
    +
    +  case class SubscribeStrategy(topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy(
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    +    def compare(a: ExecutorCacheTaskLocation, b: ExecutorCacheTaskLocation): Boolean = {
    --- End diff --
    
    Why is this an inner function?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80616878
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceRDD.scala ---
    @@ -0,0 +1,163 @@
    +/*
    + * 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 scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.kafka.clients.consumer.{ConsumerRecord, OffsetOutOfRangeException}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{Partition, SparkContext, TaskContext}
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.storage.StorageLevel
    +
    +
    +/** Offset range that one partition of the KafkaSourceRDD has to read */
    +private[kafka010] case class KafkaSourceRDDOffsetRange(
    +    topicPartition: TopicPartition,
    +    fromOffset: Long,
    +    untilOffset: Long,
    +    preferredLoc: Option[String]) {
    +  def topic: String = topicPartition.topic
    +  def partition: Int = topicPartition.partition
    +  def size: Long = untilOffset - fromOffset
    +}
    +
    +
    +/** Partition of the KafkaSourceRDD */
    +private[kafka010] case class KafkaSourceRDDPartition(
    +  index: Int, offsetRange: KafkaSourceRDDOffsetRange) extends Partition
    +
    +
    +/**
    + * An RDD that reads data from Kafka based on offset ranges across multiple partitions.
    + * Additionally, it allows preferred locations to be set for each topic + partition, so that
    + * the [[KafkaSource]] can ensure the same executor always reads the same topic + partition
    + * and cached KafkaConsuemrs (see [[CachedKafkaConsumer]] can be used read data efficiently.
    + *
    + * Note that this is a simplified version of the org.apache.spark.streaming.kafka010.KafkaRDD.
    + *
    + * @param executorKafkaParams Kafka configuration for creating KafkaConsumer on the executors
    + * @param offsetRanges Offset ranges that define the Kafka data belonging to this RDD
    + */
    +private[kafka010] class KafkaSourceRDD(
    +    sc: SparkContext,
    +    executorKafkaParams: ju.Map[String, Object],
    +    offsetRanges: Seq[KafkaSourceRDDOffsetRange])
    +  extends RDD[ConsumerRecord[Array[Byte], Array[Byte]]](sc, Nil) {
    +
    +  override def persist(newLevel: StorageLevel): this.type = {
    +    logError("Kafka ConsumerRecord is not serializable. " +
    +      "Use .map to extract fields before calling .persist or .window")
    +    super.persist(newLevel)
    +  }
    +
    +  override def getPartitions: Array[Partition] = {
    +    offsetRanges.zipWithIndex.map { case (o, i) => new KafkaSourceRDDPartition(i, o) }.toArray
    +  }
    +
    +  override def count(): Long = offsetRanges.map(_.size).sum
    +
    +  override def isEmpty(): Boolean = count == 0L
    +
    +  override def take(num: Int): Array[ConsumerRecord[Array[Byte], Array[Byte]]] = {
    +    val nonEmptyPartitions =
    +      this.partitions.map(_.asInstanceOf[KafkaSourceRDDPartition]).filter(_.offsetRange.size > 0)
    +
    +    if (num < 1 || nonEmptyPartitions.isEmpty) {
    +      return new Array[ConsumerRecord[Array[Byte], Array[Byte]]](0)
    +    }
    +
    +    // Determine in advance how many messages need to be taken from each partition
    +    val parts = nonEmptyPartitions.foldLeft(Map[Int, Int]()) { (result, part) =>
    +      val remain = num - result.values.sum
    +      if (remain > 0) {
    +        val taken = Math.min(remain, part.offsetRange.size)
    +        result + (part.index -> taken.toInt)
    +      } else {
    +        result
    +      }
    +    }
    +
    +    val buf = new ArrayBuffer[ConsumerRecord[Array[Byte], Array[Byte]]]
    +    val res = context.runJob(
    +      this,
    +      (tc: TaskContext, it: Iterator[ConsumerRecord[Array[Byte], Array[Byte]]]) =>
    +      it.take(parts(tc.partitionId)).toArray, parts.keys.toArray
    +    )
    +    res.foreach(buf ++= _)
    +    buf.toArray
    +  }
    +
    +  override def compute(
    +      thePart: Partition,
    +      context: TaskContext): Iterator[ConsumerRecord[Array[Byte], Array[Byte]]] = {
    +    val range = thePart.asInstanceOf[KafkaSourceRDDPartition].offsetRange
    +    assert(
    +      range.fromOffset <= range.untilOffset,
    +      s"Beginning offset ${range.fromOffset} is after the ending offset ${range.untilOffset} " +
    +        s"for topic ${range.topic} partition ${range.partition}. " +
    +        "You either provided an invalid fromOffset, or the Kafka topic has been damaged")
    +    if (range.fromOffset == range.untilOffset) {
    +      logInfo(s"Beginning offset ${range.fromOffset} is the same as ending offset " +
    +        s"skipping ${range.topic} ${range.partition}")
    +      Iterator.empty
    +
    +    } else {
    +
    +      val consumer = CachedKafkaConsumer.getOrCreate(
    +        range.topic, range.partition, executorKafkaParams)
    +      var requestOffset = range.fromOffset
    +
    +      logDebug(s"Creating iterator for $range")
    +
    +      new Iterator[ConsumerRecord[Array[Byte], Array[Byte]]]() {
    +
    +        private var prefetch: ConsumerRecord[Array[Byte], Array[Byte]] = _
    +
    +        private def fetchNext(): ConsumerRecord[Array[Byte], Array[Byte]] = {
    +          try {
    +            val r = consumer.get(requestOffset)
    +            requestOffset += 1
    +            r
    +          } catch {
    +            case e: OffsetOutOfRangeException =>
    +              logWarning(s"${range.topicPartition} was deleted, some data may have been missed")
    --- End diff --
    
    This is egregiously wrong.  That is not the only reason for an offset out of range exception, and this should not be a warning level log.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66005 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66005/consoleFull)** for PR 15102 at commit [`59a93a5`](https://github.com/apache/spark/commit/59a93a561235d4bb0db04b3be6c0325e695df7e2).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81878267
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafka.consumer.poll.timeoutMs", "512").toLong
    --- End diff --
    
    Renamed to `kafkaConsumer.pollTimeoutMs`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #3294 has started](https://amplab.cs.berkeley.edu/jenkins/job/NewSparkPullRequestBuilder/3294/consoleFull)** for PR 15102 at commit [`a6c4970`](https://github.com/apache/spark/commit/a6c4970ace1df46e2d65c2cc8a606f3736454d35).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66338/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66397 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66397/consoleFull)** for PR 15102 at commit [`7d658f1`](https://github.com/apache/spark/commit/7d658f1004375bbc49c60ac5091b56da34f04da2).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80617904
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    --- End diff --
    
    I'm confused as to exactly what you are recommending instead - a case statement for the code that's currently inside Subscribe, SubscribePattern, and eventually Assign?  What's the benefit of doing that?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66338 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66338/consoleFull)** for PR 15102 at commit [`d50a05e`](https://github.com/apache/spark/commit/d50a05eb703acb841b85b04e2b52e958778e6ab1).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66274 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66274/consoleFull)** for PR 15102 at commit [`d154532`](https://github.com/apache/spark/commit/d1545329673e889e93b0e4859248cebff8b488c1).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81663920
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    --- End diff --
    
    > I'm lost on what the point of sorting topic partitions is, if you're still just using topicpartition hashcode as an index into the executors.
    
    Removed the sorting


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65636 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65636/consoleFull)** for PR 15102 at commit [`f5c57f5`](https://github.com/apache/spark/commit/f5c57f51f675002298c833edb486451642735221).
     * This patch **fails to build**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81649092
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    --- End diff --
    
    Updated the description


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81836317
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamTest.scala ---
    @@ -469,29 +469,49 @@ trait StreamTest extends QueryTest with SharedSQLContext with Timeouts {
         }
       }
     
    +
    +  /**
    +   * Creates a stress test that randomly starts/stops/adds data/checks the result.
    +   *
    +   * @param ds a dataframe that executes + 1 on a stream of integers, returning the result
    +   * @param addData an add data action that adds the given numbers to the stream, encoding them
    +   *                as needed
    +   * @param iterations the iteration number
    +   */
    +  def runStressTest(
    +    ds: Dataset[Int],
    +    addData: Seq[Int] => StreamAction,
    +    iterations: Int = 100): Unit = {
    +    runStressTest(ds, Seq.empty, (data, running) => addData(data), iterations)
    +  }
    +
       /**
        * Creates a stress test that randomly starts/stops/adds data/checks the result.
        *
    -   * @param ds a dataframe that executes + 1 on a stream of integers, returning the result.
    -   * @param addData and add data action that adds the given numbers to the stream, encoding them
    +   * @param ds a dataframe that executes + 1 on a stream of integers, returning the result
    +   * @param preparedActions actions need to run before starting the stress test.
    --- End diff --
    
    nit: its kind of odd for this to be past tense.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80793355
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    --- End diff --
    
    Except you also removed it from any logging, which is going to make it hard to tie to a particular stream if you have multiple.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80607406
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    --- End diff --
    
    Why did this remove groupId as compared to the DStreams version?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81873638
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when metadata is corrupt (e.g., topics are deleted, or offsets are 
    +  out of range), which may lost data.</td>
    +</tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>(none)</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be 
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>(none)</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern" 
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.consumer.poll.timeoutMs</td>
    --- End diff --
    
    Then why is it named as kafka.something. Its confusing to have all the kafka params be named as kafka.* and this source option also having kafka. format. 
    Also if you dont expect there to be more params in the subscope of poll, then why make that scope? 
    How about `kafkaConsumer.pollTimeoutMs`?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81873756
  
    --- Diff: docs/structured-streaming-programming-guide.md ---
    @@ -1126,6 +1126,12 @@ aggDF \
     </div>
     </div>
     
    +## Advanced Sources
    --- End diff --
    
    Well there it was explicitly categories as inbuilt sources and advanced sources before this section. Here that is not there. So the term "advanced" does not make sense.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81861633
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,282 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    require(schema.isEmpty, "Kafka source has a fixed schema and cannot be set with a custom one")
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    // Each running query should use its own group id. Otherwise, the query may be only assigned
    +    // partial data since Kafka will assign partitions to multiple consumers having the same group
    +    // id. Hence, we should generate a unique id for each query.
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // Make sure executors do only what the driver tells them.
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    val failOnCorruptMetadata =
    +      caseInsensitiveParams.getOrElse(FAIL_ON_CORRUPT_METADATA_OPTION_KEY, "true").toBoolean
    +
    +    new KafkaSource(
    +      sqlContext,
    +      strategy,
    +      kafkaParamsForExecutors,
    +      parameters,
    +      metadataPath,
    +      failOnCorruptMetadata)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. Structured Streaming manages which offsets are consumed
    +           |internally, rather than rely on the kafka Consumer to do it. This will ensure that no
    --- End diff --
    
    > nit: "relying"
    
    Fixed


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > Merged this to master, @zsxwing do you have another PR for 2.0.
    
    See #15367


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79093876
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    --- End diff --
    
    This is the kind of thing that really weirds me out about copying and pasting code from the initial implementation - it's not at all clear why some of these changes were made.  It's clear that the changes aren't necessary for minimal functionality, because I didn't make them in my fork.
    
    I very firmly believe there needs to be a user-accessible interface for arbitrary configuration of a Kafka Consumer.  The kafka project's interface for setting up consumers isn't really 100% baked yet, and we need to give people a backdoor for getting their jobs done / working around issues with the underlying consumer.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66289 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66289/consoleFull)** for PR 15102 at commit [`a6c4970`](https://github.com/apache/spark/commit/a6c4970ace1df46e2d65c2cc8a606f3736454d35).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80565318
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    --- End diff --
    
    As worded this sounds like a limitation that we plan to fix.  It might be better to say something along the lines of "Structured Streaming manages which offsets are consumed internally, rather than rely on the kafka Consumer to do it."  I'd also clarify that `STARTING_OFFSET_OPTION_KEY` only applies when a new Streaming query is started, and that resuming will always pick up from where the query left off.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Just pushed to verify if the workaround for https://issues.apache.org/jira/browse/KAFKA-1894 does work on Jenkins. Not ready for another round of review.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65640/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81930531
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    +  private lazy val initialPartitionOffsets = {
    +    val metadataLog = new HDFSMetadataLog[KafkaSourceOffset](sqlContext.sparkSession, metadataPath)
    +    metadataLog.get(0).getOrElse {
    +      val offsets = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = false))
    +      metadataLog.add(0, offsets)
    +      logInfo(s"Initial offsets: $offsets")
    +      offsets
    +    }.partitionToOffsets
    +  }
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    // Make sure initialPartitionOffsets is set
    --- End diff --
    
    nit: is set --> is initialized


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65785 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65785/consoleFull)** for PR 15102 at commit [`786af2f`](https://github.com/apache/spark/commit/786af2f415b3b199bbeddb56caa60742e8ac01bb).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65785 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65785/consoleFull)** for PR 15102 at commit [`786af2f`](https://github.com/apache/spark/commit/786af2f415b3b199bbeddb56caa60742e8ac01bb).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66005/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81839555
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    --- End diff --
    
    > Is the metadata really corrupt? These actually seem like valid conditions (even if they affect our ability to provide exactly-once guarantees). What about failOnDataLoss?
    
    There may be no data lost as well. Hard to find a reasonable name :(


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80610814
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        logWarning(s"Partition ${range.topicPartition} was deleted and then added, " +
    --- End diff --
    
    As mentioned in kafka consumer, needs the offsets in question, don't assume its caused by delete + add


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030589
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    +  private lazy val initialPartitionOffsets = {
    +    val metadataLog = new HDFSMetadataLog[KafkaSourceOffset](sqlContext.sparkSession, metadataPath)
    +    metadataLog.get(0).getOrElse {
    +      val offsets = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = false))
    +      metadataLog.add(0, offsets)
    +      logInfo(s"Initial offsets: $offsets")
    +      offsets
    +    }.partitionToOffsets
    +  }
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets
    +   * [`start.get.partitionToOffsets`, `end.partitionToOffsets`), i.e. end.partitionToOffsets is
    +   * exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      reportDataLoss(
    +        s"Cannot find earliest offsets of ${deletedPartitions}. Some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      reportDataLoss(
    +        s"Added partition $p starts from $o instead of 0. Some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"$deletedPartitions are gone. Some data may have been missed")
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val topicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      // Ignore partitions that we don't know the from offsets.
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq
    +    logDebug("TopicPartitions: " + topicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = topicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        // This allows cached KafkaConsumers in the executors to be re-used to read the same
    +        // partition in every batch.
    +        Some(sortedExecutors(floorMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        reportDataLoss(s"Partition ${range.topicPartition}'s offset was changed from " +
    +          s"${range.fromOffset} to ${range.untilOffset}, some data may have been missed")
    +        false
    +      } else {
    +        true
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges, pollTimeoutMs).map { cr =>
    +      Row(cr.key, cr.value, cr.topic, cr.partition, cr.offset, cr.timestamp, cr.timestampType.id)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either seek to the latest offsets or use the current offsets
    +   * in the consumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToEnd: Boolean): Map[TopicPartition, Long] = withRetriesWithoutInterrupt {
    +    // Make sure `KafkaConsumer.poll` won't be interrupted (KAFKA-1894)
    +    assert(Thread.currentThread().isInstanceOf[StreamExecutionThread])
    +    // Poll to get the latest assigned partitions
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"Partitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToEnd) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("Seeked to the end")
    +    }
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /**
    +   * Fetch the earliest offsets for newly discovered partitions. The return results may not contain
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80617036
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceRDD.scala ---
    @@ -0,0 +1,163 @@
    +/*
    + * 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 scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.kafka.clients.consumer.{ConsumerRecord, OffsetOutOfRangeException}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{Partition, SparkContext, TaskContext}
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.storage.StorageLevel
    +
    +
    +/** Offset range that one partition of the KafkaSourceRDD has to read */
    +private[kafka010] case class KafkaSourceRDDOffsetRange(
    +    topicPartition: TopicPartition,
    +    fromOffset: Long,
    +    untilOffset: Long,
    +    preferredLoc: Option[String]) {
    +  def topic: String = topicPartition.topic
    +  def partition: Int = topicPartition.partition
    +  def size: Long = untilOffset - fromOffset
    +}
    +
    +
    +/** Partition of the KafkaSourceRDD */
    +private[kafka010] case class KafkaSourceRDDPartition(
    +  index: Int, offsetRange: KafkaSourceRDDOffsetRange) extends Partition
    +
    +
    +/**
    + * An RDD that reads data from Kafka based on offset ranges across multiple partitions.
    + * Additionally, it allows preferred locations to be set for each topic + partition, so that
    + * the [[KafkaSource]] can ensure the same executor always reads the same topic + partition
    + * and cached KafkaConsuemrs (see [[CachedKafkaConsumer]] can be used read data efficiently.
    + *
    + * Note that this is a simplified version of the org.apache.spark.streaming.kafka010.KafkaRDD.
    + *
    + * @param executorKafkaParams Kafka configuration for creating KafkaConsumer on the executors
    + * @param offsetRanges Offset ranges that define the Kafka data belonging to this RDD
    + */
    +private[kafka010] class KafkaSourceRDD(
    +    sc: SparkContext,
    +    executorKafkaParams: ju.Map[String, Object],
    +    offsetRanges: Seq[KafkaSourceRDDOffsetRange])
    +  extends RDD[ConsumerRecord[Array[Byte], Array[Byte]]](sc, Nil) {
    +
    +  override def persist(newLevel: StorageLevel): this.type = {
    +    logError("Kafka ConsumerRecord is not serializable. " +
    +      "Use .map to extract fields before calling .persist or .window")
    +    super.persist(newLevel)
    +  }
    +
    +  override def getPartitions: Array[Partition] = {
    +    offsetRanges.zipWithIndex.map { case (o, i) => new KafkaSourceRDDPartition(i, o) }.toArray
    +  }
    +
    +  override def count(): Long = offsetRanges.map(_.size).sum
    +
    +  override def isEmpty(): Boolean = count == 0L
    +
    +  override def take(num: Int): Array[ConsumerRecord[Array[Byte], Array[Byte]]] = {
    +    val nonEmptyPartitions =
    +      this.partitions.map(_.asInstanceOf[KafkaSourceRDDPartition]).filter(_.offsetRange.size > 0)
    +
    +    if (num < 1 || nonEmptyPartitions.isEmpty) {
    +      return new Array[ConsumerRecord[Array[Byte], Array[Byte]]](0)
    +    }
    +
    +    // Determine in advance how many messages need to be taken from each partition
    +    val parts = nonEmptyPartitions.foldLeft(Map[Int, Int]()) { (result, part) =>
    +      val remain = num - result.values.sum
    +      if (remain > 0) {
    +        val taken = Math.min(remain, part.offsetRange.size)
    +        result + (part.index -> taken.toInt)
    +      } else {
    +        result
    +      }
    +    }
    +
    +    val buf = new ArrayBuffer[ConsumerRecord[Array[Byte], Array[Byte]]]
    +    val res = context.runJob(
    +      this,
    +      (tc: TaskContext, it: Iterator[ConsumerRecord[Array[Byte], Array[Byte]]]) =>
    +      it.take(parts(tc.partitionId)).toArray, parts.keys.toArray
    +    )
    +    res.foreach(buf ++= _)
    +    buf.toArray
    +  }
    +
    +  override def compute(
    +      thePart: Partition,
    +      context: TaskContext): Iterator[ConsumerRecord[Array[Byte], Array[Byte]]] = {
    +    val range = thePart.asInstanceOf[KafkaSourceRDDPartition].offsetRange
    +    assert(
    +      range.fromOffset <= range.untilOffset,
    +      s"Beginning offset ${range.fromOffset} is after the ending offset ${range.untilOffset} " +
    +        s"for topic ${range.topic} partition ${range.partition}. " +
    +        "You either provided an invalid fromOffset, or the Kafka topic has been damaged")
    +    if (range.fromOffset == range.untilOffset) {
    +      logInfo(s"Beginning offset ${range.fromOffset} is the same as ending offset " +
    +        s"skipping ${range.topic} ${range.partition}")
    +      Iterator.empty
    +
    +    } else {
    +
    +      val consumer = CachedKafkaConsumer.getOrCreate(
    +        range.topic, range.partition, executorKafkaParams)
    +      var requestOffset = range.fromOffset
    +
    +      logDebug(s"Creating iterator for $range")
    +
    +      new Iterator[ConsumerRecord[Array[Byte], Array[Byte]]]() {
    +
    +        private var prefetch: ConsumerRecord[Array[Byte], Array[Byte]] = _
    +
    +        private def fetchNext(): ConsumerRecord[Array[Byte], Array[Byte]] = {
    +          try {
    +            val r = consumer.get(requestOffset)
    +            requestOffset += 1
    +            r
    +          } catch {
    +            case e: OffsetOutOfRangeException =>
    +              logWarning(s"${range.topicPartition} was deleted, some data may have been missed")
    +              null
    +          }
    +        }
    +
    +        override def hasNext(): Boolean = {
    +          if (prefetch == null && requestOffset < range.untilOffset) {
    +            prefetch = fetchNext()
    +          }
    +          prefetch != null
    --- End diff --
    
    I'm assuming the rest of these changes and the addition of prefetch is to support silently returning the wrong thing in case of offset out of range?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81648834
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,185 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +
    +    // Subscribe to multiple topics
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +
    +    // Subscribe to a pattern
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +
    +    // Subscribe to multiple topics
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +
    +    // Subscribe to a pattern
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +
    +    # Subscribe to multiple topics
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +
    +    # Subscribe to a pattern
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    --- End diff --
    
    Added an example to convert key/value to strings.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80562234
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    +    def createConsumer(): Consumer[Array[Byte], Array[Byte]]
    +  }
    +
    +  case class SubscribeStrategy(topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy(
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    +    def compare(a: ExecutorCacheTaskLocation, b: ExecutorCacheTaskLocation): Boolean = {
    +      if (a.host == b.host) { a.executorId > b.executorId } else { a.host > b.host }
    +    }
    +
    +    val bm = sc.env.blockManager
    +    bm.master.getPeers(bm.blockManagerId).toArray
    +      .map(x => ExecutorCacheTaskLocation(x.host, x.executorId))
    +      .sortWith(compare)
    +      .map(_.toString)
    +  }
    +}
    +
    +
    +/** An [[Offset]] for the [[KafkaSource]]. */
    +private[kafka010]
    +case class KafkaSourceOffset(partitionToOffsets: Map[TopicPartition, Long]) extends Offset {
    --- End diff --
    
    Can we move this into its own file?  I would also explain What exactly we are tracking and why since there has been a lot of confusion on what the requirements are here.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81661705
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    +    kafkaParams: ju.Map[String, Object]) extends Logging {
    +
    +  private val consumer = {
    +    val c = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +    val tps = new ju.ArrayList[TopicPartition]()
    +    tps.add(topicPartition)
    +    c.assign(tps)
    +    c
    +  }
    +
    +  /**
    +   * Timeout for polls to the consumer. Since the data should be already available, the poll
    +   * should get the data immediately, and the timeout value should not matter as long as it is
    +   * generous and does not cause timeout when there are not issues.
    +   */
    +  private val pollTimeoutMs = 60 * 1000
    --- End diff --
    
    Added an option for this one.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80616098
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceRDD.scala ---
    @@ -0,0 +1,163 @@
    +/*
    + * 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 scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.kafka.clients.consumer.{ConsumerRecord, OffsetOutOfRangeException}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{Partition, SparkContext, TaskContext}
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.storage.StorageLevel
    +
    +
    +/** Offset range that one partition of the KafkaSourceRDD has to read */
    +private[kafka010] case class KafkaSourceRDDOffsetRange(
    +    topicPartition: TopicPartition,
    +    fromOffset: Long,
    +    untilOffset: Long,
    +    preferredLoc: Option[String]) {
    +  def topic: String = topicPartition.topic
    +  def partition: Int = topicPartition.partition
    +  def size: Long = untilOffset - fromOffset
    +}
    +
    +
    +/** Partition of the KafkaSourceRDD */
    +private[kafka010] case class KafkaSourceRDDPartition(
    +  index: Int, offsetRange: KafkaSourceRDDOffsetRange) extends Partition
    +
    +
    +/**
    + * An RDD that reads data from Kafka based on offset ranges across multiple partitions.
    + * Additionally, it allows preferred locations to be set for each topic + partition, so that
    + * the [[KafkaSource]] can ensure the same executor always reads the same topic + partition
    + * and cached KafkaConsuemrs (see [[CachedKafkaConsumer]] can be used read data efficiently.
    + *
    + * Note that this is a simplified version of the org.apache.spark.streaming.kafka010.KafkaRDD.
    --- End diff --
    
    Why is this the only place that has this note, when much of the code in other classes (e.g. cached consumer) is taken from that as well?  Not saying it's necessary to have it everywhere, just seems inconsistent


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79088295
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    --- End diff --
    
    nit: "read" data


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66287 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66287/consoleFull)** for PR 15102 at commit [`f78c990`](https://github.com/apache/spark/commit/f78c9901a1edaa5a1d4a969195671626a63e1ec6).
     * This patch **fails Scala style tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81648912
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    --- End diff --
    
    Moved KafkaSourceOffset to a new file


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81622511
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,281 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    require(schema.isEmpty, "Kafka source has a fixed schema and cannot be set with a custom one")
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    // Each running query should use its own group id. Otherwise, the query may be only assigned
    +    // partial data since Kafka will assign partitions to multiple consumers having the same group
    +    // id. Hence, we should generate a unique id for each query.
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // Make sure executors do only what the driver tells them.
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    val failOnCorruptMetadata =
    +      caseInsensitiveParams.getOrElse(FAIL_ON_CORRUPT_METADATA_OPTION_KEY, "false").toBoolean
    --- End diff --
    
    This is still defaulting to false, but the docs say (and I believe it should) default to true.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81658824
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceRDD.scala ---
    @@ -0,0 +1,163 @@
    +/*
    + * 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 scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.kafka.clients.consumer.{ConsumerRecord, OffsetOutOfRangeException}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{Partition, SparkContext, TaskContext}
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.storage.StorageLevel
    +
    +
    +/** Offset range that one partition of the KafkaSourceRDD has to read */
    +private[kafka010] case class KafkaSourceRDDOffsetRange(
    +    topicPartition: TopicPartition,
    +    fromOffset: Long,
    +    untilOffset: Long,
    +    preferredLoc: Option[String]) {
    +  def topic: String = topicPartition.topic
    +  def partition: Int = topicPartition.partition
    +  def size: Long = untilOffset - fromOffset
    +}
    +
    +
    +/** Partition of the KafkaSourceRDD */
    +private[kafka010] case class KafkaSourceRDDPartition(
    +  index: Int, offsetRange: KafkaSourceRDDOffsetRange) extends Partition
    +
    +
    +/**
    + * An RDD that reads data from Kafka based on offset ranges across multiple partitions.
    + * Additionally, it allows preferred locations to be set for each topic + partition, so that
    + * the [[KafkaSource]] can ensure the same executor always reads the same topic + partition
    + * and cached KafkaConsuemrs (see [[CachedKafkaConsumer]] can be used read data efficiently.
    + *
    + * Note that this is a simplified version of the org.apache.spark.streaming.kafka010.KafkaRDD.
    + *
    + * @param executorKafkaParams Kafka configuration for creating KafkaConsumer on the executors
    + * @param offsetRanges Offset ranges that define the Kafka data belonging to this RDD
    + */
    +private[kafka010] class KafkaSourceRDD(
    +    sc: SparkContext,
    +    executorKafkaParams: ju.Map[String, Object],
    +    offsetRanges: Seq[KafkaSourceRDDOffsetRange])
    +  extends RDD[ConsumerRecord[Array[Byte], Array[Byte]]](sc, Nil) {
    +
    +  override def persist(newLevel: StorageLevel): this.type = {
    +    logError("Kafka ConsumerRecord is not serializable. " +
    +      "Use .map to extract fields before calling .persist or .window")
    +    super.persist(newLevel)
    +  }
    +
    +  override def getPartitions: Array[Partition] = {
    +    offsetRanges.zipWithIndex.map { case (o, i) => new KafkaSourceRDDPartition(i, o) }.toArray
    +  }
    +
    +  override def count(): Long = offsetRanges.map(_.size).sum
    +
    --- End diff --
    
    > Why missing countApprox?
    
    Added


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65694/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80567253
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    --- End diff --
    
    Are these redundant with the key/value?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79094763
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    --- End diff --
    
    Are you talking about a difference in GenericRow vs GenericInternalRow, or are you saying this shouldn't be a map over an rdd at all?  Sorry, I'm not anywhere near familiar enough with the sql internals.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    I asked @koeninger to clarify the specific suggestions he is referring to above, here's my response:
    
    > [Comments here and on JIRA relating to concerns with the `Offset` implementation]
    
    I'd be happy to consider a PR (either against this branch now or against master if this patch is merged) to use a different offset for `KafkaSource`, or even change the offset API in all of structured streaming. A change that large however would need to be a different PR, and should not block this one unless there are correctness issues. I'd want to see some test cases though that show why the current implementation is wrong from an end-user perspective if it needs to block merging initial kafka support.
     
    > [Comments here and on JIRA about using String -> String for configuration]
    
    I'd also be happy to consider PRs to improve the DataFrameReader/Writer interface.  That would also need to be in a separate PR.  It would need to work well across languages and be backwards compatible (i.e. what happens when you are using an older data source with the new configuration system?).
    
    That said, we already have something that we've been using since Spark 1.3, even if its not perfect. It does work across languages and I don't see a problem with supporting comma separated strings long term for topic lists (kafka even does this today in its own configuration for things like `bootstrap.servers`.).  As a result, I do not think it is reasonable to suggest we block merging this patch on an overhaul of the DataSource API configuration system.
    
    I think @koeninger made a good suggestion to block accepting certain kafka configurations.  In particular, `auto.offset.reset` does not make sense in a world where we are managing the offsets ourselves (kafka documentation suggests you set this to false if you maintain offsets externally).  Similarly, letting the user set the group id could cause data to get split with a different query and thus could affect correctness.  My only question here is if we should have a whitelist or a blacklist.  Scanning though the list of possible configuration options, I think it could go either way.  I tend to error on this side of more power and go with the blacklist.
    
    I disagree that prefixing configuration that should be passed to kafka with kafka is a hack.  We do this in other places in the DataFrameReader/Writer API and have not had any complaints or confusion.  I could be convinced otherwise if someone can point out a case where this would be confusing or ambiguous to a user.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80609930
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    --- End diff --
    
    If you're completely leaving out the ability for people to run executors on the same nodes as brokers and get locality, that needs to be clearly documented.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > This already does depend on most of the existing Kafka DStream implementation....
    
    I pushed for this code to be copied rather than refactored because I think this is the right direction long term.  While it is nice to minimize inter-project dependencies, that is not really the motivation.  While the code is very similar now, there a bunch of things I'd like to start changing:
     - I don't think that all the classes need to be type parameterized.  Our interface  SQL has its own type system, analyser, and interface to the type system of the JVM (encoders).  We should be using that.  Operators in SQL do not type parameterize in general.
     - To optimize performance, there are several tricks we might want to play eventually (maybe prefetching data during execution, etc).
    
    These are just ideas, but given that DStreams and Structured Streaming have significantly different models and user interfaces, I don't think that we want to tie ourselves to the same internals.  If we identify utilities that are needed by both, then we should pull those out and share them.
    
    > Users are going to change topicpartitions whether you want them to or not...
    
    I think we need to take a step back here and look at what is actually required by the `Offset` interface.  We don't need to handle the general problem of is kafka `Offset A` from `Topic 1` before or after kafka `Offset B` from `Topic 2`.  We'll only ever look at full `KafkaOffsets` that represent slices in time across a couple of topicpartitions and were returned by the `Source` (possibly with other annotations the Source wants to add).  The only questions that the the `StreamExecution` will ask today are:
     - Does `x: KafkaOffset == y: KafkaOffset` (i.e. is there new data since the last time I checked)?
     - Give me the data between `KafkaOffset` x and `KafkaOffset` y for all included topicpartitions.
    
    The final version of this `Source` should almost certainly support wildcards with topicpartitions that change on the fly.  Since it seems this is one of the harder problems to solve.  As a strawman, I'd propose that we only support static lists of topics in this PR and possibly even static partitions.  I want to get users to kick the tires on structured streaming in general and report whats missing so we can all prioritize our engineering effort.
    
    > It's clear from the jira this shouldn't get rushed into 2.0.1, let's do this as right as possible given the circumstances.
    
    Agreed, if this doesn't make 2.0.1 thats fine with me.
    
    > How can we collaborate on a shared branch? You guys manually copying stuff from my fork doesn't make any sense.
    
    I typically open PRs against [the PR author's branch](https://github.com/zsxwing/spark/tree/kafka-source) when I want to collaborate more directly.
    
    > Can you give some specific technical direction as to how users can communicate the type for key and value, without having to map over the stream as is done in this PR?
    
    I'd like this to work the same as other calculations in SQL, using column expressions.
    
    ```scala
    df.withColumn("value", $"value".cast("string"))
    ```
    
    I'd also like to create expressions that work well with kafka specific deserializers, as well as integrations with our json parsing and maybe Avro too.  The nice thing about this path is it fits with other SQL APIs and should play nicely with Dataset `Encoder`s, UDFs, our expression library, etc.
    
    Does that seem reasonable?  Is this missing important cases?
    



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81851399
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when metadata is corrupt (e.g., topics are deleted, or offsets are 
    +  out of range), which may lost data.</td>
    +</tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>(none)</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be 
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>(none)</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern" 
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.consumer.poll.timeoutMs</td>
    --- End diff --
    
    this is not a spark specific one. this can be in the must-be-specified table.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80584097
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    --- End diff --
    
    We don't have to fix this here, but this is probably really slow.  We should be using the internal APIs here.  I might open a PR against this branch to encode directly into tungsten format.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79089541
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    +    def createConsumer(): Consumer[K, V]
    +  }
    +
    +  case class SubscribeStrategy[K, V](topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy[K, V](
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    +    def compare(a: ExecutorCacheTaskLocation, b: ExecutorCacheTaskLocation): Boolean = {
    +      if (a.host == b.host) { a.executorId > b.executorId } else { a.host > b.host }
    +    }
    +
    +    val bm = sc.env.blockManager
    +    bm.master.getPeers(bm.blockManagerId).toArray
    +      .map(x => ExecutorCacheTaskLocation(x.host, x.executorId))
    +      .sortWith(compare)
    +      .map(_.toString)
    +  }
    +}
    +
    +
    +/** An [[Offset]] for the [[KafkaSource]]. */
    +private[kafka010]
    +case class KafkaSourceOffset(partitionToOffsets: Map[TopicPartition, Long]) extends Offset {
    +  /**
    +   * Returns a negative integer, zero, or a positive integer as this object is less than, equal to,
    +   * or greater than the specified object.
    +   */
    +  override def compareTo(other: Offset): Int = other match {
    +    case KafkaSourceOffset(otherOffsets) =>
    +      val allTopicAndPartitions = (this.partitionToOffsets.keySet ++ otherOffsets.keySet).toSeq
    +
    +      val comparisons = allTopicAndPartitions.map { tp =>
    +        (this.partitionToOffsets.get(tp), otherOffsets.get(tp)) match {
    +          case (Some(a), Some(b)) =>
    +            if (a < b) {
    +              -1
    +            } else if (a > b) {
    +              1
    +            } else {
    +              0
    +            }
    +          case (None, _) => -1
    +          case (_, None) => 1
    +        }
    +      }
    +      val nonZeroSigns = comparisons.filter { _ != 0 }.toSet
    +      nonZeroSigns.size match {
    +        case 0 => 0 // if both empty or only 0s
    +        case 1 => nonZeroSigns.head // if there are only (0s and 1s) or (0s and -1s)
    +        case _ => // there are both 1s and -1s
    +          throw new IllegalArgumentException(
    +            s"Invalid comparison between non-linear histories: $this <=> $other")
    +      }
    +
    +    case _ =>
    +      throw new IllegalArgumentException(s"Cannot compare $this <=> $other")
    +  }
    +
    +  override def toString(): String = {
    +    partitionToOffsets.toSeq.sortBy(_._1.toString).mkString("[", ", ", "]")
    +  }
    +}
    +
    +/** Companion object of the [[KafkaSourceOffset]] */
    +private[kafka010] object KafkaSourceOffset {
    +
    +  def getPartitionOffsets(offset: Offset): Map[TopicPartition, Long] = {
    +    offset match {
    +      case o: KafkaSourceOffset => o.partitionToOffsets
    +      case _ =>
    +        throw new IllegalArgumentException(
    +          s"Invalid conversion from offset of ${offset.getClass} to KafkaSourceOffset")
    +    }
    +  }
    +
    +  /**
    +   * Returns [[KafkaSourceOffset]] from a variable sequence of (topic, partitionId, offset)
    +   * tuples.
    +   */
    +  def apply(offsetTuples: (String, Int, Long)*): KafkaSourceOffset = {
    +    KafkaSourceOffset(offsetTuples.map { case(t, p, o) => (new TopicPartition(t, p), o) }.toMap)
    +  }
    +}
    +
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +  private val strategyOptionNames = Set("subscribe", "subscribepattern")
    +
    +  /** Class to conveniently update Kafka config params, while logging the changes */
    +  private case class ConfigUpdater(module: String, kafkaParams: Map[String, String]) {
    +    private val map = new ju.HashMap[String, Object](kafkaParams.asJava)
    +    def set(key: String, value: Object): this.type = {
    +      map.put(key, value)
    +      logInfo(s"$module: Set $key to $value, earlier value: ${kafkaParams.get(key).getOrElse("")}")
    +      this
    +    }
    +
    +    def setIfUnset(key: String, value: Object): ConfigUpdater = {
    +      if (!map.containsKey(key)) {
    +        map.put(key, value)
    +        logInfo(s"$module: Set $key to $value")
    +      }
    +      this
    +    }
    +
    +    def build(): ju.Map[String, Object] = map
    +  }
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +    validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with user-specified group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG,
    +          "spark-executor-" + specifiedKafkaParams(ConsumerConfig.GROUP_ID_CONFIG))
    +
    +        // So that consumers in executors no keep committing offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => strategyOptionNames.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy[Array[Byte], Array[Byte]](
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy[Array[Byte], Array[Byte]](
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case(k, _) => strategyOptionNames.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + strategyOptionNames.mkString(", ") + ". See docs for more details.")
    --- End diff --
    
    Are there any docs? :)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80617145
  
    --- Diff: external/kafka-0-10-sql/pom.xml ---
    @@ -0,0 +1,82 @@
    +<?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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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>
    +    <groupId>org.apache.spark</groupId>
    +    <artifactId>spark-parent_2.11</artifactId>
    +    <version>2.1.0-SNAPSHOT</version>
    +    <relativePath>../../pom.xml</relativePath>
    +  </parent>
    +
    +  <groupId>org.apache.spark</groupId>
    +  <artifactId>spark-sql-kafka-0-10_2.11</artifactId>
    +  <properties>
    +    <sbt.project.name>sql-kafka-0-10</sbt.project.name>
    +  </properties>
    +  <packaging>jar</packaging>
    +  <name>Spark Integration for Kafka 0.10</name>
    --- End diff --
    
    This has the same name as the DStream, should probably be changed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > My bigger concern is that it looks like you guys are continuing to hack in a particular direction, without addressing my points or answering whether you're willing to let me help work on this.
    Have you made up your mind?
    
    Cody, I think we have been addressing your points, though I know we are not done yet. It would be helpful if you could make specific comments on the code, preferably with pointers to what you think the correct implementation would look like.  Otherwise its hard to track which points you think have been resolved and which are still in question.
    
    I appreciate that you are concerned that some of this code is duplicated, but I'm going to have to respectfully disagree on that point.  I think this is the right choice both for the stability of the DStream implementation and our ability to optimize the SQL implementation.
    
    > You should not be assuming 0 for a starting offset for partitions you've just learned about. You should be asking the underlying driver consumer what its position is.
    
    I'll let Ryan comment further here, but I'm not sure if this is correct.  It sounds like if we rely on Kafka to manage the its position there will be cases where partial failure could result it data loss.  In general, I think we need to be careful about relying on Kafka internals when our end goal is to provide a much [higher level abstraction](https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#programming-model).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    This is pretty much the fundamental issue.  Kafka offsets alone aren't
    capable of meeting the SQL Offset interface as defined.  I think that means
    the Offset interface needs to be reconsidered or eliminated.  I think that
    work needs to be done now, before even more work gets put into a
    fundamentally unworkable interface.  I don't see what the rush is, because
    this isn't going to make it into 2.0.1 anyway.
    
    
    On Thu, Sep 22, 2016 at 12:29 PM, Shixiong Zhu <no...@github.com>
    wrote:
    
    > PR with failing test indicating at least one reason why it's wrong from an
    > end-user perspective:
    >
    > @koeninger <https://github.com/koeninger> Thanks for writing the test.
    > Yes, we are aware of this issue. However, it's unlikely that we can support
    > deleting topics using the current Source API. You can take a look at how
    > StreamExecution checks the new data here: https://github.com/apache/
    > spark/blob/976f3b1227c1a9e0b878e010531285fdba57b6a7/sql/core/src/main/
    > scala/org/apache/spark/sql/execution/streaming/StreamExecution.scala#L320
    >
    > Using the hash code to compare offsets has a potential issue, it may make
    > the latest offset be smaller than the old offset, then StreamExecution
    > won't process the new data.
    >
    > I think one possible solution is StreamExecution doesn't compare the
    > offsets, instead, it just assumes getOffset will always return the latest
    > offset, and it never rollback to an old offset. This needs more discussion
    > anyway. Hence I suggest we don't block this PR for this. Deleting topics
    > can be supported in a later PR when we make an agreement on how to resolve
    > the issue.
    >
    > \u2014
    > You are receiving this because you were mentioned.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15102#issuecomment-248971360>, or mute
    > the thread
    > <https://github.com/notifications/unsubscribe-auth/AAGAB0a4SZx4Zjq4hMkI6tSLIDwJLW8Bks5qsrsUgaJpZM4J9QvR>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66289 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66289/consoleFull)** for PR 15102 at commit [`a6c4970`](https://github.com/apache/spark/commit/a6c4970ace1df46e2d65c2cc8a606f3736454d35).
     * This patch **fails from timeout after a configured wait of \`250m\`**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > We are not giving the developer the option to manually configure a consumer in this way for this PR precisely because I don't think we can while still maintaining the semantics that structured streaming has promised.
    
    You've got this backwards.  As soon as you give someone the ability to set auto.offset.reset to largest, it opens up the can of worms as to whether resets should happen at the beginning of a stream, during a stream, and/or when a partition is added.  Giving people the ability to configure a consumer doesn't cause that problem, it allows them to solve that problem until such time as the Kafka project has a unified way to solve it.  Similarly, as soon as you allow pattern subscriptions, it opens up the can of worms as to adding/removing topics and whether the sql Offset interface as is makes sense for Kafka.  Just saying you aren't going to handle deletions for right now doesn't solve that problem.  
    
    If you really don't want to consider changing the Offset interface, and want to tell people who need the details of Kafka in order to work done to use the DStream, then you should probably eliminate all configuration options except brokers, a list of topics, and maybe SSL.
    
    I'll try one more time, and then I'm done:
    - Months ago you came up with an interface that realistically will only work with Kafka / Kinesis / lookalikes, yet had no implementation for any of those.
    - Actually attempting an implementation raised some notable differences between what the interface allowed for and what the implementation needed.
    - I offered some specific suggestions, including considering changes to the interface
    - I offered to help with implementation
    
    Your response, from my point of view, has been
    - Decline to consider changes to the interface
    - Decline any assistance with actual implementation
    - Only (re)implement a subset of Kafka functionality that you can see is "safe", regardless of whether it's congruent with the way Kafka is already being used by users.
    
    Under those circumstances, I'm happy to answer specific directed questions you may have, but I'm not interested in continuing to argue.  If you guys say you've got this and you're going to do it your way, then you've got it.
    
    Let me know if you change your mind, I'll still be around.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80614481
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    --- End diff --
    
    @marmbrus the new consumer shouldn't be using ZK for consumer groups, so this shouldn't leak state into ZK.  I quickly verified this with a spark job that had auto commit turned off.  It will show up in the list of consumer groups though, and a senseless name may make it hard for people that want to do monitoring via kafka tools.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    For streaming you already know what the global order is, because you know when you asked for A and B.  I agree that we should probably remove the comparable requirement from `Offset` in favor of just having equality.  At the time it was a useful safe guard, but its clearly causing more confusion than anything.
    
    Assuming `A` was retrieved before `B`, then it seems like you emit a warning that data was possibly missed from A (since it was deleted before we could get it) and you start a new batch on topic B from offsets 0-1.  Right?
    
    > Or do you actually think that stuff like option("assign", "topicA:1:1,topicA:2:2,topicB:3:3") makes it clear what the arguments are?
    
    We don't support assign.  When we do add that support, that is not super easy to follow, I don't feel strongly that its better or worse than JSON though if its unambiguous.
    
    Are there arguments that we do support that you think are confusing?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65926 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65926/consoleFull)** for PR 15102 at commit [`755ceaa`](https://github.com/apache/spark/commit/755ceaa3531a690f755982a55c71f977c3039bc0).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `        // ('scaled' = +Infinity). However in the case that this class also has`
      * `        // 0 probability, the class will not be selected ('scaled' is NaN).`
      * `  final val thresholds: DoubleArrayParam = new DoubleArrayParam(this, \"thresholds\", \"Thresholds in multi-class classification to adjust the probability of predicting each class. Array must have length equal to the number of classes, with values > 0 excepting that at most one value may be 0. The class with largest value p/t is predicted, where p is the original probability of that class and t is the class's threshold\", (t: Array[Double]) => t.forall(_ >= 0) && t.count(_ == 0) <= 1)`
      * `    thresholds = Param(Params._dummy(), \"thresholds\", \"Thresholds in multi-class classification to adjust the probability of predicting each class. Array must have length equal to the number of classes, with values > 0, excepting that at most one value may be 0. The class with largest value p/t is predicted, where p is the original probability of that class and t is the class's threshold.\", typeConverter=TypeConverters.toListFloat)`
      * `case class SortOrder(child: Expression, direction: SortDirection, nullOrdering: NullOrdering)`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    We can add an option to allow the user failing the query instead of just logging the warning.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80568624
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    --- End diff --
    
    nit: indentation


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65937/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80605915
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    --- End diff --
    
    Unless you're 100% sure what people are doing with custom deserializers, I'd recommend keeping everything available that could be obtained from a ConsumerRecord.  If you're concerned about bloat, give people a choice between 2 schema, one with all the fields and one with just key / value.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80599802
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    --- End diff --
    
    Seems that is obvious from the fact that there are wild cards in the name.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81661605
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    --- End diff --
    
    > Should we be using configuration for these?
    
    Added configs


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65404/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    I spent a while playing around with this today on a real cluster, and overall it is pretty cool!  I have a few suggestions we should implement in the long run, but these can probably be done in follow-up PRs
     - It would be nice to be able to do something other than earliest/latest.  In particular, I have some low volume streams where I want to go back a bit as I'm working interactively.  Going back all the way results in a really long job.  If there was a time index, I'd love to say `-10 minutes` but even just `-100 offsets would be great.
     - When specifying `earliest`, you end up with really big partitions.  As a result you get virtually no progress reporting until its done.  I'd consider having a max number of offsets in a task.  It should be easy to split them up in `getBatch`.  One question, is it a problem if two tasks are pulling from the same topic partition in parallel?  Does this break the assumptions of our caching?
     - Similarly, you get no results until the end.  We might also want to have a `maxOffsetsInBatch` similar to what we have in the `FileStreamSource`.
    
    I can do a final pass over the code, but do we think we are getting close to something that we can merge and iterate on?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Ok, finished a line-by-line compare + comment.
    
    The biggest thing I'm having trouble reconciling is the stated emphasis on limiting user options in order to give guarantees, yet throwing those guarantees away with only warn level logging (e.g. the handling of offset out of range exception).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Ok, so this kind of thing is why I was concerned about the copy, paste, randomly change things approach to developing this module.
    
    > (5) Topics are deleted when a Spark job is runinng, which may cause OffsetOutOfRangeException. (I'm not sure if there are more types of exceptions, may need to investigate) Solution: log a warning. Note: if a Spark job fails, then the query will fail as well.
    
    OffsetOutOfRangeException basically means you asked Kafka for an offset, and it wasn't there.  The most common reason this happens isn't because a topic got deleted, it's because messages expired out of retention before they got read.
    
    Just logging at warning level and continuing in this situation is catastrophically, someone-loses-their-paying-job-not-their-spark-job, bad.
    
    The existing kafka DStream integrations that have been around for 7 spark versions will just let that exception be thrown, resulting in errors / failed tasks, which make it pretty obvious that something is really wrong.
    
    If you think that behavior is incorrect, let's figure out a unified behavior for how to deal with exceptional situations that break fundamental assumptions, and make it reallllly obvious to users how to get the behavior they need across both modules.  But having the structured stream behave in significantly different ways seems like a recipe for trouble.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    * This already does depend on most of the existing Kafka DStream implementation.  The fact that most of it was copied wholesale proves that.  If you're just saying that you don't want it to have a transitive dependency on the spark-streaming-X module, I can refactor that.  I would much rather take the time to do that work personally now, as opposed to the maintenance problems later.
    
    * Users are going to change topicpartitions whether you want them to or not, and this PR ostensibly supports SubscribePattern, so it must handle changing topicpartitions.  Kafka does not have a global order  (Kafka doesn't even have a per-partition order that's guaranteed contiguous, see SPARK-17147, but that's another can of worms).  Given an offset from topicpartition A and an offset from topicpartition B, it is impossible to determine ordering without some other information.  I brought some of these concerns up during the structured streaming design document, and it was handwaved as we'll just make structured offset an interface and try to figure it out later.  I believe my PR does the least bad thing possible given this interface, in that it does allow changing partitions, does not violate hashcode, and does have a stable order (if we really want to deal with hashcode collisions, we can sort and concat all topicpartitions or something).  If you see something else wrong there,
  by all means let me know.  Yes, if someone publishes data to a topicpartition right before deleting it, the stream may not consume that data, but... really, what did they expect to happen in that case?  We can talk about whether it might be possible to use time indexing in kafka as an alternative ordering, but what's there right now doesn't cut it.
    
    My thoughts at this point:
    
    * It's clear from the jira this shouldn't get rushed into 2.0.1, let's do this as right as possible given the circumstances.
    * How can we collaborate on a shared branch?  You guys manually copying stuff from my fork doesn't make any sense.
    * @marmbrus Can you give some specific technical direction as to how users can communicate the type for key and value, without having to map over the stream as is done in this PR?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80615842
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. This will ensure that no data is missed when when new
    +           |topics/partitions are dynamically subscribed. See the docs for more details.
    +         """.stripMargin)
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as keys are " +
    +          s"deserialized as byte arrays with ByteArrayDeserializer. Use Dataframe operations to " +
    +          s"explicitly deserialize the keys.")
    --- End diff --
    
    This needs to point to documentation on how I use this with string K, V and MyCustomClass


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79088914
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    --- End diff --
    
    Can we split this file up?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80609252
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    --- End diff --
    
    So if I was just reading this, I'd expect the initial offsets to always start at the earliest offset, since the argument seekToLatest was false.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66047 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66047/consoleFull)** for PR 15102 at commit [`9d95d52`](https://github.com/apache/spark/commit/9d95d52cd1cb9ef83efaaadc5d4e9a5dc3e1c843).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    My fork is not following auto.offset.reset, it's following what the
    (potentially user-provided) consumer does when it sees a new partition.
    Maybe that's auto.offset.reset, maybe it's something else.
    
    Either way, who are you to presume that a user doesn't know what she is
    doing when she configured a consumer to start at a particular position for
    an added partition?  You have no guarantee that offset 0L even exists at
    that time.
    
    On Tue, Sep 20, 2016 at 2:52 PM, Shixiong Zhu <no...@github.com>
    wrote:
    
    > You should not be assuming 0 for a starting offset for partitions you've
    > just learned about. You should be asking the underlying driver consumer
    > what its position is.
    >
    > Yes, there are two approaches for getting new partitions' offsets:
    >
    >    1. From a user perspective, if I set \u201cauto.offset.reset\u201d to latest, I
    >    would like to process new data after the query starts. So we should start
    >    from the earliest offset for a new partition.
    >    2. Follow auto.offset.reset as what you did in your fork.
    >
    > However, option 2 makes the query result indeterminate when
    > auto.offset.reset is latest, depends on how the query runs. E.g., if you
    > add new partitions and push new data very quickly, the new data may be
    > lost; if you add new partitions and push new data when the app is being
    > recovered, the new data may be lost as well.
    >
    > \u2014
    > You are receiving this because you were mentioned.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15102#issuecomment-248414530>, or mute
    > the thread
    > <https://github.com/notifications/unsubscribe-auth/AAGAB1U_gCyEfg0GHzuymzWp3wtZ4zNoks5qsDmYgaJpZM4J9QvR>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    We aren't comparing ordering of offsets across partitions, and I don't
    think that was ever in consideration.  At this point the most likely
    candidate for the global ordering is implicit in the single driver thread
    that is asking for getOffset
    
    On Sep 23, 2016 12:41 AM, "Jay White Bear" <no...@github.com> wrote:
    
    > Just curious looking at this, if you are comparing "sequential" offsets
    > across partitions a rebalance would definitely affect this and, unless
    > something has changed, it probably not a good idea to compare offsets from
    > kafka across partitions. You could simply add an id/timestamp to the
    > producer and send it with the message rather than using this methodology or
    > if you must use offset query the broker for the full list and compare what
    > you consumed to that list (small increase in latency btwn consumption and
    > processing). This is from the Kafka paper, which makes me question your
    > scheme: "...Note that our message ids are increasing but not consecutive.
    > To compute the id of the next message, we have to add the length of the
    > current message to its id." This means simply comparing which offsets are
    > larger will not necessarily yield you the most recent message across
    > partitions and definitely won't hold in a rebalance during which time some
    > broker logs will be on hold and not consumed. In my own implementation, the
    > offsets are great for message guarantees (eg delivery/consumption checks),
    > because the broker has a full ordered list, but not for cross partition
    > ordering.
    >
    > \u2014
    > You are receiving this because you were mentioned.
    > Reply to this email directly, view it on GitHub
    > <https://github.com/apache/spark/pull/15102#issuecomment-249107463>, or mute
    > the thread
    > <https://github.com/notifications/unsubscribe-auth/AAGAB8MjSGueEHbEv3gXHkFiV5_CfsTqks5qs2Z2gaJpZM4J9QvR>
    > .
    >



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > I'd want to see some test cases though that show why the current implementation is wrong from an end-user perspective if it needs to block merging initial kafka support.
    
    PR with failing test indicating at least one reason why it's wrong from an end-user perspective:
    
    https://github.com/zsxwing/spark/pull/4
    
    >  I do not think it is reasonable to suggest we block merging this patch on an overhaul of the DataSource API configuration system.
    
    Here's what I actually said:
    'if you know your plan down the line is to use json for structured configuration, you should use it now, and provide more convenient ways to construct json later, not use "convenient" non-json hacks now.'
    
    No hyperbole about blocking on a complete overhaul, nothing that isn't backwards compatible.  I'm just saying that, if the design document already recognizes that json is necessary to work around the string -> string interface... start using structured json strings now, and make it more convenient later.
    
    Or do you actually think that stuff like
    
    option("assign", "topicA:1:1,topicA:2:2,topicB:3:3")
    
    makes it clear what the arguments are?
    
    > I think @koeninger made a good suggestion to block accepting certain kafka configurations.
    
    In case it wasn't clear, I was not suggesting that preventing users from doing things they could otherwise do with Kafka is actually a good idea.  I think it's a bad idea, but if you're going to run with it, you might as well be consistent about it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80616386
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceRDD.scala ---
    @@ -0,0 +1,163 @@
    +/*
    + * 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 scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.kafka.clients.consumer.{ConsumerRecord, OffsetOutOfRangeException}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{Partition, SparkContext, TaskContext}
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.storage.StorageLevel
    +
    +
    +/** Offset range that one partition of the KafkaSourceRDD has to read */
    +private[kafka010] case class KafkaSourceRDDOffsetRange(
    +    topicPartition: TopicPartition,
    +    fromOffset: Long,
    +    untilOffset: Long,
    +    preferredLoc: Option[String]) {
    +  def topic: String = topicPartition.topic
    +  def partition: Int = topicPartition.partition
    +  def size: Long = untilOffset - fromOffset
    +}
    +
    +
    +/** Partition of the KafkaSourceRDD */
    +private[kafka010] case class KafkaSourceRDDPartition(
    +  index: Int, offsetRange: KafkaSourceRDDOffsetRange) extends Partition
    +
    +
    +/**
    + * An RDD that reads data from Kafka based on offset ranges across multiple partitions.
    + * Additionally, it allows preferred locations to be set for each topic + partition, so that
    + * the [[KafkaSource]] can ensure the same executor always reads the same topic + partition
    + * and cached KafkaConsuemrs (see [[CachedKafkaConsumer]] can be used read data efficiently.
    + *
    + * Note that this is a simplified version of the org.apache.spark.streaming.kafka010.KafkaRDD.
    + *
    + * @param executorKafkaParams Kafka configuration for creating KafkaConsumer on the executors
    + * @param offsetRanges Offset ranges that define the Kafka data belonging to this RDD
    + */
    +private[kafka010] class KafkaSourceRDD(
    +    sc: SparkContext,
    +    executorKafkaParams: ju.Map[String, Object],
    +    offsetRanges: Seq[KafkaSourceRDDOffsetRange])
    +  extends RDD[ConsumerRecord[Array[Byte], Array[Byte]]](sc, Nil) {
    +
    +  override def persist(newLevel: StorageLevel): this.type = {
    +    logError("Kafka ConsumerRecord is not serializable. " +
    +      "Use .map to extract fields before calling .persist or .window")
    +    super.persist(newLevel)
    +  }
    +
    +  override def getPartitions: Array[Partition] = {
    +    offsetRanges.zipWithIndex.map { case (o, i) => new KafkaSourceRDDPartition(i, o) }.toArray
    +  }
    +
    +  override def count(): Long = offsetRanges.map(_.size).sum
    +
    --- End diff --
    
    Why missing countApprox?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80609099
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    --- End diff --
    
    This is semantics, but it's not the ending Sql Offset that is excluded, it's the ending kafka offsets that are excluded.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80612293
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        logWarning(s"Partition ${range.topicPartition} was deleted and then added, " +
    +          "some data may have been missed")
    +        false
    +      } else {
    +        true
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(partitions)
    +    val partitionToOffsets = 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 offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Throwable = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case NonFatal(e) =>
    +          lastException = e
    +          e.printStackTrace()
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    +    def createConsumer(): Consumer[Array[Byte], Array[Byte]]
    +  }
    +
    +  case class SubscribeStrategy(topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    --- End diff --
    
    So this has none of the workaround in the direct stream for KAFKA-3370.  I realize that's because you guys are trying to limit people to only auto.offset.reset = latest or earliest.
    
    But that also means that if people have no way of setting auto.offset.reset to none, those of us who would prefer to know loud and clear when our stream falls sufficiently behind that it resets... are totally out of luck, right?  Seems like a pretty big potential violation of stream guarantees.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged this to master, @zsxwing do you have another PR for 2.0.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80614899
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    --- End diff --
    
    This comment is backwards.  The idea is for executors to do only what the driver tells them, i.e. _throw_ an exception if given an offset that they can't fulfill.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66274 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66274/consoleFull)** for PR 15102 at commit [`d154532`](https://github.com/apache/spark/commit/d1545329673e889e93b0e4859248cebff8b488c1).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Just from a very brief look, this duplicates egregious amounts of code from the existing Kafka submodule and doesn't handle offset ordering correctly when topicpartitions change.
    
    I'd -1 on this, wholesale, if I had the right to.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66288 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66288/consoleFull)** for PR 15102 at commit [`7ff1059`](https://github.com/apache/spark/commit/7ff10599fdadcbdd2515b3216d35307e906de184).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81873748
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafka.consumer.poll.timeoutMs", "512").toLong
    --- End diff --
    
    > What is this option named as "kafka.consumer.poll.timeoutMs". This makes it look like that it is a kafka param. Which it is not.
    
    How about `executor.poll.timeoutMs`?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030551
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,239 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +The following options should be set for the Kafka source.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>meaning</th></tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern"
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.bootstrap.servers</td>
    +  <td>A comma-separated list of host:port</td>
    +  <td>The Kafka "bootstrap.servers" configuration.</td>
    +</tr>
    +</table>
    +
    +The rest configurations are optional:
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81851039
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    --- End diff --
    
    I would split this into two tables, one that must be specified (subscribe/subscribePattern, and kafka.bootstrap...) and then optional params.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Comparable requirement removed in #15207.
    
    > I think in the absence of prior information about the position in a topicpartition, you start a new batch on topic B starting from wherever the consumer's position was at the time it acquired the subscription, which might not be 0. I.e. you call position() before seekToEnd().
    
    Why do you care when it acquired it?  If it appeared in-between the the last batch and now, don't you want to consume all of the available data from it?  Otherwise the answer is going to depend on the specifics on when you see the topic, which seems counter to the model of Structured Streaming.
    
    > I think the main thing that would be confusing is to specify topics in one way (custom-delimited string) for one configuration, and in another way (structured json) for another configuration.
    
    Are you proposing users have to type `"[\"topic1\", \"topic2\"]` (or pull in a json library) instead of `"topic1,topic2"`?  Seems we could pretty seamlessly add support for JSON in the future, while still making the common case easy to type.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    @tdas I think as long as marmbrus' PR to remove comparable from the interface works for sane variations of subscription changes it's the best way to go.  I'm honestly fine with someone getting what they deserve if they delete and recreate a topic in the space of a single batch or while a stream is down.
    
    @marmbrus 
    > Why do you care when it acquired it? 
    
    This isn't so much a temporal thing, as a let the consumer do its job thing.  This sort of configuration should ideally be handled by auto.offset.reset, and we shouldn't bake in too much second guessing about it.  There's plenty of use case for "I want to be able to add a topicpartition mid stream, but I don't want to start it from the beginning."
    
    > Are you proposing users have to type
    
    I'm saying that you guys proposed json as a workaround for the string->string thing.  Given that, yeah, I think consistency in using json for any non-scalar values is worth 2 extra characters per topic and 4 at the ends.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66265 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66265/consoleFull)** for PR 15102 at commit [`e883062`](https://github.com/apache/spark/commit/e88306267e372101a685492afcfa652408a83109).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65685/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79676581
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    --- End diff --
    
    I disagree that we should expose half-baked external API's in the MVP.  Specifically, it sounds like doing so would allow users to setup configurations that would violate the correctness guarantees.  This is not to say that we should never expose these, but instead that I would value stability, simplicity and correctness over extra functionality.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66397 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66397/consoleFull)** for PR 15102 at commit [`7d658f1`](https://github.com/apache/spark/commit/7d658f1004375bbc49c60ac5091b56da34f04da2).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030538
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,239 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +The following options should be set for the Kafka source.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>meaning</th></tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern"
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.bootstrap.servers</td>
    +  <td>A comma-separated list of host:port</td>
    +  <td>The Kafka "bootstrap.servers" configuration.</td>
    +</tr>
    +</table>
    +
    +The rest configurations are optional:
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnDataLoss</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when it's possible that data is lost (e.g., topics are deleted, or 
    +  offsets are out of range). This may be a false alarm. You can disable it when it doesn't work
    +  as you expected.</td>
    +</tr>
    +<tr>
    +  <td>kafkaConsumer.pollTimeoutMs</td>
    +  <td>long</td>
    +  <td>512</td>
    +  <td>The timeout in milliseconds to poll data from Kafka in executors.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.numRetries</td>
    +  <td>int</td>
    +  <td>3</td>
    +  <td>Number of times to retry before giving up fatch Kafka latest offsets.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.retryIntervalMs</td>
    +  <td>long</td>
    +  <td>10</td>
    +  <td>milliseconds to wait before retrying to fetch Kafka offsets</td>
    +</tr>
    +</table>
    +
    +Kafka's own configurations can be set via `DataStreamReader.option` with `kafka.` prefix, e.g, 
    +`stream.option("kafka.bootstrap.servers", "host:port")`. For possible kafkaParams, see 
    +[Kafka consumer config docs](http://kafka.apache.org/documentation.html#newconsumerconfigs).
    +
    +Note that the following Kafka params cannot be set and the Kafka source will throw an exception:
    +- **group.id**: Kafka source will create a unique group id for each query automatically.
    +- **auto.offset.reset**: Set the source option `startingOffset` to `earliest` or `latest` to specify
    + where to start instead. Structured Streaming manages which offsets are consumed internally, rather 
    + than rely on the kafka Consumer to do it. This will ensure that no data is missed when when new 
    + topics/partitions are dynamically subscribed. Note that `startingOffset` only applies when a new
    + Streaming query is started, and that resuming will always pick up from where the query left off.
    +- **key.deserializer**: Keys are always deserialized as byte arrays with ByteArrayDeserializer. Use 
    + Dataframe operations to explicitly deserialize the keys.
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79092976
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    +    def createConsumer(): Consumer[K, V]
    +  }
    +
    +  case class SubscribeStrategy[K, V](topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy[K, V](
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    +    def compare(a: ExecutorCacheTaskLocation, b: ExecutorCacheTaskLocation): Boolean = {
    +      if (a.host == b.host) { a.executorId > b.executorId } else { a.host > b.host }
    +    }
    +
    +    val bm = sc.env.blockManager
    +    bm.master.getPeers(bm.blockManagerId).toArray
    +      .map(x => ExecutorCacheTaskLocation(x.host, x.executorId))
    +      .sortWith(compare)
    +      .map(_.toString)
    +  }
    +}
    +
    +
    +/** An [[Offset]] for the [[KafkaSource]]. */
    +private[kafka010]
    +case class KafkaSourceOffset(partitionToOffsets: Map[TopicPartition, Long]) extends Offset {
    +  /**
    +   * Returns a negative integer, zero, or a positive integer as this object is less than, equal to,
    +   * or greater than the specified object.
    +   */
    +  override def compareTo(other: Offset): Int = other match {
    +    case KafkaSourceOffset(otherOffsets) =>
    +      val allTopicAndPartitions = (this.partitionToOffsets.keySet ++ otherOffsets.keySet).toSeq
    +
    +      val comparisons = allTopicAndPartitions.map { tp =>
    +        (this.partitionToOffsets.get(tp), otherOffsets.get(tp)) match {
    +          case (Some(a), Some(b)) =>
    +            if (a < b) {
    +              -1
    +            } else if (a > b) {
    +              1
    +            } else {
    +              0
    +            }
    +          case (None, _) => -1
    +          case (_, None) => 1
    +        }
    +      }
    +      val nonZeroSigns = comparisons.filter { _ != 0 }.toSet
    +      nonZeroSigns.size match {
    +        case 0 => 0 // if both empty or only 0s
    +        case 1 => nonZeroSigns.head // if there are only (0s and 1s) or (0s and -1s)
    +        case _ => // there are both 1s and -1s
    +          throw new IllegalArgumentException(
    +            s"Invalid comparison between non-linear histories: $this <=> $other")
    +      }
    +
    +    case _ =>
    +      throw new IllegalArgumentException(s"Cannot compare $this <=> $other")
    +  }
    +
    +  override def toString(): String = {
    +    partitionToOffsets.toSeq.sortBy(_._1.toString).mkString("[", ", ", "]")
    +  }
    +}
    +
    +/** Companion object of the [[KafkaSourceOffset]] */
    +private[kafka010] object KafkaSourceOffset {
    +
    +  def getPartitionOffsets(offset: Offset): Map[TopicPartition, Long] = {
    +    offset match {
    +      case o: KafkaSourceOffset => o.partitionToOffsets
    +      case _ =>
    +        throw new IllegalArgumentException(
    +          s"Invalid conversion from offset of ${offset.getClass} to KafkaSourceOffset")
    +    }
    +  }
    +
    +  /**
    +   * Returns [[KafkaSourceOffset]] from a variable sequence of (topic, partitionId, offset)
    +   * tuples.
    +   */
    +  def apply(offsetTuples: (String, Int, Long)*): KafkaSourceOffset = {
    +    KafkaSourceOffset(offsetTuples.map { case(t, p, o) => (new TopicPartition(t, p), o) }.toMap)
    +  }
    +}
    +
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +  private val strategyOptionNames = Set("subscribe", "subscribepattern")
    +
    +  /** Class to conveniently update Kafka config params, while logging the changes */
    +  private case class ConfigUpdater(module: String, kafkaParams: Map[String, String]) {
    +    private val map = new ju.HashMap[String, Object](kafkaParams.asJava)
    +    def set(key: String, value: Object): this.type = {
    +      map.put(key, value)
    +      logInfo(s"$module: Set $key to $value, earlier value: ${kafkaParams.get(key).getOrElse("")}")
    +      this
    +    }
    +
    +    def setIfUnset(key: String, value: Object): ConfigUpdater = {
    +      if (!map.containsKey(key)) {
    +        map.put(key, value)
    +        logInfo(s"$module: Set $key to $value")
    +      }
    +      this
    +    }
    +
    +    def build(): ju.Map[String, Object] = map
    +  }
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +    validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with user-specified group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG,
    +          "spark-executor-" + specifiedKafkaParams(ConsumerConfig.GROUP_ID_CONFIG))
    +
    +        // So that consumers in executors no keep committing offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => strategyOptionNames.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy[Array[Byte], Array[Byte]](
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy[Array[Byte], Array[Byte]](
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case(k, _) => strategyOptionNames.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + strategyOptionNames.mkString(", ") + ". See docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + strategyOptionNames.mkString(", ") + ". See docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => strategyOptionNames.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    --- End diff --
    
    It's not legal to create topics with a comma, verified in code, tested with kafka 0.8 and 0.10


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79690215
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    --- End diff --
    
    DStreams != DataFrames and we are not getting rid of DStreams.  This is by design.  The proposal here is to only accept only static lists of topics and to support adding partitions.  It doesn't sound like any of that will have to change down the road, correct?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80610748
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    --- End diff --
    
    Is it ever possible for offset ranges to be stored somewhere in this design?  Because preferredLoc can get stale.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66047 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66047/consoleFull)** for PR 15102 at commit [`9d95d52`](https://github.com/apache/spark/commit/9d95d52cd1cb9ef83efaaadc5d4e9a5dc3e1c843).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66398/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81661497
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. This will ensure that no data is missed when when new
    +           |topics/partitions are dynamically subscribed. See the docs for more details.
    +         """.stripMargin)
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as keys are " +
    +          s"deserialized as byte arrays with ByteArrayDeserializer. Use Dataframe operations to " +
    +          s"explicitly deserialize the keys.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG}"))
    +    {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as value are " +
    +          s"deserialized as byte arrays with ByteArrayDeserializer. Use Dataframe operations to " +
    +          s"explicitly deserialize the values.")
    +    }
    +
    +    val otherUnsupportedConfigs = Seq(
    +      ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, // committing correctly requires new APIs in Source
    +      ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG) // interceptors can modify payload, so not safe
    +
    +    otherUnsupportedConfigs.foreach { c =>
    +      if (caseInsensitiveParams.contains(s"kafka.$c")) {
    +        throw new IllegalArgumentException(s"Kafka option '$c' is not supported")
    +      }
    +    }
    +
    +    if (!caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Option 'kafka.${ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG}' must be specified for " +
    +          s"configuring Kafka consumer")
    +    }
    +  }
    +
    +  override def shortName(): String = "kafka"
    +
    +  /** Class to conveniently update Kafka config params, while logging the changes */
    +  private case class ConfigUpdater(module: String, kafkaParams: Map[String, String]) {
    +    private val map = new ju.HashMap[String, Object](kafkaParams.asJava)
    +
    +    def set(key: String, value: Object): this.type = {
    +      map.put(key, value)
    +      logInfo(s"$module: Set $key to $value, earlier value: ${kafkaParams.get(key).getOrElse("")}")
    +      this
    +    }
    +
    +    def setIfUnset(key: String, value: Object): ConfigUpdater = {
    +      if (!map.containsKey(key)) {
    +        map.put(key, value)
    +        logInfo(s"$module: Set $key to $value")
    +      }
    +      this
    +    }
    +
    +    def build(): ju.Map[String, Object] = map
    +  }
    +}
    +
    +private[kafka010] object KafkaSourceProvider {
    +  private val STRATEGY_OPTION_KEYS = Set("subscribe", "subscribepattern")
    +  private val STARTING_OFFSET_OPTION_KEY = "startingoffset"
    +  private val STARTING_OFFSET_OPTION_VALUES = Set("earliest", "latest")
    --- End diff --
    
    > Are you going to add none here once you have Assign?
    
    Yes


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81649044
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    --- End diff --
    
    Add `require` to prevent any user specified schema. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66397/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80749159
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        logWarning(s"Partition ${range.topicPartition} was deleted and then added, " +
    +          "some data may have been missed")
    +        false
    +      } else {
    +        true
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(partitions)
    +    val partitionToOffsets = 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 offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    --- End diff --
    
    > Is this actually used anywhere? ctrl-F didn't find it in this PR
    
    Sorry. I forgot to add them back after debug. Will add them back. This is basically wrapping Kafka APIs.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65694 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65694/consoleFull)** for PR 15102 at commit [`881b206`](https://github.com/apache/spark/commit/881b20678f84b321962085a1c9dea0a7387e21c6).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79089396
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    +    def createConsumer(): Consumer[K, V]
    +  }
    +
    +  case class SubscribeStrategy[K, V](topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy[K, V](
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    +    def compare(a: ExecutorCacheTaskLocation, b: ExecutorCacheTaskLocation): Boolean = {
    +      if (a.host == b.host) { a.executorId > b.executorId } else { a.host > b.host }
    +    }
    +
    +    val bm = sc.env.blockManager
    +    bm.master.getPeers(bm.blockManagerId).toArray
    +      .map(x => ExecutorCacheTaskLocation(x.host, x.executorId))
    +      .sortWith(compare)
    +      .map(_.toString)
    +  }
    +}
    +
    +
    +/** An [[Offset]] for the [[KafkaSource]]. */
    +private[kafka010]
    +case class KafkaSourceOffset(partitionToOffsets: Map[TopicPartition, Long]) extends Offset {
    +  /**
    +   * Returns a negative integer, zero, or a positive integer as this object is less than, equal to,
    +   * or greater than the specified object.
    +   */
    +  override def compareTo(other: Offset): Int = other match {
    +    case KafkaSourceOffset(otherOffsets) =>
    +      val allTopicAndPartitions = (this.partitionToOffsets.keySet ++ otherOffsets.keySet).toSeq
    +
    +      val comparisons = allTopicAndPartitions.map { tp =>
    +        (this.partitionToOffsets.get(tp), otherOffsets.get(tp)) match {
    +          case (Some(a), Some(b)) =>
    +            if (a < b) {
    +              -1
    +            } else if (a > b) {
    +              1
    +            } else {
    +              0
    +            }
    +          case (None, _) => -1
    +          case (_, None) => 1
    +        }
    +      }
    +      val nonZeroSigns = comparisons.filter { _ != 0 }.toSet
    +      nonZeroSigns.size match {
    +        case 0 => 0 // if both empty or only 0s
    +        case 1 => nonZeroSigns.head // if there are only (0s and 1s) or (0s and -1s)
    +        case _ => // there are both 1s and -1s
    +          throw new IllegalArgumentException(
    +            s"Invalid comparison between non-linear histories: $this <=> $other")
    +      }
    +
    +    case _ =>
    +      throw new IllegalArgumentException(s"Cannot compare $this <=> $other")
    +  }
    +
    +  override def toString(): String = {
    +    partitionToOffsets.toSeq.sortBy(_._1.toString).mkString("[", ", ", "]")
    +  }
    +}
    +
    +/** Companion object of the [[KafkaSourceOffset]] */
    +private[kafka010] object KafkaSourceOffset {
    +
    +  def getPartitionOffsets(offset: Offset): Map[TopicPartition, Long] = {
    +    offset match {
    +      case o: KafkaSourceOffset => o.partitionToOffsets
    +      case _ =>
    +        throw new IllegalArgumentException(
    +          s"Invalid conversion from offset of ${offset.getClass} to KafkaSourceOffset")
    +    }
    +  }
    +
    +  /**
    +   * Returns [[KafkaSourceOffset]] from a variable sequence of (topic, partitionId, offset)
    +   * tuples.
    +   */
    +  def apply(offsetTuples: (String, Int, Long)*): KafkaSourceOffset = {
    +    KafkaSourceOffset(offsetTuples.map { case(t, p, o) => (new TopicPartition(t, p), o) }.toMap)
    +  }
    +}
    +
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +  private val strategyOptionNames = Set("subscribe", "subscribepattern")
    +
    +  /** Class to conveniently update Kafka config params, while logging the changes */
    +  private case class ConfigUpdater(module: String, kafkaParams: Map[String, String]) {
    +    private val map = new ju.HashMap[String, Object](kafkaParams.asJava)
    +    def set(key: String, value: Object): this.type = {
    +      map.put(key, value)
    +      logInfo(s"$module: Set $key to $value, earlier value: ${kafkaParams.get(key).getOrElse("")}")
    +      this
    +    }
    +
    +    def setIfUnset(key: String, value: Object): ConfigUpdater = {
    +      if (!map.containsKey(key)) {
    +        map.put(key, value)
    +        logInfo(s"$module: Set $key to $value")
    +      }
    +      this
    +    }
    +
    +    def build(): ju.Map[String, Object] = map
    +  }
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +    validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with user-specified group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG,
    +          "spark-executor-" + specifiedKafkaParams(ConsumerConfig.GROUP_ID_CONFIG))
    +
    +        // So that consumers in executors no keep committing offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => strategyOptionNames.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy[Array[Byte], Array[Byte]](
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    --- End diff --
    
    We should make sure we are correct here (in the face of topics appearing and disappearing if we are going to include this in the MVP.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66274/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66285 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66285/consoleFull)** for PR 15102 at commit [`ccadd81`](https://github.com/apache/spark/commit/ccadd81d08f56e45bbe5970656960578ee291bb5).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80567477
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    --- End diff --
    
    I'd also probably get rid of this.  I think its only useful to verify we got the data from kafka, after that we should manage possible internal corruption transparently.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #3294 has finished](https://amplab.cs.berkeley.edu/jenkins/job/NewSparkPullRequestBuilder/3294/consoleFull)** for PR 15102 at commit [`a6c4970`](https://github.com/apache/spark/commit/a6c4970ace1df46e2d65c2cc8a606f3736454d35).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66345 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66345/consoleFull)** for PR 15102 at commit [`4316906`](https://github.com/apache/spark/commit/4316906ab19556d297ded2bc38af85bb81a2e91b).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79088253
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,186 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.{KafkaException, TopicPartition}
    +
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +class CachedKafkaConsumer[K, V] private(
    --- End diff --
    
    I mentioned this in a larger comment, but we might want to consider removing these.  I think that this source should probably always pass data to execution as bytes (maybe even copying them directly in tungsten rows eventually).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65405 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65405/consoleFull)** for PR 15102 at commit [`d3c0754`](https://github.com/apache/spark/commit/d3c0754c9b5c9aa2c29b0d3ca0b28ddae041b054).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80568479
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    +    def createConsumer(): Consumer[Array[Byte], Array[Byte]]
    +  }
    +
    +  case class SubscribeStrategy(topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy(
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    --- End diff --
    
    There are other static functions in the class itself.  I'd consider moving this there and making it private rather than splitting them across two places.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    /cc @marmbrus 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81932096
  
    --- Diff: external/kafka-0-10-sql/src/test/scala/org/apache/spark/sql/kafka010/KafkaSourceSuite.scala ---
    @@ -0,0 +1,422 @@
    +/*
    + * 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.concurrent.atomic.AtomicInteger
    +
    +import scala.util.Random
    +
    +import org.apache.kafka.clients.producer.RecordMetadata
    +import org.scalatest.BeforeAndAfter
    +import org.scalatest.time.SpanSugar._
    +
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.streaming.StreamTest
    +import org.apache.spark.sql.test.SharedSQLContext
    +
    +
    +abstract class KafkaSourceTest extends StreamTest with SharedSQLContext {
    +
    +  protected var testUtils: KafkaTestUtils = _
    +
    +  override val streamingTimeout = 30.seconds
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    testUtils = new KafkaTestUtils
    +    testUtils.setup()
    +  }
    +
    +  override def afterAll(): Unit = {
    +    if (testUtils != null) {
    +      testUtils.teardown()
    +      testUtils = null
    +      super.afterAll()
    +    }
    +  }
    +
    +  protected def makeSureGetOffsetCalled = AssertOnQuery { q =>
    +    // Because KafkaSource's initialPartitionOffsets is set lazily, we need to make sure
    +    // its "getOffset" is called before pushing any data. Otherwise, because of the race contion,
    +    // we don't know which data should be fetched when `startingOffset` is latest.
    +    q.processAllAvailable()
    +    true
    +  }
    +
    +  /**
    +   * Add data to Kafka.
    +   *
    +   * `topicAction` can be used to run actions for each topic before inserting data.
    +   */
    +  case class AddKafkaData(topics: Set[String], data: Int*)
    +    (implicit ensureDataInMultiplePartition: Boolean = false,
    +      concurrent: Boolean = false,
    +      message: String = "",
    +      topicAction: (String, Option[Int]) => Unit = (_, _) => {}) extends AddData {
    +
    +    override def addData(query: Option[StreamExecution]): (Source, Offset) = {
    +      if (query.get.isActive) {
    +        // Make sure no Spark job is running when deleting a topic
    +        query.get.processAllAvailable()
    +      }
    +
    +      val existingTopics = testUtils.getAllTopicsAndPartitionSize().toMap
    +      val newTopics = topics.diff(existingTopics.keySet)
    +      for (newTopic <- newTopics) {
    +        topicAction(newTopic, None)
    +      }
    +      for (existingTopicPartitions <- existingTopics) {
    +        topicAction(existingTopicPartitions._1, Some(existingTopicPartitions._2))
    +      }
    +
    +      // Read all topics again in case some topics are delete.
    +      val allTopics = testUtils.getAllTopicsAndPartitionSize().toMap.keys
    +      require(
    +        query.nonEmpty,
    +        "Cannot add data when there is no query for finding the active kafka source")
    +
    +      val sources = query.get.logicalPlan.collect {
    +        case StreamingExecutionRelation(source, _) if source.isInstanceOf[KafkaSource] =>
    +          source.asInstanceOf[KafkaSource]
    +      }
    +      if (sources.isEmpty) {
    +        throw new Exception(
    +          "Could not find Kafka source in the StreamExecution logical plan to add data to")
    +      } else if (sources.size > 1) {
    +        throw new Exception(
    +          "Could not select the Kafka source in the StreamExecution logical plan as there" +
    +            "are multiple Kafka sources:\n\t" + sources.mkString("\n\t"))
    +      }
    +      val kafkaSource = sources.head
    +      val topic = topics.toSeq(Random.nextInt(topics.size))
    +      val sentMetadata = testUtils.sendMessages(topic, data.map { _.toString }.toArray)
    +
    +      def metadataToStr(m: (String, RecordMetadata)): String = {
    +        s"Sent ${m._1} to partition ${m._2.partition()}, offset ${m._2.offset()}"
    +      }
    +      // Verify that the test data gets inserted into multiple partitions
    +      if (ensureDataInMultiplePartition) {
    +        require(
    +          sentMetadata.groupBy(_._2.partition).size > 1,
    +          s"Added data does not test multiple partitions: ${sentMetadata.map(metadataToStr)}")
    +      }
    +
    +      val offset = KafkaSourceOffset(testUtils.getLatestOffsets(topics))
    +      logInfo(s"Added data, expected offset $offset")
    +      (kafkaSource, offset)
    +    }
    +
    +    override def toString: String =
    +      s"AddKafkaData(topics = $topics, data = $data, message = $message)"
    +  }
    +}
    +
    +
    +class KafkaSourceSuite extends KafkaSourceTest {
    +
    +  import testImplicits._
    +
    +  private val topicId = new AtomicInteger(0)
    +
    +  test("cannot stop Kafka stream") {
    +    val topic = newTopic()
    +    testUtils.createTopic(newTopic(), partitions = 5)
    +    testUtils.sendMessages(topic, (101 to 105).map { _.toString }.toArray)
    +
    +    val reader = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", testUtils.brokerAddress)
    +      .option("kafka.metadata.max.age.ms", "1")
    +      .option("subscribePattern", s"topic-.*")
    +
    +    val kafka = reader.load()
    +      .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +    val mapped = kafka.map(kv => kv._2.toInt + 1)
    +
    +    testStream(mapped)(
    +      StopStream
    +    )
    +  }
    +
    +  test("subscribing topic by name from latest offsets") {
    +    val topic = newTopic()
    +    testFromLatestOffsets(topic, "subscribe" -> topic)
    +  }
    +
    +  test("subscribing topic by name from earliest offsets") {
    +    val topic = newTopic()
    +    testFromEarliestOffsets(topic, "subscribe" -> topic)
    +  }
    +
    +  test("subscribing topic by pattern from latest offsets") {
    +    val topicPrefix = newTopic()
    +    val topic = topicPrefix + "-suffix"
    +    testFromLatestOffsets(topic, "subscribePattern" -> s"$topicPrefix-.*")
    +  }
    +
    +  test("subscribing topic by pattern from earliest offsets") {
    +    val topicPrefix = newTopic()
    +    val topic = topicPrefix + "-suffix"
    +    testFromEarliestOffsets(topic, "subscribePattern" -> s"$topicPrefix-.*")
    +  }
    +
    +  test("subscribing topic by pattern with topic deletions") {
    +    val topicPrefix = newTopic()
    +    val topic = topicPrefix + "-seems"
    +    val topic2 = topicPrefix + "-bad"
    +    testUtils.createTopic(topic, partitions = 5)
    +    testUtils.sendMessages(topic, Array("-1"))
    +    require(testUtils.getLatestOffsets(Set(topic)).size === 5)
    +
    +    val reader = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", testUtils.brokerAddress)
    +      .option("kafka.metadata.max.age.ms", "1")
    +      .option("subscribePattern", s"$topicPrefix-.*")
    +
    +    val kafka = reader.load()
    +      .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +    val mapped = kafka.map(kv => kv._2.toInt + 1)
    +
    +    testStream(mapped)(
    +      makeSureGetOffsetCalled,
    +      AddKafkaData(Set(topic), 1, 2, 3),
    +      CheckAnswer(2, 3, 4),
    +      Assert {
    +        testUtils.deleteTopic(topic)
    +        testUtils.createTopic(topic2, partitions = 5)
    +        true
    +      },
    +      AddKafkaData(Set(topic2), 4, 5, 6),
    +      CheckAnswer(2, 3, 4, 5, 6, 7)
    +    )
    +  }
    +
    +  test("bad source options") {
    +    def testBadOptions(options: (String, String)*)(expectedMsgs: String*): Unit = {
    +      val ex = intercept[IllegalArgumentException] {
    +        val reader = spark
    +          .readStream
    +          .format("kafka")
    +        options.foreach { case (k, v) => reader.option(k, v) }
    +        reader.load()
    +      }
    +      expectedMsgs.foreach { m =>
    +        assert(ex.getMessage.toLowerCase.contains(m.toLowerCase))
    +      }
    +    }
    +
    +    // No strategy specified
    +    testBadOptions()("options must be specified", "subscribe", "subscribePattern")
    +
    +    // Multiple strategies specified
    +    testBadOptions("subscribe" -> "t", "subscribePattern" -> "t.*")(
    +      "only one", "options can be specified")
    +
    +    testBadOptions("subscribe" -> "")("no topics to subscribe")
    +    testBadOptions("subscribePattern" -> "")("pattern to subscribe is empty")
    +  }
    +
    +  test("unsupported kafka configs") {
    +    def testUnsupportedConfig(key: String, value: String = "someValue"): Unit = {
    +      val ex = intercept[IllegalArgumentException] {
    +        val reader = spark
    +          .readStream
    +          .format("kafka")
    +          .option("subscribe", "topic")
    +          .option("kafka.bootstrap.servers", "somehost")
    +          .option(s"$key", value)
    +        reader.load()
    +      }
    +      assert(ex.getMessage.toLowerCase.contains("not supported"))
    +    }
    +
    +    testUnsupportedConfig("kafka.group.id")
    +    testUnsupportedConfig("kafka.auto.offset.reset")
    +    testUnsupportedConfig("kafka.enable.auto.commit")
    +    testUnsupportedConfig("kafka.interceptor.classes")
    +    testUnsupportedConfig("kafka.key.deserializer")
    +    testUnsupportedConfig("kafka.value.deserializer")
    +
    +    // only earliest and latest is supported
    --- End diff --
    
    this needs to be removed. this is outdated comment after we removed support for auto.offset.reset


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81851459
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when metadata is corrupt (e.g., topics are deleted, or offsets are 
    +  out of range), which may lost data.</td>
    +</tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>(none)</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be 
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>(none)</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern" 
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.consumer.poll.timeoutMs</td>
    +  <td>long</td>
    +  <td>512</td>
    +  <td>The timeout in milliseconds to poll data from Kafka in executors.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.numRetries</td>
    +  <td>int</td>
    +  <td>3</td>
    +  <td>Number of times to retry before giving up fatch Kafka latest offsets.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.retry.intervalMs</td>
    --- End diff --
    
    why another retry scope? Why not `fetchOffset.retryIntervalMs`? 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80568553
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    --- End diff --
    
    Should we error if they specify a schema, rather than just ignore it?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Absent a direct answer, I'm going to read that as "Yes I've made up my mind, no I will not consider PRs to the contrary."
    
    If you want pointers to what I think the correct implementation would look like, I'd say look at the existing DStream and my prototype structured streaming fork.  With the main difference that, as I said above, I don't think the current sql Offset interface makes sense if all you need is to measure equality | not equal | error.
    
    My main concern is making sure end users can do their jobs using Kafka.  If your main concern is a higher level abstraction that may or may not actually work well with Kafka, I wish you luck in that endeavor, but I don't think it makes sense for me to spend any more time arguing with you about it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65845 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65845/consoleFull)** for PR 15102 at commit [`5f33eb4`](https://github.com/apache/spark/commit/5f33eb4692e4b95812e70f43d838cb47bd57698b).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79088325
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    --- End diff --
    
    nit: this sentance cuts off.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > I pushed for this code to be copied rather than refactored because I think this is the right direction long term. While it is nice to minimize inter-project dependencies, that is not really the motivation. While the code is very similar now, there a bunch of things I'd like to start changing:
    
    A bigger concern for me at this point is that the code was copied, and then modified in ways that don't seem to have anything to do with the necessities of structured streaming (e.g. your "why is this a nested class" comment).
    
    Options from my point of view, from best to worst
    
    1. Refactor to a common submodule.  Based on how little I had to change to get the common functionality in my branch, I think this is going to initially leave most things untouched.  If things change in the future, they can be refactored / copied as necessary.  I think this minimizes the chance that someone fixes a bug in Dstream cached consumer, and forgets to fix in sql cached consumer, or vice versa.
    
    2. Copy without changes, make only minimal changes necessary at first.  This is going to make what happened more obvious, and make it easier to maintain changes across both pieces of code
    
    3.  Copy and make unnecessary changes (what seems to have been done currently).  This seems like a maintenance nightmare for no gain.
    
    
    > 
    > I don't think that all the classes need to be type parameterized. Our interface SQL has its own type system, analyser, and interface to the type system of the JVM (encoders). We should be using that. Operators in SQL do not type parameterize in general.
    > To optimize performance, there are several tricks we might want to play eventually (maybe prefetching data during execution, etc).
    
    Kafka consumers prefetch data already, that's the main reason the CachedKafkaConsumer exists.  My thought here is that there isn't much gain to be had with something more than a thin shim around a Kafka rdd, or at least not for a while.  Kafka's data model doesn't really allow for much in terms of pushdown optimizations (you basically get to query by offset, or maybe time).  About the only idea I've heard that might have promise was Reynold suggesting scheduling straight map jobs as long-running kafka consumers in a poll loop on the executors, to avoid batching latency.  But that seems to open a whole can of worms in terms of deterministic behavior, and is probably much further down the road.  If we get there, what's the harm in cutting shared dependencies at that point rather than now?
    
    > These are just ideas, but given that DStreams and Structured Streaming have significantly different models and user interfaces, I don't think that we want to tie ourselves to the same internals. If we identify utilities that are needed by both, then we should pull those out and share them.
    
    At this point, the shared need is basically everything except KafkaUtils' static constructors, and the parts of the DirectStream related to the DStream interface.  You still need an rdd, a cache for consumers, offset ranges, a way to configure consumers, a way to configure locality, a consumer running on the driver to get latest offsets...
    
    > We don't need to handle the general problem of is kafka Offset A from Topic 1 before or after kafka Offset B from Topic 2. 
    > 
    > Does x: KafkaOffset == y: KafkaOffset (i.e. is there new data since the last time I checked)?
    
    We do need to handle it comparing completely different topicpartitions, because it's entirely possible to have a job with a single topicpartition A, which is deleted or unsubscribed, and then single topicpartition B is added, in the space of one batch.  I have talked to companies that are actually doing this kind of thing.  If all we need to do is be able to tell that one sql offset (that we already knew about) is different from another sql offset (that we just learned about), then I think it's pretty straightforward - your three cases are
    
    * error.  ahead in some common topicpartitions, and behind in others.
    * equal.  same kafka offsets for same topicpartitions
    * not equal.  different offsets for same topicpartitions, and/or different topicpartitions
    
    That does imply that any ordering of sql Offsets is by when we learn about them in processing time, which sounds suspect, but...
    
    > The final version of this Source should almost certainly support wildcards with topicpartitions that change on the fly. Since it seems this is one of the harder problems to solve, as a strawman, I'd propose that we only support static lists of topics in this PR and possibly even static partitions. I want to get users to kick the tires on structured streaming in general and report whats missing so we can all prioritize our engineering effort.
    
    The problem I see with that approach is that doing it right may require changing the structured streaming interface, which gets progressively harder to do the more users and more implementations there are relying on it.  I think it's generally best to learn about your items of highest risk first (even if you don't totally solve them in version 1.0).
    
    > I typically open PRs against the PR author's branch when I want to collaborate more directly.
    
    Sorry, I meant this less in terms of github mechanics and more in terms of process - are you going to consider pull requests against this branch, what pieces make sense to split off, etc.  For a specific initial question, is your mind made up about the submodule thing, or if I do that refactor will you at least look at it?
    
    > df.withColumn("value", $"value".cast("string"))
    > I'd also like to create expressions that work well with kafka specific deserializers, as well as integrations with our json parsing and maybe Avro too. The nice thing about this path is it fits with other SQL APIs and should play nicely with Dataset Encoders, UDFs, our expression library, etc.
    > 
    > Does that seem reasonable? Is this missing important cases?
    
    Yeah, that seems reasonable.  Yeah, the builtin types, json, and maybe avro are the ones to hit.  I'd be 100% on board if we had one working example of a specific deserializer, that didn't require access to private spark classes, so people could tell how to do it for whatever serialization scheme they are using.
    
    My guess is someone's going to want an implicit api to let them just call .stringKeyValue or whatever on the dataframe because all they care about is those two columns, but that's really straightforward for people to do themselves.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66288/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81933327
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,239 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +The following options should be set for the Kafka source.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>meaning</th></tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern"
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.bootstrap.servers</td>
    +  <td>A comma-separated list of host:port</td>
    +  <td>The Kafka "bootstrap.servers" configuration.</td>
    +</tr>
    +</table>
    +
    +The rest configurations are optional:
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnDataLoss</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when it's possible that data is lost (e.g., topics are deleted, or 
    +  offsets are out of range). This may be a false alarm. You can disable it when it doesn't work
    +  as you expected.</td>
    +</tr>
    +<tr>
    +  <td>kafkaConsumer.pollTimeoutMs</td>
    +  <td>long</td>
    +  <td>512</td>
    +  <td>The timeout in milliseconds to poll data from Kafka in executors.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.numRetries</td>
    +  <td>int</td>
    +  <td>3</td>
    +  <td>Number of times to retry before giving up fatch Kafka latest offsets.</td>
    +</tr>
    +<tr>
    +  <td>fetchOffset.retryIntervalMs</td>
    +  <td>long</td>
    +  <td>10</td>
    +  <td>milliseconds to wait before retrying to fetch Kafka offsets</td>
    +</tr>
    +</table>
    +
    +Kafka's own configurations can be set via `DataStreamReader.option` with `kafka.` prefix, e.g, 
    +`stream.option("kafka.bootstrap.servers", "host:port")`. For possible kafkaParams, see 
    +[Kafka consumer config docs](http://kafka.apache.org/documentation.html#newconsumerconfigs).
    +
    +Note that the following Kafka params cannot be set and the Kafka source will throw an exception:
    +- **group.id**: Kafka source will create a unique group id for each query automatically.
    +- **auto.offset.reset**: Set the source option `startingOffset` to `earliest` or `latest` to specify
    + where to start instead. Structured Streaming manages which offsets are consumed internally, rather 
    + than rely on the kafka Consumer to do it. This will ensure that no data is missed when when new 
    + topics/partitions are dynamically subscribed. Note that `startingOffset` only applies when a new
    + Streaming query is started, and that resuming will always pick up from where the query left off.
    +- **key.deserializer**: Keys are always deserialized as byte arrays with ByteArrayDeserializer. Use 
    + Dataframe operations to explicitly deserialize the keys.
    --- End diff --
    
    nit: Dataframe -> DataFrame
    multiple places have this issue


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81835883
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,282 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    require(schema.isEmpty, "Kafka source has a fixed schema and cannot be set with a custom one")
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    // Each running query should use its own group id. Otherwise, the query may be only assigned
    +    // partial data since Kafka will assign partitions to multiple consumers having the same group
    +    // id. Hence, we should generate a unique id for each query.
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // Make sure executors do only what the driver tells them.
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    val failOnCorruptMetadata =
    +      caseInsensitiveParams.getOrElse(FAIL_ON_CORRUPT_METADATA_OPTION_KEY, "true").toBoolean
    +
    +    new KafkaSource(
    +      sqlContext,
    +      strategy,
    +      kafkaParamsForExecutors,
    +      parameters,
    +      metadataPath,
    +      failOnCorruptMetadata)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. Structured Streaming manages which offsets are consumed
    +           |internally, rather than rely on the kafka Consumer to do it. This will ensure that no
    --- End diff --
    
    nit: "relying"


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81878432
  
    --- Diff: docs/structured-streaming-programming-guide.md ---
    @@ -1126,6 +1126,12 @@ aggDF \
     </div>
     </div>
     
    +## Advanced Sources
    --- End diff --
    
    Cool.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81851557
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when metadata is corrupt (e.g., topics are deleted, or offsets are 
    +  out of range), which may lost data.</td>
    +</tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>(none)</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be 
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>(none)</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern" 
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.consumer.poll.timeoutMs</td>
    +  <td>long</td>
    --- End diff --
    
    nit: can keep this is `int`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81623277
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,185 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +
    +    // Subscribe to multiple topics
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +
    +    // Subscribe to a pattern
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +
    +    // Subscribe to multiple topics
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +
    +    // Subscribe to a pattern
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +
    +    # Subscribe to multiple topics
    +    spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +
    +    # Subscribe to a pattern
    +    spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    --- End diff --
    
    This should probably include an example of how to select key / value in the desired format.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80599360
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    --- End diff --
    
    This also, gives good source description by toString() on the consumer strategy. Would need to have another if statement in source.toString.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > For streaming you already know what the global order is, because you know when you asked for A and B. I agree that we should probably remove the comparable requirement from Offset in favor of just having equality.
    
    Sounds good, as long as the execution portion of it isn't e.g. storing timestamps for A and running into issues on driver failover to a machine with clock drift.
    
    
    > Assuming A was retrieved before B, then it seems like you emit a warning that data was possibly missed from A (since it was deleted before we could get it) and you start a new batch on topic B from offsets 0-1. Right?
    
    I think in the absence of prior information about the position in a topicpartition, you start a new batch on topic B starting from wherever the consumer's position was at the time it acquired the subscription, which might not be 0.  I.e. you call position() before seekToEnd().  This might mean you need to record 2 kafka offsets in an SQL Offset if it's the first time you've seen that topicpartition.
    
    > Are there arguments that we do support that you think are confusing?
    
    I think the main thing that would be confusing is to specify topics in one way (custom-delimited string) for one configuration, and in another way (structured json) for another configuration.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81836478
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StreamExecution.scala ---
    @@ -530,3 +530,8 @@ object StreamExecution {
     
       def nextId: Long = _nextId.getAndIncrement()
     }
    +
    +/**
    + * A special thread to run the stream query.
    --- End diff --
    
    You might comment that we actually check for this class elsewhere.  This part is not super clear to me.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66396 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66396/consoleFull)** for PR 15102 at commit [`d9d848c`](https://github.com/apache/spark/commit/d9d848ca455d659e39ceadf8c2b8d50867b85962).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66396 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66396/consoleFull)** for PR 15102 at commit [`d9d848c`](https://github.com/apache/spark/commit/d9d848ca455d659e39ceadf8c2b8d50867b85962).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65640 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65640/consoleFull)** for PR 15102 at commit [`b64d104`](https://github.com/apache/spark/commit/b64d1046a13ce3b03b2598f13dd2d1aeb1219048).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81930482
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    --- End diff --
    
    nit:
    - Lazily initialize initialPartitionOffsets to make sure that `KafkaConsumer.poll` is only called in StreamExecutionThread.
    - interrupting a thread *while* running


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    
    > It would be nice to be able to do something other than earliest/latest.
    
    That's what Assign and the starting offset arguments to the Subscribe strategies are for.  The implementation was already there.
    
    > When specifying earliest, you end up with really big partitions. 
    
    Again, spark.streaming.kafka.maxRatePerPartition and the associated implementation was already there.  If you don't want the coupling to time, it's pretty straightforward.  The bigger question is when / if / how you're going to do backpressure.
    
    >  One question, is it a problem if two tasks are pulling from the same topic partition in parallel? Does this break the assumptions of our caching?
    
    This breaks fundamental assumptions of Kafka (per-topicpartition ordering) and really shouldn't be done.
    
    > I can do a final pass over the code, but do we think we are getting close to something that we can merge and iterate on?
    
    I think we're in much better shape than when we started, but I still honestly think this implementation made a bunch of user-visible behavioral and configuration changes from the DStream that really have nothing to do with the inherent differences between it and structured streaming.  This isn't just me whining about "you changed my code",  it really is going to make it harder to explain to people and harder to maintain.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66265 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66265/consoleFull)** for PR 15102 at commit [`e883062`](https://github.com/apache/spark/commit/e88306267e372101a685492afcfa652408a83109).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80612809
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    +    def createConsumer(): Consumer[Array[Byte], Array[Byte]]
    +  }
    +
    +  case class SubscribeStrategy(topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy(
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy {
    +    override def createConsumer(): Consumer[Array[Byte], Array[Byte]] = {
    +      val consumer = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    +    def compare(a: ExecutorCacheTaskLocation, b: ExecutorCacheTaskLocation): Boolean = {
    +      if (a.host == b.host) { a.executorId > b.executorId } else { a.host > b.host }
    +    }
    +
    +    val bm = sc.env.blockManager
    +    bm.master.getPeers(bm.blockManagerId).toArray
    +      .map(x => ExecutorCacheTaskLocation(x.host, x.executorId))
    +      .sortWith(compare)
    +      .map(_.toString)
    +  }
    +}
    +
    +
    +/** An [[Offset]] for the [[KafkaSource]]. */
    +private[kafka010]
    +case class KafkaSourceOffset(partitionToOffsets: Map[TopicPartition, Long]) extends Offset {
    --- End diff --
    
    Nit regarding naming -  this is a map of a partition to an offset, not a partition to multiple offsets, at least until we put in 2 starting offsets for newly discovered partitions.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80611465
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        logWarning(s"Partition ${range.topicPartition} was deleted and then added, " +
    +          "some data may have been missed")
    +        false
    +      } else {
    +        true
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    --- End diff --
    
    So this poll, itself, may result in new partitions being assigned, yes?  And those partitions will not be paused, nor included in the return value?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65636 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65636/consoleFull)** for PR 15102 at commit [`f5c57f5`](https://github.com/apache/spark/commit/f5c57f51f675002298c833edb486451642735221).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80563435
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    --- End diff --
    
    Document what this consumer is used for.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66283/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66398 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66398/consoleFull)** for PR 15102 at commit [`4754125`](https://github.com/apache/spark/commit/4754125d041ebdf2286bb015770d58351779622d).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66345/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65926/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80610210
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    --- End diff --
    
    I'm lost on what the point of sorting topic partitions is, if you're still just using topicpartition hashcode as an index into the executors.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80568269
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    --- End diff --
    
    I know users should be data independent, but I'd consider reordering these because right now it looks kind of random.
     - topic
     - partition
     - offset
     - timestamp / type
     - key
     - value


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80606631
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -149,6 +160,14 @@ private[kafka010] case class KafkaSource(
             Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
           } else None
           KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        logWarning(s"Partition ${range.topicPartition} was deleted and then added, " +
    --- End diff --
    
    I'd change this to error level and specify what the offsets in question were.  I also wouldn't assume that a partition was deleted and then added, this could be caused by other things.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65937 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65937/consoleFull)** for PR 15102 at commit [`852f607`](https://github.com/apache/spark/commit/852f607a4253af67d2b425527fa0b87ad20aa953).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66345 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66345/consoleFull)** for PR 15102 at commit [`4316906`](https://github.com/apache/spark/commit/4316906ab19556d297ded2bc38af85bb81a2e91b).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80609718
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    --- End diff --
    
    Is logging at a warning level sufficient to inform a user that a guarantee has been violated, if that guarantee is sufficiently important that it should prevent them from being able to directly configure auto.offset.reset?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80607976
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    +    kafkaParams: ju.Map[String, Object]) extends Logging {
    +
    +  private val consumer = {
    +    val c = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +    val tps = new ju.ArrayList[TopicPartition]()
    +    tps.add(topicPartition)
    +    c.assign(tps)
    +    c
    +  }
    +
    +  /**
    +   * Timeout for polls to the consumer. Since the data should be already available, the poll
    +   * should get the data immediately, and the timeout value should not matter as long as it is
    +   * generous and does not cause timeout when there are not issues.
    +   */
    +  private val pollTimeoutMs = 60 * 1000
    +
    +  /** Iterator to the already fetch data */
    +  private var fetchedData = ju.Collections.emptyIterator[ConsumerRecord[Array[Byte], Array[Byte]]]
    +  private var nextOffsetInFetchedData = -2L
    +
    +  /**
    +   * Get the record for the given offset, waiting up to timeout ms if IO is necessary.
    +   * Sequential forward access will use buffers, but random access will be horribly inefficient.
    +   */
    +  def get(offset: Long): ConsumerRecord[Array[Byte], Array[Byte]] = {
    +    logDebug(s"Get $topicPartition nextOffset $nextOffsetInFetchedData requested $offset")
    +    if (offset != nextOffsetInFetchedData) {
    +      logInfo(s"Initial fetch for $topicPartition $offset")
    +      seek(offset)
    +      poll()
    +    }
    +
    +    if (!fetchedData.hasNext()) { poll() }
    +    assert(fetchedData.hasNext(),
    +      s"Failed to get records for $topicPartition $offset after polling for $pollTimeoutMs")
    +    var record = fetchedData.next()
    +
    +    if (record.offset != offset) {
    +      logInfo(s"Buffer miss for $topicPartition $offset")
    +      seek(offset)
    +      poll()
    +      assert(fetchedData.hasNext(),
    +        s"Failed to get records for $topicPartition $offset after polling for $pollTimeoutMs")
    +      record = fetchedData.next()
    +      assert(record.offset == offset,
    +        s"Got wrong record for $topicPartition even after seeking to offset $offset")
    +    }
    +
    +    nextOffsetInFetchedData = offset + 1
    +    record
    +  }
    +
    +  private def close(): Unit = consumer.close()
    +
    +  private def seek(offset: Long): Unit = {
    +    logDebug(s"Seeking to $topicPartition $offset")
    +    consumer.seek(topicPartition, offset)
    +  }
    +
    +  private def poll(): Unit = {
    +    val p = consumer.poll(pollTimeoutMs)
    --- End diff --
    
    Ok, I see what's going on here now.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81933155
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,239 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +The following options should be set for the Kafka source.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>meaning</th></tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern"
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.bootstrap.servers</td>
    +  <td>A comma-separated list of host:port</td>
    +  <td>The Kafka "bootstrap.servers" configuration.</td>
    +</tr>
    +</table>
    +
    +The rest configurations are optional:
    --- End diff --
    
    nit: the following configurations ...


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Right now since there are some arguments about how to handle various failures, I'm listing what I found via stress test to discuss:
    
    (1) Kafka APIs fail because we cannot connect to Kafka cluster. Solution: fail the query.
    
    (2) `getOffset` fails temporarily because some of topics are deleted at the same time. `consumer.position` will throw NPE due to this race condition. Solution: retry (This is why `withRetries` is added)
    
    ```
    consumer.poll(0)
    val partitions = consumer.assignment()
    consumer.position(p) 
    ```
    
    (3) In `getBatch`, some partitions are new because they are not in `fromOffsets`. Then we will call `fetchNewPartitionEarliestOffsets` to fetch these partitions. However, some of these new partitions may be deleted due to topic deletion, then they won't appear in `consumer.assignment()`. Solution: log a warning.
    
    (4) In `getBatch`, some partitions are new because they are not in `fromOffsets`. Then we will call `fetchNewPartitionEarliestOffsets` to fetch these partitions. Similiar to (2), `consumer.position` may throw NPE due to this race condition. Solution : retry.
    
    (5) Topics are deleted when a Spark job is runinng, which may cause `OffsetOutOfRangeException`. (I'm not sure if there are more types of exceptions, may need to investigate) Solution: log a warning.
    
    (6) A topic is deleted then added. This may make untilOffset is less than fromOffset. Solution: log a warning.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66005 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66005/consoleFull)** for PR 15102 at commit [`59a93a5`](https://github.com/apache/spark/commit/59a93a561235d4bb0db04b3be6c0325e695df7e2).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `case class KafkaSourceOffset(partitionToOffsets: Map[TopicPartition, Long]) extends Offset `
      * `abstract class StreamExecutionThread(name: String) extends UninterruptibleThread(name)`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80613358
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. This will ensure that no data is missed when when new
    +           |topics/partitions are dynamically subscribed. See the docs for more details.
    +         """.stripMargin)
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as keys are " +
    +          s"deserialized as byte arrays with ByteArrayDeserializer. Use Dataframe operations to " +
    +          s"explicitly deserialize the keys.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG}"))
    +    {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as value are " +
    +          s"deserialized as byte arrays with ByteArrayDeserializer. Use Dataframe operations to " +
    +          s"explicitly deserialize the values.")
    +    }
    +
    +    val otherUnsupportedConfigs = Seq(
    +      ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, // committing correctly requires new APIs in Source
    +      ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG) // interceptors can modify payload, so not safe
    +
    +    otherUnsupportedConfigs.foreach { c =>
    +      if (caseInsensitiveParams.contains(s"kafka.$c")) {
    +        throw new IllegalArgumentException(s"Kafka option '$c' is not supported")
    +      }
    +    }
    +
    +    if (!caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Option 'kafka.${ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG}' must be specified for " +
    +          s"configuring Kafka consumer")
    +    }
    +  }
    +
    +  override def shortName(): String = "kafka"
    +
    +  /** Class to conveniently update Kafka config params, while logging the changes */
    +  private case class ConfigUpdater(module: String, kafkaParams: Map[String, String]) {
    +    private val map = new ju.HashMap[String, Object](kafkaParams.asJava)
    +
    +    def set(key: String, value: Object): this.type = {
    +      map.put(key, value)
    +      logInfo(s"$module: Set $key to $value, earlier value: ${kafkaParams.get(key).getOrElse("")}")
    +      this
    +    }
    +
    +    def setIfUnset(key: String, value: Object): ConfigUpdater = {
    +      if (!map.containsKey(key)) {
    +        map.put(key, value)
    +        logInfo(s"$module: Set $key to $value")
    +      }
    +      this
    +    }
    +
    +    def build(): ju.Map[String, Object] = map
    +  }
    +}
    +
    +private[kafka010] object KafkaSourceProvider {
    +  private val STRATEGY_OPTION_KEYS = Set("subscribe", "subscribepattern")
    +  private val STARTING_OFFSET_OPTION_KEY = "startingoffset"
    +  private val STARTING_OFFSET_OPTION_VALUES = Set("earliest", "latest")
    --- End diff --
    
    Are you going to add none here once you have Assign?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79089641
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    --- End diff --
    
    Why are theses all inner classes?  Also, do we need these interfaces?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81833814
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    --- End diff --
    
    I would consider dropping all of these implementation details from the docs.  I think its possible we will change them.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65845 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65845/consoleFull)** for PR 15102 at commit [`5f33eb4`](https://github.com/apache/spark/commit/5f33eb4692e4b95812e70f43d838cb47bd57698b).
     * This patch **fails to build**.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `class SparkContext(config: SparkConf) extends Logging `
      * `class ChiSqSelector @Since(\"2.1.0\") () extends Serializable `
      * `case class ShowColumnsCommand(tableName: TableIdentifier) extends RunnableCommand `
      * `abstract class CompactibleFileStreamLog[T: ClassTag](`
      * `class FileStreamSinkLog(`
      * `  case class FileEntry(path: String, timestamp: Timestamp, batchId: Long) extends Serializable`
      * `class FileStreamSourceLog(`
      * `trait Offset extends Serializable `


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80563543
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    --- End diff --
    
    Still cuts off.  I'd consider removing this abstraction completely.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65685 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65685/consoleFull)** for PR 15102 at commit [`6bc2994`](https://github.com/apache/spark/commit/6bc2994f98567127137aee54a5141d98337986c5).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `  sealed trait ConsumerStrategy `
      * `  case class SubscribeStrategy(topics: Seq[String], kafkaParams: ju.Map[String, Object])`
      * `  case class SubscribePatternStrategy(`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66338 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66338/consoleFull)** for PR 15102 at commit [`d50a05e`](https://github.com/apache/spark/commit/d50a05eb703acb841b85b04e2b52e958778e6ab1).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81875588
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,282 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    require(schema.isEmpty, "Kafka source has a fixed schema and cannot be set with a custom one")
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    // Each running query should use its own group id. Otherwise, the query may be only assigned
    +    // partial data since Kafka will assign partitions to multiple consumers having the same group
    +    // id. Hence, we should generate a unique id for each query.
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // Make sure executors do only what the driver tells them.
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessarily
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    val failOnDataLoss =
    +      caseInsensitiveParams.getOrElse(FAIL_ON_DATA_LOSS_OPTION_KEY, "true").toBoolean
    +
    +    new KafkaSource(
    +      sqlContext,
    +      strategy,
    +      kafkaParamsForExecutors,
    +      parameters,
    +      metadataPath,
    +      failOnDataLoss)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. Structured Streaming manages which offsets are consumed
    +           |internally, rather than relying on the kafka Consumer to do it. This will ensure that no
    --- End diff --
    
    nit: kafka Consumer --> KafkaConsumer


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030620
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    +  private lazy val initialPartitionOffsets = {
    +    val metadataLog = new HDFSMetadataLog[KafkaSourceOffset](sqlContext.sparkSession, metadataPath)
    +    metadataLog.get(0).getOrElse {
    +      val offsets = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = false))
    +      metadataLog.add(0, offsets)
    +      logInfo(s"Initial offsets: $offsets")
    +      offsets
    +    }.partitionToOffsets
    +  }
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    // Make sure initialPartitionOffsets is set
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81661642
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    --- End diff --
    
    Fixed the comment


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80615307
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // So that the driver does not pull too much data
    +        .set(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, new java.lang.Integer(1))
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("executor", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-executor")
    +
    +        // So that consumers in executors does not commit offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, set it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy(
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy(
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +
    +    // Validate source options
    +
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case (k, _) => STRATEGY_OPTION_KEYS.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + STRATEGY_OPTION_KEYS.mkString(", ") + ". See the docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => STRATEGY_OPTION_KEYS.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    +        if (topics.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "No topics to subscribe to as specified value for option " +
    +              s"'subscribe' is '$value'")
    +        }
    +      case ("subscribepattern", value) =>
    +        val pattern = caseInsensitiveParams("subscribepattern").trim()
    +        if (pattern.isEmpty) {
    +          throw new IllegalArgumentException(
    +            "Pattern to subscribe is empty as specified value for option " +
    +              s"'subscribePattern' is '$value'")
    +        }
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(pos) if !STARTING_OFFSET_OPTION_VALUES.contains(pos.trim.toLowerCase) =>
    +        throw new IllegalArgumentException(
    +          s"Illegal value '$pos' for option '$STARTING_OFFSET_OPTION_KEY', " +
    +            s"acceptable values are: ${STARTING_OFFSET_OPTION_VALUES.mkString(", ")}")
    +      case _ =>
    +    }
    +
    +    // Validate user-specified Kafka options
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.GROUP_ID_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"Kafka option '${ConsumerConfig.GROUP_ID_CONFIG}' is not supported as " +
    +          s"user-specified consumer groups is not used to track offsets.")
    +    }
    +
    +    if (caseInsensitiveParams.contains(s"kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}")) {
    +      throw new IllegalArgumentException(
    +        s"""
    +           |Kafka option '${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}' is not supported.
    +           |Instead set the source option '$STARTING_OFFSET_OPTION_KEY' to 'earliest' or 'latest' to
    +           |specify where to start. This will ensure that no data is missed when when new
    +           |topics/partitions are dynamically subscribed. See the docs for more details.
    --- End diff --
    
    You can't promise no data is missed.  In fact, limiting it to earliest or latest pretty much ensures that data can be missed without the stream failing, because the consumer will automatically reset when it can't get retention.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81661667
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    --- End diff --
    
    > Still cuts off. I'd consider removing this abstraction completely.
    
    Fixed the format


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66289/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81861936
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    --- End diff --
    
    Rename to `failOnDataLoss`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80563033
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy {
    --- End diff --
    
    I would consider getting rid of this.  There is only one place in the code where we we call this function, why not just inline the logic there?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80563908
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    +
    +    val autoOffsetResetValue = caseInsensitiveParams.get(STARTING_OFFSET_OPTION_KEY) match {
    +      case Some(value) => value.trim()  // same values as those supported by auto.offset.reset
    +      case None => "latest"
    +    }
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in Kafka source do not mess with any existing group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG, s"$uniqueGroupId-driver")
    +
    +        // So that consumers can start from earliest or latest
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetResetValue)
    +
    +        // So that consumers in the driver does not commit offsets unnecessaribly
    --- End diff --
    
    nit: spelling 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80564169
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    --- End diff --
    
    Also, do these get cleaned up?  or are we leaking state into ZK?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81861960
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    --- End diff --
    
    > I would split this into two tables, one that must be specified (subscribe/subscribePattern, and kafka.bootstrap...) and then optional params.
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030575
  
    --- Diff: external/kafka-0-10-sql/src/test/scala/org/apache/spark/sql/kafka010/KafkaSourceSuite.scala ---
    @@ -0,0 +1,422 @@
    +/*
    + * 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.concurrent.atomic.AtomicInteger
    +
    +import scala.util.Random
    +
    +import org.apache.kafka.clients.producer.RecordMetadata
    +import org.scalatest.BeforeAndAfter
    +import org.scalatest.time.SpanSugar._
    +
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.streaming.StreamTest
    +import org.apache.spark.sql.test.SharedSQLContext
    +
    +
    +abstract class KafkaSourceTest extends StreamTest with SharedSQLContext {
    +
    +  protected var testUtils: KafkaTestUtils = _
    +
    +  override val streamingTimeout = 30.seconds
    +
    +  override def beforeAll(): Unit = {
    +    super.beforeAll()
    +    testUtils = new KafkaTestUtils
    +    testUtils.setup()
    +  }
    +
    +  override def afterAll(): Unit = {
    +    if (testUtils != null) {
    +      testUtils.teardown()
    +      testUtils = null
    +      super.afterAll()
    +    }
    +  }
    +
    +  protected def makeSureGetOffsetCalled = AssertOnQuery { q =>
    +    // Because KafkaSource's initialPartitionOffsets is set lazily, we need to make sure
    +    // its "getOffset" is called before pushing any data. Otherwise, because of the race contion,
    +    // we don't know which data should be fetched when `startingOffset` is latest.
    +    q.processAllAvailable()
    +    true
    +  }
    +
    +  /**
    +   * Add data to Kafka.
    +   *
    +   * `topicAction` can be used to run actions for each topic before inserting data.
    +   */
    +  case class AddKafkaData(topics: Set[String], data: Int*)
    +    (implicit ensureDataInMultiplePartition: Boolean = false,
    +      concurrent: Boolean = false,
    +      message: String = "",
    +      topicAction: (String, Option[Int]) => Unit = (_, _) => {}) extends AddData {
    +
    +    override def addData(query: Option[StreamExecution]): (Source, Offset) = {
    +      if (query.get.isActive) {
    +        // Make sure no Spark job is running when deleting a topic
    +        query.get.processAllAvailable()
    +      }
    +
    +      val existingTopics = testUtils.getAllTopicsAndPartitionSize().toMap
    +      val newTopics = topics.diff(existingTopics.keySet)
    +      for (newTopic <- newTopics) {
    +        topicAction(newTopic, None)
    +      }
    +      for (existingTopicPartitions <- existingTopics) {
    +        topicAction(existingTopicPartitions._1, Some(existingTopicPartitions._2))
    +      }
    +
    +      // Read all topics again in case some topics are delete.
    +      val allTopics = testUtils.getAllTopicsAndPartitionSize().toMap.keys
    +      require(
    +        query.nonEmpty,
    +        "Cannot add data when there is no query for finding the active kafka source")
    +
    +      val sources = query.get.logicalPlan.collect {
    +        case StreamingExecutionRelation(source, _) if source.isInstanceOf[KafkaSource] =>
    +          source.asInstanceOf[KafkaSource]
    +      }
    +      if (sources.isEmpty) {
    +        throw new Exception(
    +          "Could not find Kafka source in the StreamExecution logical plan to add data to")
    +      } else if (sources.size > 1) {
    +        throw new Exception(
    +          "Could not select the Kafka source in the StreamExecution logical plan as there" +
    +            "are multiple Kafka sources:\n\t" + sources.mkString("\n\t"))
    +      }
    +      val kafkaSource = sources.head
    +      val topic = topics.toSeq(Random.nextInt(topics.size))
    +      val sentMetadata = testUtils.sendMessages(topic, data.map { _.toString }.toArray)
    +
    +      def metadataToStr(m: (String, RecordMetadata)): String = {
    +        s"Sent ${m._1} to partition ${m._2.partition()}, offset ${m._2.offset()}"
    +      }
    +      // Verify that the test data gets inserted into multiple partitions
    +      if (ensureDataInMultiplePartition) {
    +        require(
    +          sentMetadata.groupBy(_._2.partition).size > 1,
    +          s"Added data does not test multiple partitions: ${sentMetadata.map(metadataToStr)}")
    +      }
    +
    +      val offset = KafkaSourceOffset(testUtils.getLatestOffsets(topics))
    +      logInfo(s"Added data, expected offset $offset")
    +      (kafkaSource, offset)
    +    }
    +
    +    override def toString: String =
    +      s"AddKafkaData(topics = $topics, data = $data, message = $message)"
    +  }
    +}
    +
    +
    +class KafkaSourceSuite extends KafkaSourceTest {
    +
    +  import testImplicits._
    +
    +  private val topicId = new AtomicInteger(0)
    +
    +  test("cannot stop Kafka stream") {
    +    val topic = newTopic()
    +    testUtils.createTopic(newTopic(), partitions = 5)
    +    testUtils.sendMessages(topic, (101 to 105).map { _.toString }.toArray)
    +
    +    val reader = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", testUtils.brokerAddress)
    +      .option("kafka.metadata.max.age.ms", "1")
    +      .option("subscribePattern", s"topic-.*")
    +
    +    val kafka = reader.load()
    +      .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +    val mapped = kafka.map(kv => kv._2.toInt + 1)
    +
    +    testStream(mapped)(
    +      StopStream
    +    )
    +  }
    +
    +  test("subscribing topic by name from latest offsets") {
    +    val topic = newTopic()
    +    testFromLatestOffsets(topic, "subscribe" -> topic)
    +  }
    +
    +  test("subscribing topic by name from earliest offsets") {
    +    val topic = newTopic()
    +    testFromEarliestOffsets(topic, "subscribe" -> topic)
    +  }
    +
    +  test("subscribing topic by pattern from latest offsets") {
    +    val topicPrefix = newTopic()
    +    val topic = topicPrefix + "-suffix"
    +    testFromLatestOffsets(topic, "subscribePattern" -> s"$topicPrefix-.*")
    +  }
    +
    +  test("subscribing topic by pattern from earliest offsets") {
    +    val topicPrefix = newTopic()
    +    val topic = topicPrefix + "-suffix"
    +    testFromEarliestOffsets(topic, "subscribePattern" -> s"$topicPrefix-.*")
    +  }
    +
    +  test("subscribing topic by pattern with topic deletions") {
    +    val topicPrefix = newTopic()
    +    val topic = topicPrefix + "-seems"
    +    val topic2 = topicPrefix + "-bad"
    +    testUtils.createTopic(topic, partitions = 5)
    +    testUtils.sendMessages(topic, Array("-1"))
    +    require(testUtils.getLatestOffsets(Set(topic)).size === 5)
    +
    +    val reader = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", testUtils.brokerAddress)
    +      .option("kafka.metadata.max.age.ms", "1")
    +      .option("subscribePattern", s"$topicPrefix-.*")
    +
    +    val kafka = reader.load()
    +      .selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +    val mapped = kafka.map(kv => kv._2.toInt + 1)
    +
    +    testStream(mapped)(
    +      makeSureGetOffsetCalled,
    +      AddKafkaData(Set(topic), 1, 2, 3),
    +      CheckAnswer(2, 3, 4),
    +      Assert {
    +        testUtils.deleteTopic(topic)
    +        testUtils.createTopic(topic2, partitions = 5)
    +        true
    +      },
    +      AddKafkaData(Set(topic2), 4, 5, 6),
    +      CheckAnswer(2, 3, 4, 5, 6, 7)
    +    )
    +  }
    +
    +  test("bad source options") {
    +    def testBadOptions(options: (String, String)*)(expectedMsgs: String*): Unit = {
    +      val ex = intercept[IllegalArgumentException] {
    +        val reader = spark
    +          .readStream
    +          .format("kafka")
    +        options.foreach { case (k, v) => reader.option(k, v) }
    +        reader.load()
    +      }
    +      expectedMsgs.foreach { m =>
    +        assert(ex.getMessage.toLowerCase.contains(m.toLowerCase))
    +      }
    +    }
    +
    +    // No strategy specified
    +    testBadOptions()("options must be specified", "subscribe", "subscribePattern")
    +
    +    // Multiple strategies specified
    +    testBadOptions("subscribe" -> "t", "subscribePattern" -> "t.*")(
    +      "only one", "options can be specified")
    +
    +    testBadOptions("subscribe" -> "")("no topics to subscribe")
    +    testBadOptions("subscribePattern" -> "")("pattern to subscribe is empty")
    +  }
    +
    +  test("unsupported kafka configs") {
    +    def testUnsupportedConfig(key: String, value: String = "someValue"): Unit = {
    +      val ex = intercept[IllegalArgumentException] {
    +        val reader = spark
    +          .readStream
    +          .format("kafka")
    +          .option("subscribe", "topic")
    +          .option("kafka.bootstrap.servers", "somehost")
    +          .option(s"$key", value)
    +        reader.load()
    +      }
    +      assert(ex.getMessage.toLowerCase.contains("not supported"))
    +    }
    +
    +    testUnsupportedConfig("kafka.group.id")
    +    testUnsupportedConfig("kafka.auto.offset.reset")
    +    testUnsupportedConfig("kafka.enable.auto.commit")
    +    testUnsupportedConfig("kafka.interceptor.classes")
    +    testUnsupportedConfig("kafka.key.deserializer")
    +    testUnsupportedConfig("kafka.value.deserializer")
    +
    +    // only earliest and latest is supported
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79088749
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    --- End diff --
    
    This should be `RDD[InternalRow]` otherwise we are copying and doing a lot of extra conversion.  It doesn't have to be this PR, but we might just want to do this right since I think I'll have a significant impact on performance.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > Either way, who are you to presume that a user doesn't know what she is
    doing when she configured a consumer to start at a particular position for
    an added partition?
    
    I feel like we are talking past each other.  We are not giving the developer the option to manually configure a consumer in this way for this PR precisely because I don't think we can while still maintaining the semantics that structured streaming has promised.  This is consciously a higher level API than is provided by DStreams.  Neither of these is right or wrong. I do want to be able to support as many real use cases as possible in the Structured Streaming API, but not at the expense of correctness for the queries that we support. If there are low level use cases that we can't support, which require users to use DStreams instead, that is okay, as it is okay that some users still program against RDDs.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81862040
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    +  <td>[true, false]</td>
    +  <td>true</td>
    +  <td>Whether to fail the query when metadata is corrupt (e.g., topics are deleted, or offsets are 
    +  out of range), which may lost data.</td>
    +</tr>
    +<tr>
    +  <td>subscribe</td>
    +  <td>A comma-separated list of topics</td>
    +  <td>(none)</td>
    +  <td>The topic list to subscribe. Only one of "subscribe" and "subscribePattern" options can be 
    +  specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>subscribePattern</td>
    +  <td>Java regex string</td>
    +  <td>(none)</td>
    +  <td>The pattern used to subscribe the topic. Only one of "subscribe" and "subscribePattern" 
    +  options can be specified for Kafka source.</td>
    +</tr>
    +<tr>
    +  <td>kafka.consumer.poll.timeoutMs</td>
    --- End diff --
    
    > this is not a spark specific one. this can be in the must-be-specified table.
    
    This is actually not a Kafka config. This is only used in KafkaSource


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030626
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    > PR with failing test indicating at least one reason why it's wrong from an end-user perspective:
    
    @koeninger Thanks for writing the test. Yes, we are aware of this issue. However, it's unlikely that we can support deleting topics using the current Source API. You can take a look at how StreamExecution checks the new data here: https://github.com/apache/spark/blob/976f3b1227c1a9e0b878e010531285fdba57b6a7/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/StreamExecution.scala#L320 
    
    Using the hash code to compare offsets has a potential issue, it may make the latest offset be smaller than the old offset, then StreamExecution won't process the new data.
    
    I think one possible solution is StreamExecution doesn't compare the offsets, instead, it just assumes `getOffset` will always return the latest offset, and it never rollback to an old offset. This needs more discussion anyway. Hence I suggest we don't block this PR for this. Deleting topics can be supported in a later PR when we make an agreement on how to resolve the issue.



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65636/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80610562
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,366 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      logWarning(s"Partitions removed: ${deletedPartitions}, some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.filter { tp =>
    +      newPartitionOffsets.contains(tp) || fromPartitionOffsets.contains(tp)
    +    }.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.filter { range =>
    +      if (range.untilOffset < range.fromOffset) {
    +        logWarning(s"Partition ${range.topicPartition} was deleted and then added, " +
    +          "some data may have been missed")
    +        false
    +      } else {
    +        true
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(partitions)
    +    val partitionToOffsets = 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 offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Throwable = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case NonFatal(e) =>
    +          lastException = e
    +          e.printStackTrace()
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    --- End diff --
    
    Why the name change from floorMod used in the Direct Stream and in java 8 math?  This isn't guaranteed to return a positive number.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81840127
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    --- End diff --
    
    Hmmm, can you enumerate the cases where setting this to true could cause the query to fail.  I understand:
     - falling so far behind that data gets aged out.
     - deleting a topic before the stream is able to catch up.
    
    What else?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81844299
  
    --- Diff: docs/structured-streaming-kafka-integration.md ---
    @@ -0,0 +1,231 @@
    +---
    +layout: global
    +title: Structured Streaming + Kafka Integration Guide (Kafka broker version 0.10.0 or higher)
    +---
    +
    +Structured Streaming integration for Kafka 0.10 to poll data from Kafka. It provides simple parallelism,
    +1:1 correspondence between Kafka partitions and Spark partitions. The source will cache the Kafka
    +consumer in executors and try the best to schedule the same Kafka topic partition to the same executor.
    +
    +### Linking
    +For Scala/Java applications using SBT/Maven project definitions, link your application with the following artifact:
    +
    +    groupId = org.apache.spark
    +    artifactId = spark-sql-kafka-0-10_{{site.SCALA_BINARY_VERSION}}
    +    version = {{site.SPARK_VERSION_SHORT}}
    +
    +For Python applications, you need to add this above library and its dependencies when deploying your
    +application. See the [Deploying](#deploying) subsection below.
    +
    +### Creating a Kafka Source Stream
    +
    +<div class="codetabs">
    +<div data-lang="scala" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    val ds1 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to multiple topics
    +    val ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +    // Subscribe to a pattern
    +    val ds3 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +      .as[(String, String)]
    +
    +</div>
    +<div data-lang="java" markdown="1">
    +
    +    // Subscribe to 1 topic
    +    Dataset<Row> ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to multiple topics
    +    Dataset<Row> ds2 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    // Subscribe to a pattern
    +    Dataset<Row> ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +<div data-lang="python" markdown="1">
    +
    +    # Subscribe to 1 topic
    +    ds1 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1")
    +      .load()
    +    ds1.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to multiple topics
    +    ds2 = spark
    +      .readStream
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribe", "topic1,topic2")
    +      .load()
    +    ds2.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +    # Subscribe to a pattern
    +    ds3 = spark
    +      .readStream()
    +      .format("kafka")
    +      .option("kafka.bootstrap.servers", "host1:port1,host2:port2")
    +      .option("subscribePattern", "topic.*")
    +      .load()
    +    ds3.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
    +
    +</div>
    +</div>
    +
    +Each row in the source has the following schema:
    +<table class="table">
    +<tr><th>Column</th><th>Type</th></tr>
    +<tr>
    +  <td>key</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>value</td>
    +  <td>binary</td>
    +</tr>
    +<tr>
    +  <td>topic</td>
    +  <td>string</td>
    +</tr>
    +<tr>
    +  <td>partition</td>
    +  <td>int</td>
    +</tr>
    +<tr>
    +  <td>offset</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestamp</td>
    +  <td>long</td>
    +</tr>
    +<tr>
    +  <td>timestampType</td>
    +  <td>int</td>
    +</tr>
    +</table>
    +
    +Right now, the Kafka source has the following Spark's specific options.
    +
    +<table class="table">
    +<tr><th>Option</th><th>value</th><th>default</th><th>meaning</th></tr>
    +<tr>
    +  <td>startingOffset</td>
    +  <td>["earliest", "latest"]</td>
    +  <td>"latest"</td>
    +  <td>The start point when a query is started, either "earliest" which is from the earliest offset, 
    +  or "latest" which is just from the latest offset. Note: This only applies when a new Streaming q
    +  uery is started, and that resuming will always pick up from where the query left off.</td>
    +</tr>
    +<tr>
    +  <td>failOnCorruptMetadata</td>
    --- End diff --
    
    These all sound like possible data loss (or missing data) to me.  We could clarify in the description that its only possible.  "Corrupt" sounds like its there but inconsistent, a checksum is failing, or something like that.  If others disagree though, this is minor.  We should just be super clear about the conditions in the description.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65401 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65401/consoleFull)** for PR 15102 at commit [`c4db857`](https://github.com/apache/spark/commit/c4db857d745e8814892c9ef8076d8752f6cb4e19).
     * This patch **fails MiMa tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80607795
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    +    kafkaParams: ju.Map[String, Object]) extends Logging {
    +
    +  private val consumer = {
    +    val c = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +    val tps = new ju.ArrayList[TopicPartition]()
    +    tps.add(topicPartition)
    +    c.assign(tps)
    +    c
    +  }
    +
    +  /**
    +   * Timeout for polls to the consumer. Since the data should be already available, the poll
    +   * should get the data immediately, and the timeout value should not matter as long as it is
    +   * generous and does not cause timeout when there are not issues.
    +   */
    +  private val pollTimeoutMs = 60 * 1000
    +
    +  /** Iterator to the already fetch data */
    +  private var fetchedData = ju.Collections.emptyIterator[ConsumerRecord[Array[Byte], Array[Byte]]]
    +  private var nextOffsetInFetchedData = -2L
    +
    +  /**
    +   * Get the record for the given offset, waiting up to timeout ms if IO is necessary.
    +   * Sequential forward access will use buffers, but random access will be horribly inefficient.
    +   */
    +  def get(offset: Long): ConsumerRecord[Array[Byte], Array[Byte]] = {
    +    logDebug(s"Get $topicPartition nextOffset $nextOffsetInFetchedData requested $offset")
    +    if (offset != nextOffsetInFetchedData) {
    +      logInfo(s"Initial fetch for $topicPartition $offset")
    +      seek(offset)
    +      poll()
    +    }
    +
    +    if (!fetchedData.hasNext()) { poll() }
    --- End diff --
    
    pollTimeoutMs was defined above, but isn't used here


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by koeninger <gi...@git.apache.org>.
Github user koeninger commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80607882
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/CachedKafkaConsumer.scala ---
    @@ -0,0 +1,155 @@
    +/*
    + * 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 org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord, KafkaConsumer}
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.{SparkEnv, SparkException, TaskContext}
    +import org.apache.spark.internal.Logging
    +
    +
    +/**
    + * Consumer of single topicpartition, intended for cached reuse.
    + * Underlying consumer is not threadsafe, so neither is this,
    + * but processing the same topicpartition and group id in multiple threads is usually bad anyway.
    + */
    +private[kafka010] case class CachedKafkaConsumer private(
    +    topicPartition: TopicPartition,
    +    kafkaParams: ju.Map[String, Object]) extends Logging {
    +
    +  private val consumer = {
    +    val c = new KafkaConsumer[Array[Byte], Array[Byte]](kafkaParams)
    +    val tps = new ju.ArrayList[TopicPartition]()
    +    tps.add(topicPartition)
    +    c.assign(tps)
    +    c
    +  }
    +
    +  /**
    +   * Timeout for polls to the consumer. Since the data should be already available, the poll
    +   * should get the data immediately, and the timeout value should not matter as long as it is
    +   * generous and does not cause timeout when there are not issues.
    +   */
    +  private val pollTimeoutMs = 60 * 1000
    +
    +  /** Iterator to the already fetch data */
    +  private var fetchedData = ju.Collections.emptyIterator[ConsumerRecord[Array[Byte], Array[Byte]]]
    +  private var nextOffsetInFetchedData = -2L
    +
    +  /**
    +   * Get the record for the given offset, waiting up to timeout ms if IO is necessary.
    +   * Sequential forward access will use buffers, but random access will be horribly inefficient.
    +   */
    +  def get(offset: Long): ConsumerRecord[Array[Byte], Array[Byte]] = {
    +    logDebug(s"Get $topicPartition nextOffset $nextOffsetInFetchedData requested $offset")
    +    if (offset != nextOffsetInFetchedData) {
    +      logInfo(s"Initial fetch for $topicPartition $offset")
    +      seek(offset)
    +      poll()
    +    }
    +
    +    if (!fetchedData.hasNext()) { poll() }
    +    assert(fetchedData.hasNext(),
    +      s"Failed to get records for $topicPartition $offset after polling for $pollTimeoutMs")
    +    var record = fetchedData.next()
    +
    +    if (record.offset != offset) {
    +      logInfo(s"Buffer miss for $topicPartition $offset")
    +      seek(offset)
    +      poll()
    --- End diff --
    
    Nor is the timeout used here


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80564114
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSourceProvider.scala ---
    @@ -0,0 +1,263 @@
    +/*
    + * 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.UUID
    +
    +import scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.ConsumerConfig
    +import org.apache.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.SQLContext
    +import org.apache.spark.sql.execution.streaming.Source
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types.StructType
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +    with DataSourceRegister with Logging {
    +  import KafkaSourceProvider._
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +      validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +    val uniqueGroupId = s"spark-kafka-source-${UUID.randomUUID}-${metadataPath.hashCode}"
    --- End diff --
    
    Comment why we are picking something random.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81873392
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafka.consumer.poll.timeoutMs", "512").toLong
    --- End diff --
    
    What is this option named as "kafka.consumer.poll.timeoutMs". This makes it look like that it is a kafka param. Which it is not. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65405/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r82030607
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,396 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +import scala.util.control.NonFatal
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.UninterruptibleThread
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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
    + *   [[KafkaSource]] to query for the offsets. See the docs on
    + *   [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + *
    + * Zero data lost is not guaranteed when topics are deleted. If zero data lost is critical, the user
    + * must make sure all messages in a topic have been processed when deleting a topic.
    + *
    + * There is a known issue caused by KAFKA-1894: the query using KafkaSource maybe cannot be stopped.
    + * To avoid this issue, you should make sure stopping the query before stopping the Kafka brokers
    + * and not use wrong broker addresses.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String],
    +    metadataPath: String,
    +    failOnDataLoss: Boolean)
    +  extends Source with Logging {
    +
    +  private val sc = sqlContext.sparkContext
    +
    +  private val pollTimeoutMs = sourceOptions.getOrElse("kafkaConsumer.pollTimeoutMs", "512").toLong
    +
    +  private val maxOffsetFetchAttempts =
    +    sourceOptions.getOrElse("fetchOffset.numRetries", "3").toInt
    +
    +  private val offsetFetchAttemptIntervalMs =
    +    sourceOptions.getOrElse("fetchOffset.retryIntervalMs", "10").toLong
    +
    +  /**
    +   * A KafkaConsumer used in the driver to query the latest Kafka offsets. This only queries the
    +   * offsets and never commits them.
    +   */
    +  private val consumer = consumerStrategy.createConsumer()
    +
    +  /**
    +   * Lazy set initialPartitionOffsets to make sure only call `KafkaConsumer.poll` in
    +   * StreamExecutionThread. Otherwise, interrupting a thread running `KafkaConsumer.poll` may hang
    +   * forever (KAFKA-1894).
    +   */
    +  private lazy val initialPartitionOffsets = {
    +    val metadataLog = new HDFSMetadataLog[KafkaSourceOffset](sqlContext.sparkSession, metadataPath)
    +    metadataLog.get(0).getOrElse {
    +      val offsets = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = false))
    +      metadataLog.add(0, offsets)
    +      logInfo(s"Initial offsets: $offsets")
    +      offsets
    +    }.partitionToOffsets
    +  }
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToEnd = true))
    +    logDebug(s"GetOffset: ${offset.partitionToOffsets.toSeq.map(_.toString).sorted}")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets
    +   * [`start.get.partitionToOffsets`, `end.partitionToOffsets`), i.e. end.partitionToOffsets is
    +   * exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    // Make sure initialPartitionOffsets is set
    +    initialPartitionOffsets
    +
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    if (newPartitionOffsets.keySet != newPartitions) {
    +      // We cannot get from offsets for some partitions. It means they got deleted.
    +      val deletedPartitions = newPartitions.diff(newPartitionOffsets.keySet)
    +      reportDataLoss(
    +        s"Cannot find earliest offsets of ${deletedPartitions}. Some data may have been missed")
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      reportDataLoss(
    +        s"Added partition $p starts from $o instead of 0. Some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"$deletedPartitions are gone. Some data may have been missed")
    --- End diff --
    
    done


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66265/
    Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #66283 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66283/consoleFull)** for PR 15102 at commit [`77208d1`](https://github.com/apache/spark/commit/77208d1611810f5c6afb5ba63911cadb1794c863).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65785/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r81861641
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamTest.scala ---
    @@ -469,29 +469,49 @@ trait StreamTest extends QueryTest with SharedSQLContext with Timeouts {
         }
       }
     
    +
    +  /**
    +   * Creates a stress test that randomly starts/stops/adds data/checks the result.
    +   *
    +   * @param ds a dataframe that executes + 1 on a stream of integers, returning the result
    +   * @param addData an add data action that adds the given numbers to the stream, encoding them
    +   *                as needed
    +   * @param iterations the iteration number
    +   */
    +  def runStressTest(
    +    ds: Dataset[Int],
    +    addData: Seq[Int] => StreamAction,
    +    iterations: Int = 100): Unit = {
    +    runStressTest(ds, Seq.empty, (data, running) => addData(data), iterations)
    +  }
    +
       /**
        * Creates a stress test that randomly starts/stops/adds data/checks the result.
        *
    -   * @param ds a dataframe that executes + 1 on a stream of integers, returning the result.
    -   * @param addData and add data action that adds the given numbers to the stream, encoding them
    +   * @param ds a dataframe that executes + 1 on a stream of integers, returning the result
    +   * @param preparedActions actions need to run before starting the stress test.
    --- End diff --
    
    > nit: its kind of odd for this to be past tense.
    
    fixed


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66287/
    Test FAILed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    @koeninger Thanks a lot for looking at this PR.
    
    - The duplicated codes are mostly because we don't want to depend on Spark DStream in structured streaming source. Anyway, we can create a common project for these codes if that's really a big deal.
    - This PR doesn't support topicpartitions changes for now. I'm not sure how to implement he strict ordering for Kafka offsets when topicpartitions changes on the fly. The strict ordering is important to StreamingExecution otherwise it may skip some data. Do you have any thoughts? I looked your PR but seems you have not yet resolved this problem?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    FYI: #15274 adds support for parsing JSON from the key/value into a Spark SQL `StructType`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65937 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65937/consoleFull)** for PR 15102 at commit [`852f607`](https://github.com/apache/spark/commit/852f607a4253af67d2b425527fa0b87ad20aa953).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by jwbear <gi...@git.apache.org>.
Github user jwbear commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Just curious looking at this, if you are comparing "sequential" offsets across partitions a rebalance would definitely affect this and, unless something has changed, it probably not a good idea to compare offsets from kafka across partitions. You could simply add an id/timestamp to the producer and send it with the message rather than using this methodology or if you must use offset query the broker for the full list and compare what you consumed to that list (small increase in latency btwn consumption and processing).  This is from the Kafka paper, which makes me question your scheme: "...Note that our message ids are increasing but not consecutive. To compute the id of the next message, we have to add the length of the current message to its id." This means simply comparing which offsets are larger will not necessarily yield you the most recent message across partitions and definitely won't hold in a rebalance during which time some broker logs will be on hold and not consumed.
  In my own implementation, the offsets are great for message guarantees (eg delivery/consumption checks), because the broker has a full ordered list, but not for cross partition ordering. 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    **[Test build #65694 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65694/consoleFull)** for PR 15102 at commit [`881b206`](https://github.com/apache/spark/commit/881b20678f84b321962085a1c9dea0a7387e21c6).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #15102: [SPARK-17346][SQL] Add Kafka source for Structured Strea...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15102
  
    Merged build finished. Test PASSed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by marmbrus <gi...@git.apache.org>.
Github user marmbrus commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r79089110
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,446 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +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.kafka.common.serialization.ByteArrayDeserializer
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.SparkContext
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *   returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy[Array[Byte], Array[Byte]],
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  @transient private val consumer = consumerStrategy.createConsumer()
    +  @transient private val sc = sqlContext.sparkContext
    +  @transient private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: " + initialPartitionOffsets)
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /**
    +   * Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive.
    +   */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logDebug(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.size
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +    val offsetRanges = sortedTopicPartitions.flatMap { tp =>
    +      fromPartitionOffsets.get(tp).map { fromOffset =>
    +        val untilOffset = untilPartitionOffsets(tp)
    +        val preferredLoc = if (numExecutors > 0) {
    +          Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +        } else None
    +        KafkaSourceRDD.OffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +      }
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD[Array[Byte], Array[Byte]](
    +      sc, executorKafkaParams, offsetRanges, sourceOptions).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch: " + offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  private def fetchPartitionOffsets(seekToLatest: Boolean): Map[TopicPartition, Long] = {
    +    synchronized {
    +      logTrace("\tPolling")
    +      consumer.poll(0)
    +      val partitions = consumer.assignment()
    +      consumer.pause(partitions)
    +      logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +      if (seekToLatest) {
    +        consumer.seekToEnd(partitions)
    +        logDebug("\tSeeked to the end")
    +      }
    +      logTrace("Getting positions")
    +      val partitionToOffsets = partitions.asScala.map(p => p -> consumer.position(p))
    +      logDebug(s"Got positions $partitionToOffsets")
    +      partitionToOffsets.toMap
    +    }
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    +    StructField("checksum", LongType),
    +    StructField("key", BinaryType),
    +    StructField("offset", LongType),
    +    StructField("partition", IntegerType),
    +    StructField("serializedKeySize", IntegerType),
    +    StructField("serializedValueSize", IntegerType),
    +    StructField("timestamp", LongType),
    +    StructField("timestampType", IntegerType),
    +    StructField("topic", StringType),
    +    StructField("value", BinaryType)
    +  ))
    +
    +  sealed trait ConsumerStrategy[K, V] {
    +    def createConsumer(): Consumer[K, V]
    +  }
    +
    +  case class SubscribeStrategy[K, V](topics: Seq[String], kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(topics.asJava)
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"Subscribe[${topics.mkString(", ")}]"
    +  }
    +
    +  case class SubscribePatternStrategy[K, V](
    +    topicPattern: String, kafkaParams: ju.Map[String, Object])
    +    extends ConsumerStrategy[K, V] {
    +    override def createConsumer(): Consumer[K, V] = {
    +      val consumer = new KafkaConsumer[K, V](kafkaParams)
    +      consumer.subscribe(
    +        ju.regex.Pattern.compile(topicPattern),
    +        new NoOpConsumerRebalanceListener())
    +      consumer.poll(0)
    +      consumer
    +    }
    +
    +    override def toString: String = s"SubscribePattern[$topicPattern]"
    +  }
    +
    +  def getSortedExecutorList(sc: SparkContext): Array[String] = {
    +    def compare(a: ExecutorCacheTaskLocation, b: ExecutorCacheTaskLocation): Boolean = {
    +      if (a.host == b.host) { a.executorId > b.executorId } else { a.host > b.host }
    +    }
    +
    +    val bm = sc.env.blockManager
    +    bm.master.getPeers(bm.blockManagerId).toArray
    +      .map(x => ExecutorCacheTaskLocation(x.host, x.executorId))
    +      .sortWith(compare)
    +      .map(_.toString)
    +  }
    +}
    +
    +
    +/** An [[Offset]] for the [[KafkaSource]]. */
    +private[kafka010]
    +case class KafkaSourceOffset(partitionToOffsets: Map[TopicPartition, Long]) extends Offset {
    +  /**
    +   * Returns a negative integer, zero, or a positive integer as this object is less than, equal to,
    +   * or greater than the specified object.
    +   */
    +  override def compareTo(other: Offset): Int = other match {
    +    case KafkaSourceOffset(otherOffsets) =>
    +      val allTopicAndPartitions = (this.partitionToOffsets.keySet ++ otherOffsets.keySet).toSeq
    +
    +      val comparisons = allTopicAndPartitions.map { tp =>
    +        (this.partitionToOffsets.get(tp), otherOffsets.get(tp)) match {
    +          case (Some(a), Some(b)) =>
    +            if (a < b) {
    +              -1
    +            } else if (a > b) {
    +              1
    +            } else {
    +              0
    +            }
    +          case (None, _) => -1
    +          case (_, None) => 1
    +        }
    +      }
    +      val nonZeroSigns = comparisons.filter { _ != 0 }.toSet
    +      nonZeroSigns.size match {
    +        case 0 => 0 // if both empty or only 0s
    +        case 1 => nonZeroSigns.head // if there are only (0s and 1s) or (0s and -1s)
    +        case _ => // there are both 1s and -1s
    +          throw new IllegalArgumentException(
    +            s"Invalid comparison between non-linear histories: $this <=> $other")
    +      }
    +
    +    case _ =>
    +      throw new IllegalArgumentException(s"Cannot compare $this <=> $other")
    +  }
    +
    +  override def toString(): String = {
    +    partitionToOffsets.toSeq.sortBy(_._1.toString).mkString("[", ", ", "]")
    +  }
    +}
    +
    +/** Companion object of the [[KafkaSourceOffset]] */
    +private[kafka010] object KafkaSourceOffset {
    +
    +  def getPartitionOffsets(offset: Offset): Map[TopicPartition, Long] = {
    +    offset match {
    +      case o: KafkaSourceOffset => o.partitionToOffsets
    +      case _ =>
    +        throw new IllegalArgumentException(
    +          s"Invalid conversion from offset of ${offset.getClass} to KafkaSourceOffset")
    +    }
    +  }
    +
    +  /**
    +   * Returns [[KafkaSourceOffset]] from a variable sequence of (topic, partitionId, offset)
    +   * tuples.
    +   */
    +  def apply(offsetTuples: (String, Int, Long)*): KafkaSourceOffset = {
    +    KafkaSourceOffset(offsetTuples.map { case(t, p, o) => (new TopicPartition(t, p), o) }.toMap)
    +  }
    +}
    +
    +
    +/**
    + * The provider class for the [[KafkaSource]]. This provider is designed such that it throws
    + * IllegalArgumentException when the Kafka Dataset is created, so that it can catch
    + * missing options even before the query is started.
    + */
    +private[kafka010] class KafkaSourceProvider extends StreamSourceProvider
    +  with DataSourceRegister with Logging {
    +  private val strategyOptionNames = Set("subscribe", "subscribepattern")
    +
    +  /** Class to conveniently update Kafka config params, while logging the changes */
    +  private case class ConfigUpdater(module: String, kafkaParams: Map[String, String]) {
    +    private val map = new ju.HashMap[String, Object](kafkaParams.asJava)
    +    def set(key: String, value: Object): this.type = {
    +      map.put(key, value)
    +      logInfo(s"$module: Set $key to $value, earlier value: ${kafkaParams.get(key).getOrElse("")}")
    +      this
    +    }
    +
    +    def setIfUnset(key: String, value: Object): ConfigUpdater = {
    +      if (!map.containsKey(key)) {
    +        map.put(key, value)
    +        logInfo(s"$module: Set $key to $value")
    +      }
    +      this
    +    }
    +
    +    def build(): ju.Map[String, Object] = map
    +  }
    +
    +  /**
    +   * Returns the name and schema of the source. In addition, it also verifies whether the options
    +   * are correct and sufficient to create the [[KafkaSource]] when the query is started.
    +   */
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) = {
    +    validateOptions(parameters)
    +    ("kafka", KafkaSource.kafkaSchema)
    +  }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +    validateOptions(parameters)
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedKafkaParams =
    +      parameters
    +        .keySet
    +        .filter(_.toLowerCase.startsWith("kafka."))
    +        .map { k => k.drop(6).toString -> parameters(k) }
    +        .toMap
    +
    +    val deserClassName = classOf[ByteArrayDeserializer].getName
    +
    +    val kafkaParamsForStrategy =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .build()
    +
    +    val kafkaParamsForExecutors =
    +      ConfigUpdater("source", specifiedKafkaParams)
    +        .set(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +        .set(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, deserClassName)
    +
    +        // So that consumers in executors never throw NoOffsetForPartitionException
    +        .set(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none")
    +
    +        // So that consumers in executors do not mess with user-specified group id
    +        .set(ConsumerConfig.GROUP_ID_CONFIG,
    +          "spark-executor-" + specifiedKafkaParams(ConsumerConfig.GROUP_ID_CONFIG))
    +
    +        // So that consumers in executors no keep committing offsets unnecessaribly
    +        .set(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
    +
    +        // If buffer config is not set, it to reasonable value to work around
    +        // buffer issues (see KAFKA-3135)
    +        .setIfUnset(ConsumerConfig.RECEIVE_BUFFER_CONFIG, 65536: java.lang.Integer)
    +        .build()
    +
    +    val strategy = caseInsensitiveParams.find(x => strategyOptionNames.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        SubscribeStrategy[Array[Byte], Array[Byte]](
    +          value.split(",").map(_.trim()).filter(_.nonEmpty),
    +          kafkaParamsForStrategy)
    +      case ("subscribepattern", value) =>
    +        SubscribePatternStrategy[Array[Byte], Array[Byte]](
    +          value.trim(),
    +          kafkaParamsForStrategy)
    +      case _ =>
    +        // Should never reach here as we are already matching on
    +        // matched strategy names
    +        throw new IllegalArgumentException("Unknown option")
    +    }
    +
    +    new KafkaSource(sqlContext, strategy, kafkaParamsForExecutors, parameters)
    +  }
    +
    +  private def validateOptions(parameters: Map[String, String]): Unit = {
    +    val caseInsensitiveParams = parameters.map { case (k, v) => (k.toLowerCase, v) }
    +    val specifiedStrategies =
    +      caseInsensitiveParams.filter { case(k, _) => strategyOptionNames.contains(k) }.toSeq
    +    if (specifiedStrategies.isEmpty) {
    +      throw new IllegalArgumentException(
    +        "One of the following options must be specified for Kafka source: "
    +          + strategyOptionNames.mkString(", ") + ". See docs for more details.")
    +    } else if (specifiedStrategies.size > 1) {
    +      throw new IllegalArgumentException(
    +        "Only one of the following options can be specified for Kafka source: "
    +          + strategyOptionNames.mkString(", ") + ". See docs for more details.")
    +    }
    +
    +    val strategy = caseInsensitiveParams.find(x => strategyOptionNames.contains(x._1)).get match {
    +      case ("subscribe", value) =>
    +        val topics = value.split(",").map(_.trim).filter(_.nonEmpty)
    --- End diff --
    
    I think the answer is "no", but can topics have `,`s in them?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #15102: [SPARK-17346][SQL] Add Kafka source for Structure...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15102#discussion_r80599004
  
    --- Diff: external/kafka-0-10-sql/src/main/scala/org/apache/spark/sql/kafka010/KafkaSource.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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 scala.collection.JavaConverters._
    +
    +import org.apache.kafka.clients.consumer.{Consumer, KafkaConsumer}
    +import org.apache.kafka.clients.consumer.internals.NoOpConsumerRebalanceListener
    +import org.apache.kafka.common.TopicPartition
    +
    +import org.apache.spark.SparkContext
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.scheduler.ExecutorCacheTaskLocation
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.kafka010.KafkaSource._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * A [[Source]] that uses Kafka's own [[KafkaConsumer]] API to reads data from Kafka. The design
    + * for this source is as follows.
    + *
    + * - The [[KafkaSourceOffset]] is the custom [[Offset]] defined for this source that contains
    + *   a map of TopicPartition -> offset. Note that this offset is 1 + (available offset). For
    + *   example if the last record in a Kafka topic "t", partition 2 is offset 5, then
    + *   KafkaSourceOffset will contain TopicPartition("t", 2) -> 6. This is done keep it consistent
    + *   with the semantics of `KafkaConsumer.position()`.
    + *
    + * - 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 [[KafkaSource]] to query for the offsets.
    + *   See the docs on [[org.apache.spark.sql.kafka010.KafkaSource.ConsumerStrategy]] for
    + *   more details.
    + *
    + * - The [[KafkaSource]] written to do the following.
    + *
    + *  - As soon as the source is created, the pre-configured KafkaConsumer returned by the
    + *    [[ConsumerStrategy]] is used to query the initial offsets that this source should
    + *    start reading from. This used to create the first batch.
    + *
    + *   - `getOffset()` uses the KafkaConsumer to query the latest available offsets, which are
    + *     returned as a [[KafkaSourceOffset]].
    + *
    + *   - `getBatch()` returns a DF that reads from the 'start offset' until the 'end offset' in
    + *     for each partition. The end offset is excluded to be consistent with the semantics of
    + *     [[KafkaSourceOffset]] and `KafkaConsumer.position()`.
    + *
    + *   - The DF returned is based on [[KafkaSourceRDD]] which is constructed such that the
    + *     data from Kafka topic + partition is consistently read by the same executors across
    + *     batches, and cached KafkaConsumers in the executors can be reused efficiently. See the
    + *     docs on [[KafkaSourceRDD]] for more details.
    + */
    +private[kafka010] case class KafkaSource(
    +    sqlContext: SQLContext,
    +    consumerStrategy: ConsumerStrategy,
    +    executorKafkaParams: ju.Map[String, Object],
    +    sourceOptions: Map[String, String])
    +  extends Source with Logging {
    +
    +  private val consumer = consumerStrategy.createConsumer()
    +  private val sc = sqlContext.sparkContext
    +  private val initialPartitionOffsets = fetchPartitionOffsets(seekToLatest = false)
    +  logInfo(s"Initial offsets: $initialPartitionOffsets")
    +
    +  override def schema: StructType = KafkaSource.kafkaSchema
    +
    +  /** Returns the maximum available offset for this source. */
    +  override def getOffset: Option[Offset] = {
    +    val offset = KafkaSourceOffset(fetchPartitionOffsets(seekToLatest = true))
    +    logInfo(s"GetOffset: $offset")
    +    Some(offset)
    +  }
    +
    +  /** Returns the data that is between the offsets [`start`, `end`), i.e. end is exclusive. */
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    logInfo(s"GetBatch called with start = $start, end = $end")
    +    val untilPartitionOffsets = KafkaSourceOffset.getPartitionOffsets(end)
    +    val fromPartitionOffsets = start match {
    +      case Some(prevBatchEndOffset) =>
    +        KafkaSourceOffset.getPartitionOffsets(prevBatchEndOffset)
    +      case None =>
    +        initialPartitionOffsets
    +    }
    +
    +    // Find the new partitions, and get their earliest offsets
    +    val newPartitions = untilPartitionOffsets.keySet.diff(fromPartitionOffsets.keySet)
    +    val newPartitionOffsets = if (newPartitions.nonEmpty) {
    +      fetchNewPartitionEarliestOffsets(newPartitions.toSeq)
    +    } else {
    +      Map.empty[TopicPartition, Long]
    +    }
    +    logInfo(s"Partitions added: $newPartitionOffsets")
    +    newPartitionOffsets.filter(_._2 != 0).foreach { case (p, o) =>
    +      logWarning(s"Added partition $p starts from $o instead of 0, some data may have been missed")
    +    }
    +
    +    val deletedPartitions = fromPartitionOffsets.keySet.diff(untilPartitionOffsets.keySet)
    +    logWarning(s"Partitions removed: $deletedPartitions, some data may have been missed")
    +
    +    // Sort the partitions and current list of executors to consistently assign each partition
    +    // to the executor. This allows cached KafkaConsumers in the executors to be re-used to
    +    // read the same partition in every batch.
    +    val topicPartitionOrdering = new Ordering[TopicPartition] {
    +      override def compare(l: TopicPartition, r: TopicPartition): Int = {
    +        implicitly[Ordering[(String, Long)]].compare(
    +          (l.topic, l.partition),
    +          (r.topic, r.partition))
    +      }
    +    }
    +
    +    // Use the until partitions to calculate offset ranges to ignore partitions that have
    +    // been deleted
    +    val sortedTopicPartitions = untilPartitionOffsets.keySet.toSeq.sorted(topicPartitionOrdering)
    +    logDebug("Sorted topicPartitions: " + sortedTopicPartitions.mkString(", "))
    +
    +    val sortedExecutors = getSortedExecutorList(sc)
    +    val numExecutors = sortedExecutors.length
    +    logDebug("Sorted executors: " + sortedExecutors.mkString(", "))
    +
    +    // Calculate offset ranges
    +    val offsetRanges = sortedTopicPartitions.map { tp =>
    +      val fromOffset = fromPartitionOffsets.get(tp).getOrElse {
    +        newPartitionOffsets.getOrElse(tp, {
    +          // This should not happen since newPartitionOffsets contains all partitions not in
    +          // fromPartitionOffsets
    +          throw new IllegalStateException(s"$tp doesn't have a from offset")
    +        })
    +      }
    +      val untilOffset = untilPartitionOffsets(tp)
    +      val preferredLoc = if (numExecutors > 0) {
    +        Some(sortedExecutors(positiveMod(tp.hashCode, numExecutors)))
    +      } else None
    +      KafkaSourceRDDOffsetRange(tp, fromOffset, untilOffset, preferredLoc)
    +    }.toArray
    +
    +    // Create a RDD that reads from Kafka and get the (key, value) pair as byte arrays.
    +    val rdd = new KafkaSourceRDD(
    +      sc, executorKafkaParams, offsetRanges).map { cr =>
    +        Row(cr.checksum, cr.key, cr.offset, cr.partition, cr.serializedKeySize,
    +          cr.serializedValueSize, cr.timestamp, cr.timestampType.id, cr.topic, cr.value)
    +    }
    +
    +    logInfo("GetBatch generating RDD of offset range: " +
    +      offsetRanges.sortBy(_.topicPartition.toString).mkString(", "))
    +    sqlContext.createDataFrame(rdd, schema)
    +  }
    +
    +  /** Stop this source and free any resources it has allocated. */
    +  override def stop(): Unit = synchronized {
    +    consumer.close()
    +  }
    +
    +  override def toString(): String = s"KafkaSource[$consumerStrategy]"
    +
    +  /**
    +   * Fetch the offset of a partition, either the latest offsets or the current offsets in the
    +   * KafkaConsumer.
    +   */
    +  private def fetchPartitionOffsets(
    +      seekToLatest: Boolean): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    consumer.pause(partitions)
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +
    +    // Get the current or latest offset of each partition
    +    if (seekToLatest) {
    +      consumer.seekToEnd(partitions)
    +      logDebug("\tSeeked to the end")
    +    }
    +    logTrace("Getting positions")
    +    val partitionOffsets = partitions.asScala.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for partition : $partitionOffsets")
    +    partitionOffsets
    +  }
    +
    +  /** Fetch the earliest offsets for newly discovered partitions */
    +  private def fetchNewPartitionEarliestOffsets(
    +      newPartitions: Seq[TopicPartition]): Map[TopicPartition, Long] = withRetries {
    +
    +    // Poll to get the latest assigned partitions
    +    logTrace("\tPolling")
    +    consumer.poll(0)
    +    val partitions = consumer.assignment()
    +    logDebug(s"\tPartitioned assigned to consumer: $partitions")
    +    require(newPartitions.forall(tp => partitions.contains(tp)),
    +      s"$partitions doesn't contain all new paritions: $newPartitions")
    +
    +    // Get the earliest offset of each partition
    +    consumer.seekToBeginning(newPartitions.asJava)
    +    val partitionToOffsets = newPartitions.map(p => p -> consumer.position(p)).toMap
    +    logDebug(s"Got offsets for new partitions: $partitionToOffsets")
    +    partitionToOffsets
    +  }
    +
    +  /**
    +   * 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.
    +   */
    +  private def withRetries(
    +      body: => Map[TopicPartition, Long]): Map[TopicPartition, Long] = synchronized {
    +
    +    var result: Option[Map[TopicPartition, Long]] = None
    +    var attempt = 1
    +    var lastException: Exception = null
    +    while (result.isEmpty && attempt <= MAX_OFFSET_FETCH_ATTEMPTS) {
    +      try {
    +        result = Some(body)
    +      } catch {
    +        case e: Exception =>
    +          lastException = e
    +          logWarning(s"Error in attempt $attempt getting Kafka offsets: ", e)
    +          attempt += 1
    +          Thread.sleep(OFFSET_FETCH_ATTEMPT_INTERVAL_MS)
    +      }
    +    }
    +    if (result.isEmpty) {
    +      assert(attempt > MAX_OFFSET_FETCH_ATTEMPTS)
    +      assert(lastException != null)
    +      throw lastException
    +    }
    +    result.get
    +  }
    +
    +  private def positiveMod(a: Long, b: Int): Int = ((a % b).toInt + b) % b
    +}
    +
    +
    +/** Companion object for the [[KafkaSource]]. */
    +private[kafka010] object KafkaSource {
    +
    +  val MAX_OFFSET_FETCH_ATTEMPTS = 3
    +  val OFFSET_FETCH_ATTEMPT_INTERVAL_MS = 10
    +
    +  def kafkaSchema: StructType = StructType(Seq(
    --- End diff --
    
    Actually I would suggest putting the most important ones first, key, value, topic, partition, offset, ...


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org