Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ org.apache.spark.sql.execution.datasources.v2.text.TextDataSourceV2
org.apache.spark.sql.execution.streaming.ConsoleSinkProvider
org.apache.spark.sql.execution.streaming.sources.RateStreamProvider
org.apache.spark.sql.execution.streaming.sources.TextSocketSourceProvider
org.apache.spark.sql.execution.datasources.binaryfile.BinaryFileFormat
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* 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.datasources.binaryfile

import org.apache.spark.sql.types._

/**
* `binaryfile` package implements Spark SQL data source API for loading binary file data
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
* as `DataFrame`.
*

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also document how to control the input partition size. cc: @cloud-fan

* The loaded `DataFrame` has two columns, the schema is:
* - status: `StructType` (the file status information)
* - content: `BinaryType` (binary data of the file content)
*
* The schema of "status" column described above is:
* - path: `StringType` (the file path)
* - modification_time: `TimestampType` (last modification time of the file)
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
* - length: `LongType` (the file length)
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
*/
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
class BinaryFileDataSource private() {}
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
Comment thread
HyukjinKwon marked this conversation as resolved.
Outdated

object BinaryFileDataSource {

val fileStatusSchema = StructType(
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
StructField("path", StringType, true) ::
StructField("modification_time", TimestampType, true) ::
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
StructField("length", LongType, true) :: Nil)

val binaryFileSchema = StructType(
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
StructField("status", fileStatusSchema, true) ::
StructField("content", BinaryType, true) :: Nil)

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* 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.datasources.binaryfile

import java.sql.Timestamp

import com.google.common.io.{ByteStreams, Closeables}
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileStatus, GlobFilter, Path}
import org.apache.hadoop.mapreduce.Job

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.catalyst.expressions.{AttributeReference, UnsafeRow}
import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
import org.apache.spark.sql.execution.datasources.{DataSource, FileFormat, OutputWriterFactory, PartitionedFile}
import org.apache.spark.sql.sources.{DataSourceRegister, Filter}
import org.apache.spark.sql.types._
import org.apache.spark.util.SerializableConfiguration


private[binaryfile] class BinaryFileFormat extends FileFormat with DataSourceRegister {
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
Comment thread
HyukjinKwon marked this conversation as resolved.
Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per https://issues.apache.org/jira/browse/SPARK-16964, I think we can remove private[binaryfile]


override def inferSchema(
sparkSession: SparkSession,
options: Map[String, String],
files: Seq[FileStatus]): Option[StructType] = Some(BinaryFileDataSource.binaryFileSchema)

override def prepareWrite(
sparkSession: SparkSession,
job: Job,
options: Map[String, String],
dataSchema: StructType): OutputWriterFactory = {
throw new UnsupportedOperationException("Write is not supported for binary file data source")
}

override def shortName(): String = "binaryFile"
Comment thread
WeichenXu123 marked this conversation as resolved.
Comment thread
HyukjinKwon marked this conversation as resolved.

override protected def buildReader(
sparkSession: SparkSession,
dataSchema: StructType,
partitionSchema: StructType,
requiredSchema: StructType,
filters: Seq[Filter],

@cloud-fan cloud-fan Apr 14, 2019

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we going to leverage the filters here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can put it in later PR.

options: Map[String, String],
hadoopConf: Configuration): (PartitionedFile) => Iterator[InternalRow] = {

val broadcastedHadoopConf =
sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf))

val binaryFileSourceOptions = new BinaryFileSourceOptions(options)

val pathFilterRegex = binaryFileSourceOptions.pathFilterRegex
val globFilter = if (pathFilterRegex.isEmpty) { null } else {
new GlobFilter(pathFilterRegex)
}

