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/02/02 23:45:38 UTC

[GitHub] spark pull request: Add FileStreamSource and a simple version of F...

GitHub user zsxwing opened a pull request:

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

    Add FileStreamSource and a simple version of FileStreamSink

    `FileStreamSource` is an implementation of `org.apache.spark.sql.execution.streaming.Source`. It takes advantage of the existing `HadoopFsRelationProvider` to support various file formats. It remembers files in each batch and stores it into the metadata files so as to recover them when restarting. The metadata files are stored in the file system. There will be a further PR to clean up the metadata files periodically. 
    
    `FileStreamSink` is very simple and only supports text files for now. Adding it in this patch mostly to help test `FileStreamSource`.
    
    This is based on the initial work from @marmbrus.

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

    $ git pull https://github.com/zsxwing/spark stream-df-file-source

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

    https://github.com/apache/spark/pull/11034.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 #11034
    
----
commit a2784ffc487046df2b9cc94064bc781759606908
Author: Shixiong Zhu <sh...@databricks.com>
Date:   2016-02-02T22:28:11Z

    Add FileStreamSource and FileStreamSink

----


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51961947
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset, StreamingRelation}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    --- End diff --
    
    I think there is a race here then.  You've already moved the file into the directory right?


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180158612
  
    How long is it going to take to implement caching?  I'd rather measure the performance of this implementation before we start optimizing.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180223618
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50805/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52060863
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,223 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val version = sqlContext.sparkContext.version
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        throw new IllegalArgumentException("No schema specified")
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   SPARK_VERSION
    --- End diff --
    
    I think we just want a metadata version here, since multiple spark versions will likely share the same 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51928412
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "text",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "drop1\nkeep2\nkeep3", src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      AddTextFileData(textSource, "drop4\nkeep5\nkeep6", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(textSource, "drop7\nkeep8\nkeep9", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "json",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "{'c': 'drop1'}\n{'c': 'keep2'}\n{'c': 'keep3'}", src, tmp),
    --- End diff --
    
    The column name here is `c` but the query is referencing `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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52375088
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   <FileStreamSource.VERSION>
    +   *   START
    +   *   -/a/b/c
    +   *   -/d/e/f
    +   *   ...
    +   *   END
    +   * }}}
    +   *
    +   * Note: <FileStreamSource.VERSION> means the value of `FileStreamSource.VERSION`.  Every file
    +   * path starts with "-" so that we can know if a line is a file path easily.
    +   */
    +  private def writeBatch(id: Int, files: Seq[String]): Unit = {
    +    assert(files.nonEmpty, "create a new batch without any file")
    +    val output = fs.create(new Path(metadataPath + "/" + id), true)
    +    val writer = new PrintWriter(new OutputStreamWriter(output, UTF_8))
    +    try {
    +      // scalastyle:off println
    +      writer.println(FileStreamSource.VERSION)
    +      writer.println(FileStreamSource.START_TAG)
    +      files.foreach(file => writer.println("-" + file))
    --- End diff --
    
    would be good to make "-" a field like START_TAG. Say, PATH_PREFIX?


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51928139
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,141 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override def schema: StructType = dataSchema.getOrElse(new StructType().add("value", StringType))
    --- End diff --
    
    This `getOrElse` is only going to work for the text file data source, I think that for things like JSON we should probably try and initialize the source using `dataFrameBuilder` and extract the schema from there.
    
    We should also add tests that would catch a problem 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180227126
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52209936
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,319 @@
    +/*
    + * 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.streaming
    +
    +import java.io.{ByteArrayInputStream, File, InputStream}
    +
    +import com.google.common.base.Charsets.UTF_8
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.execution.streaming.FileStreamSource._
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceTest extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "text"))
    +        stringToFile(file, content).renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +    source: FileStreamSource,
    +    content: Seq[String],
    +    src: File,
    +    tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +        content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +        file.renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  /** Use `format` and `path` to create FileStreamSource via DataFrameReader */
    +  def createFileStreamSource(
    +      format: String,
    +      path: String,
    +      schema: Option[StructType] = None): FileStreamSource = {
    +    val reader =
    +      if (schema.isDefined) {
    +        sqlContext.read.format(format).schema(schema.get)
    +      } else {
    +        sqlContext.read.format(format)
    +      }
    +    reader.stream(path)
    +      .queryExecution.analyzed
    +      .collect { case StreamingRelation(s: FileStreamSource, _) => s }
    +      .head
    +  }
    +
    +  val valueSchema = new StructType().add("value", StringType)
    +}
    +
    +class FileStreamSourceSuite extends FileStreamSourceTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("text", src.getCanonicalPath)
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "drop1\nkeep2\nkeep3", src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(textSource, "drop4\nkeep5\nkeep6", src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(textSource, "drop7\nkeep8\nkeep9", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath, Some(valueSchema))
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop1'}\n{'value': 'keep2'}\n{'value': 'keep3'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop4'}\n{'value': 'keep5'}\n{'value': 'keep6'}",
    +        src,
    +        tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop7'}\n{'value': 'keep8'}\n{'value': 'keep9'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files with inferring schema") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    // Add a file so that we can infer its schema
    +    stringToFile(new File(src, "existing"), "{'c': 'drop1'}\n{'c': 'keep2'}\n{'c': 'keep3'}")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath)
    +
    +    // FileStreamSource should infer the column "c"
    +    val df = textSource.toDF().filter($"c" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "{'c': 'drop4'}\n{'c': 'keep5'}\n{'c': 'keep6'}", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from parquet files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val fileSource = createFileStreamSource("parquet", src.getCanonicalPath, Some(valueSchema))
    +    val df = fileSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddParquetFileData(fileSource, Seq("drop1", "keep2", "keep3"), src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddParquetFileData(fileSource, Seq("drop4", "keep5", "keep6"), src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddParquetFileData(fileSource, Seq("drop7", "keep8", "keep9"), src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("file stream source without schema") {
    +    val src = Utils.createTempDir("streaming.src")
    +
    +    // Only "text" doesn't need a schema
    +    createFileStreamSource("text", src.getCanonicalPath)
    --- End diff --
    
    Fixed the path error for `stream`


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180250356
  
    **[Test build #50809 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50809/consoleFull)** for PR 11034 at commit [`ca1e6b8`](https://github.com/apache/spark/commit/ca1e6b8a8297e6c66cef8ac1d6833329f4fe3ba2).
     * 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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#issuecomment-178875023
  
    **[Test build #50604 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50604/consoleFull)** for PR 11034 at commit [`a2784ff`](https://github.com/apache/spark/commit/a2784ffc487046df2b9cc94064bc781759606908).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-182159661
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179481679
  
    **[Test build #50678 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50678/consoleFull)** for PR 11034 at commit [`71e6312`](https://github.com/apache/spark/commit/71e63129b675899f566d47b3367180db128b5472).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180500710
  
    **[Test build #50828 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50828/consoleFull)** for PR 11034 at commit [`d911963`](https://github.com/apache/spark/commit/d911963c012e8d55d926ca9c78a44baf201c443d).


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#discussion_r51668567
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/DataStreamReaderSuite.scala ---
    @@ -33,10 +33,11 @@ object LastOptions {
     class DefaultSource extends StreamSourceProvider with StreamSinkProvider {
       override def createSource(
           sqlContext: SQLContext,
    -      parameters: Map[String, String],
    -      schema: Option[StructType]): Source = {
    +      partitionColumns: Option[StructType],
    +      dataSchema: Option[StructType],
    +      parameters: Map[String, String]): Source = {
    --- End diff --
    
    If we have to add stuff we should probably add a schema too.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180540657
  
    **[Test build #50828 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50828/consoleFull)** for PR 11034 at commit [`d911963`](https://github.com/apache/spark/commit/d911963c012e8d55d926ca9c78a44baf201c443d).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180506306
  
    Changes to this PR:
    
    1. Add a HashMap batchToMetadata to store the metadata in memory so that we don't need to read metadata files in `getNextBatch`
    2. Load metadata files and handle corrupted metadata files when finding metadata files in the constructor
    3. Only text format doesn't require a schema when there are no existing files. For other cases, it will throw `IllegalArgumentException`.


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#issuecomment-179448544
  
    **[Test build #50678 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50678/consoleFull)** for PR 11034 at commit [`71e6312`](https://github.com/apache/spark/commit/71e63129b675899f566d47b3367180db128b5472).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180247264
  
    **[Test build #50807 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50807/consoleFull)** for PR 11034 at commit [`ca1e6b8`](https://github.com/apache/spark/commit/ca1e6b8a8297e6c66cef8ac1d6833329f4fe3ba2).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179509023
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180095564
  
    **[Test build #50779 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50779/consoleFull)** for PR 11034 at commit [`93af82e`](https://github.com/apache/spark/commit/93af82e3d77b0625b992f1974c5f4e931d432dcb).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180611985
  
    Small comments, otherwise LGTM


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51956830
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset, StreamingRelation}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    --- End diff --
    
    Why +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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180549049
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180167868
  
    > How long is it going to take to implement caching? I'd rather measure the performance of this implementation before we start optimizing.
    
    Not a lot of work, actually. Just adding a <batch_id, files> map and updating it in getNextBatch.


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#discussion_r51668059
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,137 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming.StreamExecution
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    --- End diff --
    
    Could we write these tests with the `MemorySink` instead, using `testStream`?  I'd like to be able to test things like dropped batches and restarting as well.  I would also be good to have them less coupled.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51957694
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,151 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        new StructType().add("value", StringType)
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /** Returns the maximum offset that can be retrieved from the source. */
    +  def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchFile += 1
    +      writeBatch(maxBatchFile, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchFile)
    +  }
    +
    +  def currentOffset: LongOffset = synchronized {
    +    new LongOffset(maxBatchFile)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    val batchFiles = (startId + 1 to endId).filter(_ >= 0).map(i => s"$metadataPath/$i")
    +    if (batchFiles.nonEmpty) {
    +      logDebug(s"Producing files from batches ${startId + 1}:$endId")
    +      logDebug(s"Batch files: $batchFiles")
    +
    +      // Probably does not need to be a spark job...
    +      val files = sqlContext
    +          .read
    +          .text(batchFiles: _*)
    +          .as[String]
    +          .collect()
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    } else {
    +      None
    +    }
    +  }
    +
    +  private def sparkContext = sqlContext.sparkContext
    +
    +  private val fs = FileSystem.get(sparkContext.hadoopConfiguration)
    +  private val existingBatchFiles = fetchAllBatchFiles()
    +  private val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +  private var maxBatchFile = if (existingBatchIds.isEmpty) -1 else existingBatchIds.max
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  if (existingBatchFiles.nonEmpty) {
    +    sqlContext.read
    +        .text(existingBatchFiles.map(_.getPath.toString): _*)
    --- End diff --
    
    should these be two indented rather than four indented?


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51956317
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,151 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        new StructType().add("value", StringType)
    --- End diff --
    
    Even if there are no files present, we should probably still defer to the source.  Those that can support that will work and those that don't will throw the correct error message.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180511006
  
    **[Test build #50830 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50830/consoleFull)** for PR 11034 at commit [`ce0556d`](https://github.com/apache/spark/commit/ce0556dea847981ce7dd0fdfd2d2017875ed59bd).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180126535
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50780/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51962367
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset, StreamingRelation}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    --- End diff --
    
    We also need to add a test that completely recreates the `DataFrame`, which will require adding a new type of action to `StreamTest`.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180639247
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180548808
  
    **[Test build #50830 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50830/consoleFull)** for PR 11034 at commit [`ce0556d`](https://github.com/apache/spark/commit/ce0556dea847981ce7dd0fdfd2d2017875ed59bd).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180558722
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179525992
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50687/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52061248
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,323 @@
    +/*
    + * 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.streaming
    +
    +import java.io.{ByteArrayInputStream, File, InputStream}
    +
    +import com.google.common.base.Charsets.UTF_8
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.execution.streaming.FileStreamSource._
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceTest extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "text"))
    +        stringToFile(file, content).renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +    source: FileStreamSource,
    +    content: Seq[String],
    +    src: File,
    +    tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    --- End diff --
    
    Could we have gotten the same thing by checking the offset before moving the 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52085871
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,229 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   SPARK_VERSION
    +   *   START
    +   *   -/a/b/c
    +   *   -/d/e/f
    +   *   ...
    +   *   END
    +   * }}}
    +   *
    +   * Note: every file path starts with "-" so that we can know if a line is a file path easily.
    +   */
    +  private def writeBatch(id: Int, files: Seq[String]): Unit = {
    +    assert(files.nonEmpty, "create a new batch without any file")
    +    val output = fs.create(new Path(metadataPath + "/" + id), true)
    +    val writer = new PrintWriter(new OutputStreamWriter(output, UTF_8))
    +    try {
    +      // scalastyle:off println
    +      writer.println(FileStreamSource.VERSION)
    +      writer.println(FileStreamSource.START_TAG)
    +      files.foreach(file => writer.println("-" + file))
    +      writer.println(FileStreamSource.END_TAG)
    +      // scalastyle:on println
    +    } finally {
    +      writer.close()
    +    }
    +    batchToMetadata(id) = files
    +  }
    +
    +  /** Read the file names of the specified batch id from the metadata file */
    +  private def readBatch(id: Int): Seq[String] = {
    +    val input = fs.open(new Path(metadataPath + "/" + id))
    +    try {
    +      FileStreamSource.readBatch(input)
    +    } finally {
    +      input.close()
    +    }
    +  }
    +}
    +
    +object FileStreamSource {
    +
    +  private val START_TAG = "START"
    +  private val END_TAG = "END"
    +  val VERSION = "FILESTREAM1"
    +
    +  /**
    +   * Parse a metadata file and return the content. If the metadata file is corrupted, it will return
    +   * an empty `Seq`.
    +   */
    +  def readBatch(input: InputStream): Seq[String] = {
    +    val lines = scala.io.Source.fromInputStream(input)(Codec.UTF8).getLines().toArray
    --- 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180227129
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50806/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52063970
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,323 @@
    +/*
    + * 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.streaming
    +
    +import java.io.{ByteArrayInputStream, File, InputStream}
    +
    +import com.google.common.base.Charsets.UTF_8
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.execution.streaming.FileStreamSource._
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceTest extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "text"))
    +        stringToFile(file, content).renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +    source: FileStreamSource,
    +    content: Seq[String],
    +    src: File,
    +    tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    --- End diff --
    
    I think we need a `synchronized` here to make sure FileStreamSource is not scanning the files when moving the 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180250585
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50809/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51962353
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset, StreamingRelation}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  /** Use `format` and `path` to create FileStreamSource via DataFrameReader */
    +  private def createFileStreamSource(format: String, path: String): FileStreamSource = {
    +    sqlContext.read
    +      .format(format)
    +      .stream(path)
    +      .queryExecution.analyzed
    +      .collect { case StreamingRelation(s: FileStreamSource, _) => s }
    +      .head
    +  }
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("text", src.getCanonicalPath)
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "drop1\nkeep2\nkeep3", src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(textSource, "drop4\nkeep5\nkeep6", src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(textSource, "drop7\nkeep8\nkeep9", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath)
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop1'}\n{'value': 'keep2'}\n{'value': 'keep3'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop4'}\n{'value': 'keep5'}\n{'value': 'keep6'}",
    +        src,
    +        tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop7'}\n{'value': 'keep8'}\n{'value': 'keep9'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files with inferring schema") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    // Add a file so that we can infer its schema
    +    stringToFile(new File(src, "existing"), "{'c': 'drop1'}\n{'c': 'keep2'}\n{'c': 'keep3'}")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath)
    +
    +    // FileStreamSource should infer the column "c"
    +    val df = textSource.toDF().filter($"c" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "{'c': 'drop4'}\n{'c': 'keep5'}\n{'c': 'keep6'}", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from parquet files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val fileSource = createFileStreamSource("parquet", src.getCanonicalPath)
    +    val df = fileSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddParquetFileData(fileSource, Seq("drop1", "keep2", "keep3"), src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddParquetFileData(fileSource, Seq("drop4", "keep5", "keep6"), src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddParquetFileData(fileSource, Seq("drop7", "keep8", "keep9"), src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("file stress test") {
    --- End diff --
    
    Lets put this in its own suite since its pretty slow.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179481853
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50678/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-182159663
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/51009/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51957846
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,151 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        new StructType().add("value", StringType)
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /** Returns the maximum offset that can be retrieved from the source. */
    +  def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchFile += 1
    +      writeBatch(maxBatchFile, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchFile)
    +  }
    +
    +  def currentOffset: LongOffset = synchronized {
    +    new LongOffset(maxBatchFile)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    val batchFiles = (startId + 1 to endId).filter(_ >= 0).map(i => s"$metadataPath/$i")
    +    if (batchFiles.nonEmpty) {
    +      logDebug(s"Producing files from batches ${startId + 1}:$endId")
    +      logDebug(s"Batch files: $batchFiles")
    +
    +      // Probably does not need to be a spark job...
    +      val files = sqlContext
    +          .read
    +          .text(batchFiles: _*)
    +          .as[String]
    +          .collect()
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    } else {
    +      None
    +    }
    +  }
    +
    +  private def sparkContext = sqlContext.sparkContext
    +
    +  private val fs = FileSystem.get(sparkContext.hadoopConfiguration)
    +  private val existingBatchFiles = fetchAllBatchFiles()
    +  private val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +  private var maxBatchFile = if (existingBatchIds.isEmpty) -1 else existingBatchIds.max
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  if (existingBatchFiles.nonEmpty) {
    --- End diff --
    
    can you add some comments on what this code is 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 pull request: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51956904
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,151 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        new StructType().add("value", StringType)
    --- End diff --
    
    > Those that can support that will work and those that don't will throw the correct error message.
    
    But we need to return some `StructType` here. Any magic and defer 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 pull request: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180140059
  
    @marmbrus After discussing with @tdas offline, we think there will be a lot of changes to FileStreamSource if we want to cache the content of metadata files (so that we don't need to read them in getNextBatch) and handle corrupted metadata files. So it's meaningless to review this one now. Let me just work on that now and review this one later.


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#discussion_r51668742
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/DataStreamReader.scala ---
    @@ -100,6 +100,7 @@ class DataStreamReader private[sql](sqlContext: SQLContext) extends Logging {
         val resolved = ResolvedDataSource.createSource(
           sqlContext,
           userSpecifiedSchema = userSpecifiedSchema,
    +      partitionColumns = Array.empty[String],
    --- End diff --
    
    Wait second... I think we only ever give the partition columns to a DataSource when it is coming from the hive metastore.  Given that, I don't know if we actually need to do this at all for streaming.  Could we simplify this?


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180113613
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50779/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-182159467
  
    **[Test build #51009 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/51009/consoleFull)** for PR 11034 at commit [`07e2ddd`](https://github.com/apache/spark/commit/07e2dddf93ca9e6c87cdb755f9d28a51bccea445).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180558130
  
    **[Test build #50838 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50838/consoleFull)** for PR 11034 at commit [`9a1042c`](https://github.com/apache/spark/commit/9a1042cd13f3023240e7435e8615f41ccb470d41).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180228151
  
    **[Test build #50807 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50807/consoleFull)** for PR 11034 at commit [`ca1e6b8`](https://github.com/apache/spark/commit/ca1e6b8a8297e6c66cef8ac1d6833329f4fe3ba2).


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#issuecomment-178908037
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50604/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51964915
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset, StreamingRelation}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    --- End diff --
    
    Ah, right. How about adding PauseStream and ResumeStream actions? So that we can make sure no batch will run when adding data 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52083851
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,223 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val version = sqlContext.sparkContext.version
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        throw new IllegalArgumentException("No schema specified")
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   SPARK_VERSION
    --- End diff --
    
    Update this comment then.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180222450
  
    retest this please


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179509027
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50684/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179525975
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180227619
  
    retest this please


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51953151
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    --- End diff --
    
    Updated tests to add `StartStream` and `StopStream`. Also added a stress test.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51953075
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,141 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override def schema: StructType = dataSchema.getOrElse(new StructType().add("value", StringType))
    --- End diff --
    
    Updated the logic here. Now if there are any existing files, it will use them to infer the schema. And also added a test for 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52065398
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/sources/interfaces.scala ---
    @@ -195,6 +196,35 @@ trait HadoopFsRelationProvider {
         }
         createRelation(sqlContext, paths, dataSchema, partitionColumns, parameters)
       }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +    val path = parameters("path")
    +    val metadataPath = parameters.getOrElse("metadataPath", s"$path/_metadata")
    +
    +    def dataFrameBuilder(files: Array[String]): DataFrame = {
    +      val relation = createRelation(
    +        sqlContext,
    +        files,
    +        schema,
    +        partitionColumns = None,
    +        bucketSpec = None,
    +        parameters)
    +      DataFrame(sqlContext, LogicalRelation(relation))
    +    }
    +
    +    val maybeSchema =
    +      if (schema.isEmpty && providerName == "text") {
    --- End diff --
    
    Moved this local into FileStreamSource


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52374787
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   <FileStreamSource.VERSION>
    +   *   START
    +   *   -/a/b/c
    +   *   -/d/e/f
    +   *   ...
    +   *   END
    +   * }}}
    +   *
    +   * Note: <FileStreamSource.VERSION> means the value of `FileStreamSource.VERSION`.  Every file
    +   * path starts with "-" so that we can know if a line is a file path easily.
    +   */
    +  private def writeBatch(id: Int, files: Seq[String]): Unit = {
    +    assert(files.nonEmpty, "create a new batch without any file")
    +    val output = fs.create(new Path(metadataPath + "/" + id), true)
    +    val writer = new PrintWriter(new OutputStreamWriter(output, UTF_8))
    +    try {
    +      // scalastyle:off println
    +      writer.println(FileStreamSource.VERSION)
    +      writer.println(FileStreamSource.START_TAG)
    +      files.foreach(file => writer.println("-" + file))
    +      writer.println(FileStreamSource.END_TAG)
    +      // scalastyle:on println
    +    } finally {
    +      writer.close()
    +    }
    +    batchToMetadata(id) = files
    +  }
    +
    +  /** Read the file names of the specified batch id from the metadata file */
    +  private def readBatch(id: Int): Seq[String] = {
    +    val input = fs.open(new Path(metadataPath + "/" + id))
    +    try {
    +      FileStreamSource.readBatch(input)
    +    } finally {
    +      input.close()
    +    }
    +  }
    +}
    +
    +object FileStreamSource {
    +
    +  private val START_TAG = "START"
    +  private val END_TAG = "END"
    +  val VERSION = "FILESTREAM1"
    +
    +  /**
    +   * Parse a metadata file and return the content. If the metadata file is corrupted, it will return
    +   * an empty `Seq`.
    +   */
    +  def readBatch(input: InputStream): Seq[String] = {
    +    val lines = scala.io.Source.fromInputStream(input)(Codec.UTF8).getLines().toArray
    +    if (lines.length < 4) {
    +      // version + start tag + end tag + at least one file path
    +      return Nil
    +    }
    +    if (lines.head != VERSION) {
    +      return Nil
    +    }
    +    if (lines(1) != START_TAG) {
    +      return Nil
    +    }
    +    if (lines.last != END_TAG) {
    +      return Nil
    +    }
    +    lines.slice(2, lines.length - 1).map(_.drop(1)) // Drop character "-"
    --- End diff --
    
    stripPrefix("-")


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180540913
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50828/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51929483
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "text",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    --- End diff --
    
    The problem is `DataFrameReader` doesn't return `Source`. It just returns `DateFrame`.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51928604
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    --- End diff --
    
    We should add tests that start/stop the stream as well to test recovery.  We should also consider creating a stress test.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51928299
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "text",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    --- End diff --
    
    I'd prefer to use the `DataFrameReader/Writer` interface here so that changes to internals don't require changes to the tests.


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#issuecomment-178872016
  
    @marmbrus @tdas Please take a look.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180221994
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52083903
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,229 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   SPARK_VERSION
    +   *   START
    +   *   -/a/b/c
    +   *   -/d/e/f
    +   *   ...
    +   *   END
    +   * }}}
    +   *
    +   * Note: every file path starts with "-" so that we can know if a line is a file path easily.
    +   */
    +  private def writeBatch(id: Int, files: Seq[String]): Unit = {
    +    assert(files.nonEmpty, "create a new batch without any file")
    +    val output = fs.create(new Path(metadataPath + "/" + id), true)
    +    val writer = new PrintWriter(new OutputStreamWriter(output, UTF_8))
    +    try {
    +      // scalastyle:off println
    +      writer.println(FileStreamSource.VERSION)
    +      writer.println(FileStreamSource.START_TAG)
    +      files.foreach(file => writer.println("-" + file))
    +      writer.println(FileStreamSource.END_TAG)
    +      // scalastyle:on println
    +    } finally {
    +      writer.close()
    +    }
    +    batchToMetadata(id) = files
    +  }
    +
    +  /** Read the file names of the specified batch id from the metadata file */
    +  private def readBatch(id: Int): Seq[String] = {
    +    val input = fs.open(new Path(metadataPath + "/" + id))
    +    try {
    +      FileStreamSource.readBatch(input)
    +    } finally {
    +      input.close()
    +    }
    +  }
    +}
    +
    +object FileStreamSource {
    +
    +  private val START_TAG = "START"
    +  private val END_TAG = "END"
    +  val VERSION = "FILESTREAM1"
    +
    +  /**
    +   * Parse a metadata file and return the content. If the metadata file is corrupted, it will return
    +   * an empty `Seq`.
    +   */
    +  def readBatch(input: InputStream): Seq[String] = {
    +    val lines = scala.io.Source.fromInputStream(input)(Codec.UTF8).getLines().toArray
    --- End diff --
    
    We should validate the version too probably?


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179525360
  
    **[Test build #50687 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50687/consoleFull)** for PR 11034 at commit [`6a90c55`](https://github.com/apache/spark/commit/6a90c55beece97af10af5aa01f004ac85fda02a4).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52372298
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    --- End diff --
    
    nit: Just say, Map of batch id to files. 


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-181529260
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51960338
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,151 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        new StructType().add("value", StringType)
    --- End diff --
    
    Oh I see, even `sqlContext.read.format("text").load()` doesn't work?  I would rather fix that than hardcode this here.  
    
    For sources like parquet/json it doesn't really make sense to let them point it at an empty directory so I would rather throw an error.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180225496
  
    retest this please


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-181596522
  
    **[Test build #50937 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50937/consoleFull)** for PR 11034 at commit [`fb0e3f9`](https://github.com/apache/spark/commit/fb0e3f932f1f4a8dcc049c96d8acaf437f3522a0).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52372756
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    --- End diff --
    
    this should be a illegalstateexception, not illegalargumentexception since this is not based on some argument that user did.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51938390
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "text",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    --- End diff --
    
    I think that we need to have at least some tests that go through the user facing API.  I would even consider just always extracting the source from the `DataFrame` since that path is likely to be more stable.
    
    ```scala
    df.queryExecution.analyzed.collect { case s: Source => s }.head
    ```


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180223617
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-181597213
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50937/
    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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#discussion_r51668215
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/sources/interfaces.scala ---
    @@ -130,8 +130,9 @@ trait SchemaRelationProvider {
     trait StreamSourceProvider {
       def createSource(
           sqlContext: SQLContext,
    -      parameters: Map[String, String],
    -      schema: Option[StructType]): Source
    +      partitionColumns: Option[StructType],
    +      dataSchema: Option[StructType],
    --- End diff --
    
    nit: could we order these the same as below: dataSchema, partitionColumns, parameters


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52129416
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,319 @@
    +/*
    + * 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.streaming
    +
    +import java.io.{ByteArrayInputStream, File, InputStream}
    +
    +import com.google.common.base.Charsets.UTF_8
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.execution.streaming.FileStreamSource._
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceTest extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "text"))
    +        stringToFile(file, content).renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +    source: FileStreamSource,
    +    content: Seq[String],
    +    src: File,
    +    tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +        content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +        file.renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  /** Use `format` and `path` to create FileStreamSource via DataFrameReader */
    +  def createFileStreamSource(
    +      format: String,
    +      path: String,
    +      schema: Option[StructType] = None): FileStreamSource = {
    +    val reader =
    +      if (schema.isDefined) {
    +        sqlContext.read.format(format).schema(schema.get)
    +      } else {
    +        sqlContext.read.format(format)
    +      }
    +    reader.stream(path)
    +      .queryExecution.analyzed
    +      .collect { case StreamingRelation(s: FileStreamSource, _) => s }
    +      .head
    +  }
    +
    +  val valueSchema = new StructType().add("value", StringType)
    +}
    +
    +class FileStreamSourceSuite extends FileStreamSourceTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("text", src.getCanonicalPath)
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "drop1\nkeep2\nkeep3", src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(textSource, "drop4\nkeep5\nkeep6", src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(textSource, "drop7\nkeep8\nkeep9", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath, Some(valueSchema))
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop1'}\n{'value': 'keep2'}\n{'value': 'keep3'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop4'}\n{'value': 'keep5'}\n{'value': 'keep6'}",
    +        src,
    +        tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop7'}\n{'value': 'keep8'}\n{'value': 'keep9'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files with inferring schema") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    // Add a file so that we can infer its schema
    +    stringToFile(new File(src, "existing"), "{'c': 'drop1'}\n{'c': 'keep2'}\n{'c': 'keep3'}")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath)
    +
    +    // FileStreamSource should infer the column "c"
    +    val df = textSource.toDF().filter($"c" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "{'c': 'drop4'}\n{'c': 'keep5'}\n{'c': 'keep6'}", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from parquet files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val fileSource = createFileStreamSource("parquet", src.getCanonicalPath, Some(valueSchema))
    +    val df = fileSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddParquetFileData(fileSource, Seq("drop1", "keep2", "keep3"), src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddParquetFileData(fileSource, Seq("drop4", "keep5", "keep6"), src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddParquetFileData(fileSource, Seq("drop7", "keep8", "keep9"), src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("file stream source without schema") {
    +    val src = Utils.createTempDir("streaming.src")
    +
    +    // Only "text" doesn't need a schema
    +    createFileStreamSource("text", src.getCanonicalPath)
    --- End diff --
    
    I would like to fix it in a separate PR since `load` throws the same error:
    
    ```
    scala> sqlContext.read.format("text").load()
    java.util.NoSuchElementException: key not found: path
      at scala.collection.MapLike$class.default(MapLike.scala:228)
      at org.apache.spark.sql.execution.datasources.CaseInsensitiveMap.default(ddl.scala:159)
      at scala.collection.MapLike$class.apply(MapLike.scala:141)
      at org.apache.spark.sql.execution.datasources.CaseInsensitiveMap.apply(ddl.scala:159)
      at org.apache.spark.sql.execution.datasources.ResolvedDataSource$$anonfun$10.apply(ResolvedDataSource.scala:200)
      at org.apache.spark.sql.execution.datasources.ResolvedDataSource$$anonfun$10.apply(ResolvedDataSource.scala:200)
      at scala.Option.getOrElse(Option.scala:121)
      at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:200)
      at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:129)
      ... 49 elided
    ```


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180639249
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50848/
    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: [SPARK-13149][SQL]Add FileStreamSource

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

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


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52374217
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   <FileStreamSource.VERSION>
    +   *   START
    +   *   -/a/b/c
    +   *   -/d/e/f
    +   *   ...
    +   *   END
    +   * }}}
    +   *
    +   * Note: <FileStreamSource.VERSION> means the value of `FileStreamSource.VERSION`.  Every file
    --- End diff --
    
    extra space after .


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52372901
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    --- End diff --
    
    nit: "." at the end.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179508218
  
    **[Test build #50684 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50684/consoleFull)** for PR 11034 at commit [`6a90c55`](https://github.com/apache/spark/commit/6a90c55beece97af10af5aa01f004ac85fda02a4).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179488523
  
    **[Test build #50687 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50687/consoleFull)** for PR 11034 at commit [`6a90c55`](https://github.com/apache/spark/commit/6a90c55beece97af10af5aa01f004ac85fda02a4).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-182139796
  
    **[Test build #51009 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/51009/consoleFull)** for PR 11034 at commit [`07e2ddd`](https://github.com/apache/spark/commit/07e2dddf93ca9e6c87cdb755f9d28a51bccea445).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52373383
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   <FileStreamSource.VERSION>
    +   *   START
    +   *   -/a/b/c
    +   *   -/d/e/f
    +   *   ...
    +   *   END
    +   * }}}
    +   *
    +   * Note: <FileStreamSource.VERSION> means the value of `FileStreamSource.VERSION`.  Every file
    +   * path starts with "-" so that we can know if a line is a file path easily.
    +   */
    +  private def writeBatch(id: Int, files: Seq[String]): Unit = {
    +    assert(files.nonEmpty, "create a new batch without any file")
    +    val output = fs.create(new Path(metadataPath + "/" + id), true)
    +    val writer = new PrintWriter(new OutputStreamWriter(output, UTF_8))
    +    try {
    +      // scalastyle:off println
    +      writer.println(FileStreamSource.VERSION)
    +      writer.println(FileStreamSource.START_TAG)
    +      files.foreach(file => writer.println("-" + file))
    +      writer.println(FileStreamSource.END_TAG)
    +      // scalastyle:on println
    +    } finally {
    +      writer.close()
    +    }
    +    batchToMetadata(id) = files
    +  }
    +
    +  /** Read the file names of the specified batch id from the metadata file */
    +  private def readBatch(id: Int): Seq[String] = {
    +    val input = fs.open(new Path(metadataPath + "/" + id))
    +    try {
    +      FileStreamSource.readBatch(input)
    +    } finally {
    +      input.close()
    +    }
    +  }
    +}
    +
    +object FileStreamSource {
    +
    +  private val START_TAG = "START"
    +  private val END_TAG = "END"
    +  val VERSION = "FILESTREAM1"
    --- End diff --
    
    FILESTREAM_V1


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51957616
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,151 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io.{BufferedWriter, OutputStreamWriter}
    +
    +import scala.collection.mutable.ArrayBuffer
    +
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  import sqlContext.implicits._
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        new StructType().add("value", StringType)
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /** Returns the maximum offset that can be retrieved from the source. */
    +  def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchFile += 1
    +      writeBatch(maxBatchFile, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchFile)
    +  }
    +
    +  def currentOffset: LongOffset = synchronized {
    +    new LongOffset(maxBatchFile)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    val batchFiles = (startId + 1 to endId).filter(_ >= 0).map(i => s"$metadataPath/$i")
    +    if (batchFiles.nonEmpty) {
    +      logDebug(s"Producing files from batches ${startId + 1}:$endId")
    +      logDebug(s"Batch files: $batchFiles")
    +
    +      // Probably does not need to be a spark job...
    +      val files = sqlContext
    +          .read
    +          .text(batchFiles: _*)
    +          .as[String]
    +          .collect()
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    } else {
    +      None
    +    }
    +  }
    +
    +  private def sparkContext = sqlContext.sparkContext
    +
    +  private val fs = FileSystem.get(sparkContext.hadoopConfiguration)
    +  private val existingBatchFiles = fetchAllBatchFiles()
    +  private val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +  private var maxBatchFile = if (existingBatchIds.isEmpty) -1 else existingBatchIds.max
    --- End diff --
    
    nit: Isnt this `maxBatchId` rather than the file (since its an int, rather than a string)?


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180113604
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-181562746
  
    retest this please


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52065379
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,223 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val version = sqlContext.sparkContext.version
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        throw new IllegalArgumentException("No schema specified")
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    +    action
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * Returns the next batch of data that is available after `start`, if any is available.
    +   */
    +  override def getNextBatch(start: Option[Offset]): Option[Batch] = {
    +    val startId = start.map(_.asInstanceOf[LongOffset].offset).getOrElse(-1L)
    +    val end = fetchMaxOffset()
    +    val endId = end.offset
    +
    +    if (startId + 1 <= endId) {
    +      val files = (startId + 1 to endId).filter(_ >= 0).flatMap { batchId =>
    +          batchToMetadata.getOrElse(batchId, Nil)
    +        }.toArray
    +      logDebug(s"Return files from batches ${startId + 1}:$endId")
    +      logDebug(s"Streaming ${files.mkString(", ")}")
    +      Some(new Batch(end, dataFrameBuilder(files)))
    +    }
    +    else {
    +      None
    +    }
    +  }
    +
    +  private def fetchAllBatchFiles(): Seq[FileStatus] = {
    +    try fs.listStatus(new Path(metadataPath)) catch {
    +      case _: java.io.FileNotFoundException =>
    +        fs.mkdirs(new Path(metadataPath))
    +        Seq.empty
    +    }
    +  }
    +
    +  private def fetchAllFiles(): Seq[String] = {
    +    fs.listStatus(new Path(path))
    +      .filterNot(_.getPath.getName.startsWith("_"))
    +      .map(_.getPath.toUri.toString)
    +  }
    +
    +  /**
    +   * Write the metadata of a batch to disk. The file format is as follows:
    +   *
    +   * {{{
    +   *   SPARK_VERSION
    --- End diff --
    
    Added FileStreamSource.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 pull request: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180639108
  
    **[Test build #50848 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50848/consoleFull)** for PR 11034 at commit [`1ffee5f`](https://github.com/apache/spark/commit/1ffee5fe8e150bdf2edccdc912de87ab0af5abb2).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `  case class Result(avgMs: Double, bestRate: Double, bestMs: Double)`
      * `              s\"Unable to generate an encoder for inner class `$`
      * `case class NaturalJoin(tpe: JoinType) extends JoinType `


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180535935
  
    **[Test build #50838 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50838/consoleFull)** for PR 11034 at commit [`9a1042c`](https://github.com/apache/spark/commit/9a1042cd13f3023240e7435e8615f41ccb470d41).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180558725
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50838/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51957547
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset, StreamingRelation}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    --- End diff --
    
    To wait until the next batch finishes.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-181597208
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180126114
  
    **[Test build #50780 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50780/consoleFull)** for PR 11034 at commit [`2af6fc8`](https://github.com/apache/spark/commit/2af6fc81368ba9ec273b6d8c25076e989907db80).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180126510
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179481850
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-181565416
  
    **[Test build #50937 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50937/consoleFull)** for PR 11034 at commit [`fb0e3f9`](https://github.com/apache/spark/commit/fb0e3f932f1f4a8dcc049c96d8acaf437f3522a0).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52381644
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,319 @@
    +/*
    + * 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.streaming
    +
    +import java.io.{ByteArrayInputStream, File, InputStream}
    +
    +import com.google.common.base.Charsets.UTF_8
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.execution.streaming.FileStreamSource._
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceTest extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "text"))
    +        stringToFile(file, content).renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +    source: FileStreamSource,
    +    content: Seq[String],
    +    src: File,
    +    tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +        content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +        file.renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  /** Use `format` and `path` to create FileStreamSource via DataFrameReader */
    +  def createFileStreamSource(
    +      format: String,
    +      path: String,
    +      schema: Option[StructType] = None): FileStreamSource = {
    +    val reader =
    +      if (schema.isDefined) {
    +        sqlContext.read.format(format).schema(schema.get)
    +      } else {
    +        sqlContext.read.format(format)
    +      }
    +    reader.stream(path)
    +      .queryExecution.analyzed
    +      .collect { case StreamingRelation(s: FileStreamSource, _) => s }
    +      .head
    +  }
    +
    +  val valueSchema = new StructType().add("value", StringType)
    +}
    +
    +class FileStreamSourceSuite extends FileStreamSourceTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("text", src.getCanonicalPath)
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    --- End diff --
    
    while this extra line?? 
    why not `val filtered = textSource.toDF().filter($"value" contains "keep")`


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-182175197
  
    LGTM. New tests are great, and they make sense. Merging this!
    Thanks @zsxwing and @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 pull request: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52111238
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,319 @@
    +/*
    + * 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.streaming
    +
    +import java.io.{ByteArrayInputStream, File, InputStream}
    +
    +import com.google.common.base.Charsets.UTF_8
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.execution.streaming.FileStreamSource._
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceTest extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "text"))
    +        stringToFile(file, content).renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +    source: FileStreamSource,
    +    content: Seq[String],
    +    src: File,
    +    tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +        content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +        file.renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  /** Use `format` and `path` to create FileStreamSource via DataFrameReader */
    +  def createFileStreamSource(
    +      format: String,
    +      path: String,
    +      schema: Option[StructType] = None): FileStreamSource = {
    +    val reader =
    +      if (schema.isDefined) {
    +        sqlContext.read.format(format).schema(schema.get)
    +      } else {
    +        sqlContext.read.format(format)
    +      }
    +    reader.stream(path)
    +      .queryExecution.analyzed
    +      .collect { case StreamingRelation(s: FileStreamSource, _) => s }
    +      .head
    +  }
    +
    +  val valueSchema = new StructType().add("value", StringType)
    +}
    +
    +class FileStreamSourceSuite extends FileStreamSourceTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("text", src.getCanonicalPath)
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "drop1\nkeep2\nkeep3", src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(textSource, "drop4\nkeep5\nkeep6", src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(textSource, "drop7\nkeep8\nkeep9", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath, Some(valueSchema))
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop1'}\n{'value': 'keep2'}\n{'value': 'keep3'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop4'}\n{'value': 'keep5'}\n{'value': 'keep6'}",
    +        src,
    +        tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(
    +        textSource,
    +        "{'value': 'drop7'}\n{'value': 'keep8'}\n{'value': 'keep9'}",
    +        src,
    +        tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files with inferring schema") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    // Add a file so that we can infer its schema
    +    stringToFile(new File(src, "existing"), "{'c': 'drop1'}\n{'c': 'keep2'}\n{'c': 'keep3'}")
    +
    +    val textSource = createFileStreamSource("json", src.getCanonicalPath)
    +
    +    // FileStreamSource should infer the column "c"
    +    val df = textSource.toDF().filter($"c" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "{'c': 'drop4'}\n{'c': 'keep5'}\n{'c': 'keep6'}", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from parquet files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val fileSource = createFileStreamSource("parquet", src.getCanonicalPath, Some(valueSchema))
    +    val df = fileSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddParquetFileData(fileSource, Seq("drop1", "keep2", "keep3"), src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      StopStream,
    +      AddParquetFileData(fileSource, Seq("drop4", "keep5", "keep6"), src, tmp),
    +      StartStream,
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddParquetFileData(fileSource, Seq("drop7", "keep8", "keep9"), src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("file stream source without schema") {
    +    val src = Utils.createTempDir("streaming.src")
    +
    +    // Only "text" doesn't need a schema
    +    createFileStreamSource("text", src.getCanonicalPath)
    --- End diff --
    
    Can we also make sure we throw a better error for this case?
    
    ```scala
    scala> sqlContext.read.format("text").stream()
    java.util.NoSuchElementException: key not found: path
      at scala.collection.MapLike$class.default(MapLike.scala:228)
      at scala.collection.AbstractMap.default(Map.scala:59)
      at scala.collection.MapLike$class.apply(MapLike.scala:141)
      at scala.collection.AbstractMap.apply(Map.scala:59)
      at org.apache.spark.sql.sources.HadoopFsRelationProvider$class.createSource(interfaces.scala:206)
      at org.apache.spark.sql.execution.datasources.text.DefaultSource.createSource(DefaultSource.scala:42)
      at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.createSource(ResolvedDataSource.scala:107)
      at org.apache.spark.sql.DataFrameReader.stream(DataFrameReader.scala:167)
      ... 40 elided
    ```


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180099140
  
    **[Test build #50780 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50780/consoleFull)** for PR 11034 at commit [`2af6fc8`](https://github.com/apache/spark/commit/2af6fc81368ba9ec273b6d8c25076e989907db80).


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-182103180
  
    Offline discussion: 
    It will be good to have a unit test that documents/tests the behavior of what file source gets generated when format and/or schema is provided/not provided and existing files present / not present, what is the schema generated in the source. So that we have clear understanding of what the behavior is.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180221999
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50803/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180540909
  
    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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#discussion_r51668637
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSink.scala ---
    @@ -0,0 +1,63 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.nio.ByteBuffer
    +
    +import org.apache.hadoop.fs.{FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.serializer.JavaSerializer
    +import org.apache.spark.sql.SQLContext
    +
    +/**
    + * A very simple sink that stores received data on the filesystem as a text file.
    + * This is not atomic.
    + */
    +class FileStreamSink(
    --- End diff --
    
    If possible it would be nice to do this in a different 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52376290
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    +    val existingBatchFiles = fetchAllBatchFiles()
    +    if (existingBatchFiles.nonEmpty) {
    +      val existingBatchIds = existingBatchFiles.map(_.getPath.getName.toInt)
    +      maxBatchId = existingBatchIds.max
    +      // Recover "batchToMetadata" and "seenFiles" from existing metadata files.
    +      existingBatchIds.sorted.foreach { batchId =>
    +        val files = readBatch(batchId)
    +        if (files.isEmpty) {
    +          // Assert that the corrupted file must be the latest metadata file.
    +          require(batchId == maxBatchId, "Invalid metadata files")
    +          maxBatchId = maxBatchId - 1
    +        } else {
    +          batchToMetadata(batchId) = files
    +          files.foreach(seenFiles.add)
    +        }
    +      }
    +    }
    +  }
    +
    +  /** Returns the schema of the data from this source */
    +  override lazy val schema: StructType = {
    +    dataSchema.getOrElse {
    +      val filesPresent = fetchAllFiles()
    +      if (filesPresent.isEmpty) {
    +        if (providerName == "text") {
    +          // Add a default schema for "text"
    +          new StructType().add("value", StringType)
    +        } else {
    +          throw new IllegalArgumentException("No schema specified")
    +        }
    +      } else {
    +        // There are some existing files. Use them to infer the schema
    +        dataFrameBuilder(filesPresent.toArray).schema
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Returns the maximum offset that can be retrieved from the source.
    +   *
    +   * `synchronized` on this method is for solving race conditions in tests. In the normal usage,
    +   * there is no race here, so the cost of `synchronized` should be rare.
    +   */
    +  private def fetchMaxOffset(): LongOffset = synchronized {
    +    val filesPresent = fetchAllFiles()
    +    val newFiles = new ArrayBuffer[String]()
    +    filesPresent.foreach { file =>
    +      if (!seenFiles.contains(file)) {
    +        logDebug(s"new file: $file")
    +        newFiles.append(file)
    +        seenFiles.add(file)
    +      } else {
    +        logDebug(s"old file: $file")
    +      }
    +    }
    +
    +    if (newFiles.nonEmpty) {
    +      maxBatchId += 1
    +      writeBatch(maxBatchId, newFiles)
    +    }
    +
    +    new LongOffset(maxBatchId)
    +  }
    +
    +  /**
    +   * For test only. Run `action` and return the current offset. When `action` is running, the method
    +   * guarantee that the current offset won't be changed and no new batch will be emitted.
    +   */
    +  def currentOffset(action: => Unit = {}): LongOffset = synchronized {
    --- End diff --
    
    this is not a good name. `currentOffset` cannot take a body of code. Rather better to name this something like `withBatchingLocked`
    ```
    fileStreamSource.withBatchingLocked {
        // do something
    }
    ```


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-179482014
  
    retest this please


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180232252
  
    **[Test build #50809 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50809/consoleFull)** for PR 11034 at commit [`ca1e6b8`](https://github.com/apache/spark/commit/ca1e6b8a8297e6c66cef8ac1d6833329f4fe3ba2).


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#issuecomment-178908030
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180247474
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50807/
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180247473
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52372110
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/FileStreamSource.scala ---
    @@ -0,0 +1,233 @@
    +/*
    + * 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.execution.streaming
    +
    +import java.io._
    +
    +import scala.collection.mutable.{ArrayBuffer, HashMap}
    +import scala.io.Codec
    +
    +import com.google.common.base.Charsets.UTF_8
    +import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.collection.OpenHashSet
    +
    +/**
    + * A very simple source that reads text files from the given directory as they appear.
    + *
    + * TODO Clean up the metadata files periodically
    + */
    +class FileStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    path: String,
    +    dataSchema: Option[StructType],
    +    providerName: String,
    +    dataFrameBuilder: Array[String] => DataFrame) extends Source with Logging {
    +
    +  private val fs = FileSystem.get(sqlContext.sparkContext.hadoopConfiguration)
    +  private var maxBatchId = -1
    +  private val seenFiles = new OpenHashSet[String]
    +
    +  /** Cache files for each batch. The content of this map is also stored in the disk.  */
    +  private val batchToMetadata = new HashMap[Long, Seq[String]]
    +
    +  {
    +    // Restore statues from the metadata files
    --- End diff --
    
    nit: statuses, not statues. :)


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52375438
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,319 @@
    +/*
    + * 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.streaming
    +
    +import java.io.{ByteArrayInputStream, File, InputStream}
    +
    +import com.google.common.base.Charsets.UTF_8
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.streaming._
    +import org.apache.spark.sql.execution.streaming.FileStreamSource._
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types.{StringType, StructType}
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceTest extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      source.currentOffset {
    +        val file = Utils.tempFileWith(new File(tmp, "text"))
    +        stringToFile(file, content).renameTo(new File(src, file.getName))
    +      } + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +    source: FileStreamSource,
    --- End diff --
    
    incorrect indent.


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-181529265
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/50932/
    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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#issuecomment-178907310
  
    **[Test build #50604 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50604/consoleFull)** for PR 11034 at commit [`a2784ff`](https://github.com/apache/spark/commit/a2784ffc487046df2b9cc94064bc781759606908).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `class FileStreamSink(`
      * `class FileStreamSource(`
      * `trait HadoopFsRelationProvider extends StreamSourceProvider with StreamSinkProvider `


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51953115
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "text",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "drop1\nkeep2\nkeep3", src, tmp),
    +      CheckAnswer("keep2", "keep3"),
    +      AddTextFileData(textSource, "drop4\nkeep5\nkeep6", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6"),
    +      AddTextFileData(textSource, "drop7\nkeep8\nkeep9", src, tmp),
    +      CheckAnswer("keep2", "keep3", "keep5", "keep6", "keep8", "keep9")
    +    )
    +
    +    Utils.deleteRecursively(src)
    +    Utils.deleteRecursively(tmp)
    +  }
    +
    +  test("read from json files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "json",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    +    val df = textSource.toDF().filter($"value" contains "keep")
    +    val filtered = df
    +
    +    testStream(filtered)(
    +      AddTextFileData(textSource, "{'c': 'drop1'}\n{'c': 'keep2'}\n{'c': 'keep3'}", src, tmp),
    --- End diff --
    
    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 pull request: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r52060451
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/sources/interfaces.scala ---
    @@ -195,6 +196,35 @@ trait HadoopFsRelationProvider {
         }
         createRelation(sqlContext, paths, dataSchema, partitionColumns, parameters)
       }
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +    val path = parameters("path")
    +    val metadataPath = parameters.getOrElse("metadataPath", s"$path/_metadata")
    +
    +    def dataFrameBuilder(files: Array[String]): DataFrame = {
    +      val relation = createRelation(
    +        sqlContext,
    +        files,
    +        schema,
    +        partitionColumns = None,
    +        bucketSpec = None,
    +        parameters)
    +      DataFrame(sqlContext, LogicalRelation(relation))
    +    }
    +
    +    val maybeSchema =
    +      if (schema.isEmpty && providerName == "text") {
    --- End diff --
    
    My point was that I don't want to special case the logic here, but should instead defer to the source.  What happens if we add another source that is capable of producing a schema without any files present?


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#discussion_r51953109
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/streaming/FileStreamSourceSuite.scala ---
    @@ -0,0 +1,131 @@
    +/*
    + * 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.streaming
    +
    +import java.io.File
    +
    +import org.apache.spark.sql.StreamTest
    +import org.apache.spark.sql.catalyst.util._
    +import org.apache.spark.sql.execution.datasources.ResolvedDataSource
    +import org.apache.spark.sql.execution.streaming.{FileStreamSource, Offset}
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.util.Utils
    +
    +class FileStreamSourceSuite extends StreamTest with SharedSQLContext {
    +
    +  import testImplicits._
    +
    +  case class AddTextFileData(source: FileStreamSource, content: String, src: File, tmp: File)
    +    extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "text"))
    +      stringToFile(file, content).renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  case class AddParquetFileData(
    +      source: FileStreamSource,
    +      content: Seq[String],
    +      src: File,
    +      tmp: File) extends AddData {
    +
    +    override def addData(): Offset = {
    +      val file = Utils.tempFileWith(new File(tmp, "parquet"))
    +      content.toDS().toDF().write.parquet(file.getCanonicalPath)
    +      file.renameTo(new File(src, file.getName))
    +      source.currentOffset + 1
    +    }
    +  }
    +
    +  test("read from text files") {
    +    val src = Utils.createTempDir("streaming.src")
    +    val tmp = Utils.createTempDir("streaming.tmp")
    +
    +    val textSource = ResolvedDataSource.createSource(
    +      sqlContext,
    +      userSpecifiedSchema = None,
    +      providerName = "text",
    +      options = Map("path" -> src.getCanonicalPath)).asInstanceOf[FileStreamSource]
    --- End diff --
    
    Updated the tests to use DataFrameReader


---
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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180250582
  
    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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180113115
  
    **[Test build #50779 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50779/consoleFull)** for PR 11034 at commit [`93af82e`](https://github.com/apache/spark/commit/93af82e3d77b0625b992f1974c5f4e931d432dcb).
     * 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: [SPARK-13149][SQL]Add FileStreamSource

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

    https://github.com/apache/spark/pull/11034#issuecomment-180621013
  
    **[Test build #50848 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50848/consoleFull)** for PR 11034 at commit [`1ffee5f`](https://github.com/apache/spark/commit/1ffee5fe8e150bdf2edccdc912de87ab0af5abb2).


---
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: [SPARK-13149][SQL]Add FileStreamSource and a s...

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

    https://github.com/apache/spark/pull/11034#issuecomment-179474898
  
    **[Test build #50684 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/50684/consoleFull)** for PR 11034 at commit [`6a90c55`](https://github.com/apache/spark/commit/6a90c55beece97af10af5aa01f004ac85fda02a4).


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