spark-http-stream transfers Spark structured stream over HTTP protocol. Unlike tcp streams, Kafka streams and HDFS file streams, http streams often flow across distributed big data clusters on the Web. This feature is very helpful to build global data processing pipelines across different data centers (scientific research institues, for example) who own seperated data sets.
spark-http-stream provides:
HttpStreamServer: a HTTP server which receives, collects and provides http streamsHttpStreamSource: reads messages from aHttpStreamServer, acts as a structured streamingSourceHttpStreamSink: sends messages to aHttpStreamServerusing HTTP-POST commands, acts as a structured streamingSink
also spark-http-stream provides:
HttpStreamClient: a client used to communicate with aHttpStreamServer, developped upon HttpClientHttpStreamSourceProvider: a StreamSourceProvider which createsHttpStreamSourceHttpStreamSinkProvider: a StreamSinkProvider which createsHttpStreamSink
The simple archtecture of spark-http-stream is shown below:
use maven to import spark-http-stream:
<dependency>
<groupId>org.grapheco</groupId>
<artifactId>spark-http-stream</artifactId>
<version>0.9.1</version>
</dependency>
HttpStreamServer is actually a Jetty server with a HttpStreamServlet, it can be started using following code:
val server = HttpStreamServer.start("/xxxx", 8080);
When http://localhost:8080/xxxx is requested, the HttpStreamServlet will use an embeded ActionsHandler to
parse request message, perform certain action(fecthSchema, fetchStream, etc), and return response message.
By default, an NullActionsHandler is provided. Of coz it can be replaced with a MemoryBufferAsReceiver:
server.withBuffer()
.addListener(new ObjectArrayPrinter())
.createTopic[(String, Int, Boolean, Float, Double, Long, Byte)]("topic-1")
.createTopic[String]("topic-2");
or with a KafkaAsReceiver:
server.withKafka("vm105:9092,vm106:9092,vm107:9092,vm181:9092,vm182:9092")
.addListener(new ObjectArrayPrinter());
as shown above, several kinds of ActionsHandler are defined in spark-http-stream:
NullActionsHandler: does nothingMemoryBufferAsReceiver: maintains a local memory buffer, stores data sent from producers into buffer, and allows consumers to fetch data in batchKafkaAsReceiver: forwards all received data to Kafka
Notes that MemoryBufferAsReceiver maintains a server-side message buffer, while KafkaAsReceiver only forwards messages to Kafka cluster.
The following code shows how to load messages from a HttpStreamSource:
val lines = spark.readStream.format(classOf[HttpStreamSourceProvider].getName)
.option("httpServletUrl", "http://localhost:8080/xxxx")
.option("topic", "topic-1");
.option("includesTimestamp", "true")
.load();
options:
httpServletUrl: path to the servlettopic: topic name of messages to be consumedincludesTimestamp: tells if each row in the loaded DataFrame includes a time stamp or not, default value isfalsetimestampColumnName: name assigned to the time stamp column, default value is '_TIMESTAMP_'msFetchPeriod: time interval in milliseconds for message polling, default value is1(1ms)
The following code shows how to output messages to a HttpStreamSink:
val query = lines.writeStream
.format(classOf[HttpStreamSinkProvider].getName)
.option("httpServletUrl", "http://localhost:8080/xxxx")
.option("topic", "topic-1")
.start();
options:
- httpServletUrl: path to the servlet
- topic: topic name of produced messages
- maxPacketSize: max size in bytes of each message packet, if the actual DataFrame is too large, it will be splitted into serveral packets, default value is
10*1024*1024(10M)
Note that HttpStreamSource is only available when the HttpStreamServer is equiped with a MemoryBufferAsReceiver (use withBuffer, as shown above). If the HttpStreamServer choose Kafka as back-end message system (use withKafka), it is wrong to consume data from HttpStreamSource, just use KafkaSource (see http://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html) instead:
val df = spark
.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "vm105:9092,vm106:9092,vm107:9092,vm181:9092,vm182:9092")
.option("subscribe", "topic-1")
.load()
see https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamSourceSinkTest.scala and https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamKafkaTest.scala to get complete example code.
as shown in previous section, serveral kinds of ActionsHandler are defined in spark-http-stream: NullActionsHandler,
MemoryBufferAsReceiver, KafkaAsReceiver.
users can also customize their own ActionsHandler as they will. The interface looks like:
trait ActionsHandler {
def listActionHandlerEntries(requestBody: Map[String, Any]): ActionHandlerEntries;
def destroy();
}
here ActionHandlerEntries is just an alias of PartialFunction[String, Map[String, Any]], which accepts an input argument action: String, and returns an output argument responseBody: Map[String, Any]. the listActionHandlerEntries method is often written as a set of case expression:
override def listActionHandlerEntries(requestBody: Map[String, Any])
: PartialFunction[String, Map[String, Any]] = {
case "actionSendStream" ⇒ handleSendStream(requestBody);
}
the code shown above says: this ActionsHandler only handles action actionSendStream, in this case, it calls the method handleSendStream(requestBody) to handle request and output its return value as response. If other action is requested, an UnsupportedActionException will be thrown by the HttpStreamServer.
ActionsHandlerFactory is defined to tell how to create a ActionsHandler with required parameters:
trait ActionsHandlerFactory {
def createInstance(params: Params): ActionsHandler;
}
spark-http-stream provides a servlet named ConfigurableHttpStreamingServlet, users can configure the servlet in web.xml:
<servlet>
<servlet-name>httpStreamServlet</servlet-name>
<servlet-class>org.apache.spark.sql.execution.streaming.http.ConfigurableHttpStreamServlet</servlet-class>
<init-param>
<param-name>handlerFactoryName</param-name>
<param-value>org.apache.spark.sql.execution.streaming.http.KafkaAsReceiverFactory</param-value>
</init-param>
<init-param>
<param-name>bootstrapServers</param-name>
<param-value>vm105:9092,vm106:9092,vm107:9092,vm181:9092,vm182:9092</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>httpStreamServlet</servlet-name>
<url-pattern>/xxxx</url-pattern>
</servlet-mapping>
As shown above, a servlet of ConfigurableHttpStreamServlet is defined with a ActionsHandlerFactory KafkaAsReceiverFactory, required parameters for the ActionsHandlerFactory (bootstrapServers, for example), are defined as a set of init-params.
HttpStreamClientprovides a HTTP client used to communicate with aHttpStreamServer`. It contains serveral methods:
sendDataFrame: send aDataFrameto the server, if theDataFrameis too large, it will be splitted into smaller packetssendRows: send data (asArray[Row]) to serverfetchSchema: retrieves schema of certain topicfecthStream: retrieves data (as 'Array[RowEx]') from serversubscribe: subscribe a topic and retrieves a subscriberIdunsubscribe: unsubscribe
Note that some methods are only available when the server is equipped with correct ActionsHandler. As an example, the KafkaAsReceiver only handles action actionSendStream, that means, if you called fetchStream and sendDataFrame methods of the HttpStreamClient, it works well. But it will fail and throw an UnsupportedActionException when you called subscribe method.
+---------------+------------------------+-----------------+
| methods | MemoryBufferAsReceiver | KafkaAsReceiver |
+---------------+------------------------+-----------------+
| sendDataFrame | √ | √ |
+---------------+------------------------+-----------------+
| sendRows | √ | √ |
+---------------+------------------------+-----------------+
| fetchSchema | √ | X |
+---------------+------------------------+-----------------+
| fecthStream | √ | X |
+---------------+------------------------+-----------------+
| subscribe | √ | X |
+---------------+------------------------+-----------------+
| unsubscribe | √ | X |
+---------------+------------------------+-----------------+
StreamListener works when new data is arrived and will be consumed by ActionsHandler:
trait StreamListener {
def onArrive(topic: String, objects: Array[RowEx]);
}
Two kinds of StreamListeners are provided:
StreamCollector: collects data in a local memory bufferStreamPrinter: prints data while arriving
an example messages look like this:
++++++++topic=topic-1++++++++
RowEx([hello1,1,true,0.1,0.1,1,49],1,0,2017-08-27 20:37:56.432)
RowEx([hello2,2,false,0.2,0.2,2,50],1,1,2017-08-27 20:37:56.432)
RowEx([hello3,3,true,0.3,0.3,3,51],1,2,2017-08-27 20:37:56.432)
spark-http-stream only supports data types which can be recognized by Spark Encoders. These data types includes: String, Boolean, Int, Long, Float, Double, Byte, Array[].
A row will be wrapped as a RowEx object on receiving. RowEx is a data structure richer than Row. It contains some members and methods:
originalRow: original rowbatchId: batch id passed by SparkoffsetInBatch: offset of this row in current batchwithTimestamp(): returns aRowwith a timestampwithId(): returns aRowwith its idextra(): returns a triple (batchId, offsetInBatch, timestamp)
Considering an original row has values [hello1,1,true,0.1,0.1,1,49], following code show contents of mentioned structures:
+---------------+-------+--------------+-----------+------------+--------+---------+
| String:hello1 | Int:1 | Boolean:true | Float:0.1 | Double:0.1 | Long:1 | Byte:49 |
+---------------+-------+--------------+-----------+------------+--------+---------+
+---------------+-------+--------------+-----++--------+-------+-------------------------------+
| String:hello1 | Int:1 | Boolean:true | ... || Long:1 | Int:0 | Timestamp:2017-08-27 20:37:56 |
+---------------+-------+--------------+-----++--------+-------+-------------------------------+
+---------------+-------+--------------+-----------+-----+-------------------------------+
| String:hello1 | Int:1 | Boolean:true | Float:0.1 | ... | Timestamp:2017-08-27 20:37:56 |
+---------------+-------+--------------+-----------+-----+-------------------------------+
+---------------+-------+--------------+-----------+------------+--------+---------+------------+
| String:hello1 | Int:1 | Boolean:true | Float:0.1 | Double:0.1 | Long:1 | Byte:49 | String:1-0 |
+---------------+-------+--------------+-----------+------------+--------+---------+------------+
+--------+-------+-------------------------------+
| Long:1 | Int:0 | Timestamp:2017-08-27 20:37:56 |
+--------+-------+-------------------------------+
spark-http-stream defines a SerilizerFactory to create a SerializerInstance:
trait SerializerFactory {
def getSerializerInstance(serializerName: String): SerializerInstance;
}
an SerializerFactory.DEFAULT object is provided which is able to create two kinds of serializers:
java: creates a JavaSerializerkryo: creates a KryoSerializer
New kind of Serializer, json serializer, for example, is welcome.
By default, HttpStreamClient and HttpStreamServer uses kryo serializer.
HttpStreamServerClientTest: tests HttpStreamServer/Client, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamServerClientTest.scalaHttpStreamSourceSinkTest: tests HttpStreamSource and HttpStreamSink, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamSourceSinkTest.scalaHttpStreamKafkaTest: tests HttpStreamSink with Kafka as underlying message reveiver, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamKafkaTest.scalaHttpStreamDemo: a tool helps to test HttpTextStream and HttpTextSink, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamDemo.scala
steps to tests HttpStreamDemo:
- choose machine A, run
HttpStreamDemo start-server-on 8080 /xxxx, this starts a HTTP server which receives data from machine B - choose machine B, run
nc -lk 9999 - run
HttpStreamDemo read-from http://machine-a-host:8080/xxxxon machine B - run
HttpStreamDemo write-into http://machine-a-host:8080/xxxxon machine C - type some text in nc, data will be received by HttpStreamSink and then consumed as HttpStreamSource, finally displayed on console
kafka-clients-0.10: used byKafkaAsReceiverhttpclient-4.5: HttpStreamClient uses HttpClient projectjetty-9.0: HttpStreamServer is devploped upon Jettyspark-2.1: spark structued streaming libray