(file: PartitionedFile) => {
val path = file.filePath
val fsPath = new Path(path)

if (globFilter == null || globFilter.accept(fsPath)) {
val fs = fsPath.getFileSystem(broadcastedHadoopConf.value.value)
val fileStatus = fs.getFileStatus(fsPath)
val length = fileStatus.getLen()
val modificationTime = new Timestamp(fileStatus.getModificationTime())
val stream = fs.open(fsPath)
Comment thread
WeichenXu123 marked this conversation as resolved.
val content = try {
Comment thread
HyukjinKwon marked this conversation as resolved.
ByteStreams.toByteArray(stream)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I remember correctly, the usual behavior in Spark is not to throw an exception but prefers null value. At this point, should we assign content null value instead of throwing exception?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, we can control it with ignoreCorruptFiles.

} finally {
Closeables.close(stream, true)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Related to above comment, should we not propagate IO exceptions?

}

val converter = RowEncoder(dataSchema)
val fullOutput = dataSchema.map { f =>
AttributeReference(f.name, f.dataType, f.nullable, f.metadata)()
}
val requiredOutput = fullOutput.filter { a =>
requiredSchema.fieldNames.contains(a.name)
}

val requiredColumns = GenerateUnsafeProjection.generate(requiredOutput, fullOutput)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this does not help the performance. We still read the file content even if content column is not required.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is OK for now, maybe we can leave a TODO and implement the real column pruning in the future.


val row = Row(Row(path, modificationTime, length), content)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since the schema is simple, we can create InternalRow directly, instead of creating Row and using RowEncoder.

string type should be UTF8String, timestamp type should be a long that is microseconds count since January 1, 1970 UTC.


Iterator(requiredColumns(converter.toRow(row)))
} else {
Iterator.empty
}
}
}
}

private[binaryfile] class BinaryFileSourceOptions(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove private[binaryfile] here as well.

@transient private val parameters: CaseInsensitiveMap[String]) extends Serializable {

def this(parameters: Map[String, String]) = this(CaseInsensitiveMap(parameters))

/**
* only include files with path matching the regex pattern.
*/
val pathFilterRegex = parameters.getOrElse("pathFilterRegex", "").toString
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* 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.datasources.binaryfile

import java.sql.Timestamp

import com.google.common.io.{ByteStreams, Closeables}
import org.apache.hadoop.fs.Path

import org.apache.spark.sql.{QueryTest, Row}
import org.apache.spark.sql.functions.{col, substring_index}
import org.apache.spark.sql.test.{SharedSQLContext, SQLTestUtils}
import org.apache.spark.sql.types.LongType

class BinaryFileSuite extends QueryTest with SharedSQLContext with SQLTestUtils {
import testImplicits._

private lazy val filePath = testFile("test-data/text-partitioned")

private lazy val fsFilePath = new Path(filePath)

private lazy val fs = fsFilePath.getFileSystem(sparkContext.hadoopConfiguration)

test("binary file test") {
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated

val resultDF = spark.read.format("binaryFile")
.load(filePath)
.select(
substring_index(col("status.path"), "/", -1).as("path"),
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
col("status.modification_time"),
col("status.length"),
col("content"),
col("year")
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
)

val expectedRowSet = new collection.mutable.HashSet[Row]()

for (partitionDirStatus <- fs.listStatus(fsFilePath)) {
val dirPath = partitionDirStatus.getPath

for (fileStatus <- fs.listStatus(dirPath)) {
val fname = fileStatus.getPath.getName
val flen = fileStatus.getLen
val modificationTime = new Timestamp(fileStatus.getModificationTime)

val fcontent = {
val stream = fs.open(fileStatus.getPath)
val content = try {
ByteStreams.toByteArray(stream)
} finally {
Closeables.close(stream, true)
}
content
}

val partitionName = dirPath.getName.split("=")(1)
Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
val year = partitionName.toInt
val row = Row(fname, modificationTime, flen, fcontent, year)
expectedRowSet.add(row)
}
}

val result = resultDF.collect()
assert(Set(result: _*) === expectedRowSet.toSet)
Comment thread
HyukjinKwon marked this conversation as resolved.
Outdated
}

Comment thread
WeichenXu123 marked this conversation as resolved.
Outdated
}