Apache Spark is an open source cluster computing framework originally developed in
the AMPLab at University of
California, Berkeley but was later donated to the Apache Software Foundation where it
remains today. In contrast to Hadoop's
two-stage disk-based MapReduce paradigm, Spark's multi-stage in-memory
primitives provides performance up to 100 times faster for certain
applications. By allowing user programs to load data into a cluster's memory
and query it repeatedly.
As Spark is build to test the Apache Mesos. Therefore lets try to
understand few basic about Apache Mesos:-
Distributed
Systems with Apache Mesos:-
Mesos :- It’s a Cluster Management platform
Yarn :- Parallel distributed computing framework.
Spark came into existence as a Library to test Mesos and its Cluster
Management Capabilities i.e. Allocate , De-allocate and Manage the Resources.
And its not at all responsible for the Processing part as its taken care by
Map-Reduce.
Originally the First version of of Spark was developed just by typing
1600 lines of code in Scala to work and run with fully functional independent
distributed system model to deploy on Mesos.
C++ was used to develop Mesos as it offers lot of Compatibility and
internally does lot’s of CPU management.
Mesos is integrated with the zookeeper to provide Master-Slave
architecture and offer more fault tolerance.
Containers in Linux are light weight VM i.e. partitions of CPU &
Disk, for fine grained information execution. Mesos utilises this very concept
of Container for easier and smarter execution of multiple parallel
processing.
Mesos supports multiple-session as it implements API & Libraries
specific to serve particular purpose, unlike Yarn which tries to implement
everything at one single place leading to more complexity resulting in
performance degradation.
Whatever application we write on top of Mesos is called as Framework
& its internal API are called as Scheduler. Here, it has its own set of
executors which is similar to Containers. Scheduler act as main() and
is similar to application master in Yarn, not as resource Master.
Mesos is preffered where the requirement is for Streaming &
Interactive Guidewire, whereas Yarn is preffered for batch processing.
Important
Note & Features:-
DataFrame is an additional Layer build on top of RDD
Meta-Data is encapsulated inside the logical plan itself.
For altering the data type & type casting we use concept of
Cascading.
Logical Plan will be same for both i.e. DataFrames & SQL Context.
Only one Physical Plan is generate for the given DataFrame, except the
case of Join where there will be multiple Physical Plans.
While writing the Optimisation Query try to keep the Filter near the
dataframe in order to restrict the loading of unwanted data. Here we are only optimising
the optimiser therefore rest all be same as that SQL Context.
Optimiser is used in cases where we want to modify the existing
definition i.e. provided by Spark.
Spark allows us to print both i.e. Analysed Plan as well as Optimised
plan
RDD Lineage provide Fault Tolerance to Spark and used to get the
information i.e. from it got generated, Number of partitions,
DataStore.
Nullable is only false in case of Booleans.
Var & Varchar are the only datatypes not supported by Spark.
SparkConf is another object which has all the configuration details
available inside it such i.e. Partition, Join, Etc…
Spark context is extended by Hive Context in order to overwrite the
optimized query plan.
We can have multiple SparkSQLContext object inside single spark Job.
Spark is based on columnar data types so it doesn’t allows Indexes.
Maximum number of fields in with Class Caste is 22.
Spark shell as Main program and leverages HDFS via SparkContext.
Here everything is first written in Memory compared to MR where after
each level of processing the data is written into the Disk i.e. Spark supports
the Iterative Data Processing mechanism which internally implies processing the
data internally.
Shared
Variables:-
Spark provides two types of shared variables to make it efficient to
run the Spark programs in a cluster. These are Broadcast Variables and
Accumulators.
Broadcast Variables: - Broadcast
variables allow to keep read-only variable cached on each machine instead of
sending a copy of it with tasks. They can be used to give the nodes in the
cluster copies of large input datasets more efficiently.
Following code snippet shows how to use the broadcast variables.
//
// Broadcast Variables
//
val broadcastVar = sc.broadcast(Array(1, 2, 3))
broadcastVar.value
Accumulators: - Accumulators
are only added using an associative operation and can therefore be efficiently
supported in parallel. They can be used to implement counters (as in MapReduce)
or sums. Tasks running on the cluster can add to an accumulator variable using
the add method. However, they cannot read its value. Only the driver program
can read the accumulator's value.
The code snippet below shows how to use Accumulator shared variable:
//
// Accumulators
//
val accum = sc.accumulator(0, "My Accumulator")
sc.parallelize(Array(1, 2, 3, 4)).foreach(x => accum += x)
accum.value
Spark
Execution:-
First the transformations are applied on the data set.
And lineage graph is also constructed simultaneously which store the
step to reach back to the RDD. We can write RDD.toDebugString method
to see detailed steps of forming RDD i.e. Lineage Graph.
Then driver does Serialization of data & copies the data on each
worker in parallel.
Then Action is performed on this RDD which actually loads the data in
the existing empty RDD. And this very process is known as Lazy Evaluation.
And after performing the first action whenever we will go for
performing 2nd action then it will be very fast as now data is already
present and cached inside memory.
Now consider a case where we have created an RDD then cached it, then
what will hapeen to the value of existing RDD, whether it will be updated
or not?
NO, once the RDD is created, it cant be updated. All what will be done
is another RDD will be created in memory & transformations will be applied
to it but those transformations will only come to existence only once an action
is triggred.
In Spark there very first RDD for any given dataset is called as Hadoop
Base RDD which builds and has the graph, for manipulation on that RDD are known
as Transformation.
Lineage graph is stored on driver side where it knows what to store
& where to store.
Apache Spark is an open source cluster computing framework originally developed in
the AMPLab at University of
California, Berkeley but was later donated to the Apache Software Foundation where it
remains today. In contrast to Hadoop's
two-stage disk-based MapReduce paradigm, Spark's multi-stage in-memory
primitives provides performance up to 100 times faster for certain
applications. By allowing user programs to load data into a cluster's memory
and query it repeatedly
Spark
Streaming:-
In Spark Streaming even if one of the nodes fails rest of the nodes can
carry forward the processing on their datasets unlike any other streaming
mechanism where, re-queuing of the entire datasets needs to be done since start
till the time of failure, which leads to data loss situation in this duration.
In streaming we deal totally in Dstream Objects which are internally of
type RDD, over the Dataframes.
Here there is No concept of lazy initialization as the first statement
itself is start(), which is an Action.
During execution of a job i.e. at the time running the job, rest all
activities are halted.
Driver manages all the Meta-Info and receiver passes it to store the
data towards Client.
If a Receiver fails, then it’s the Driver which has capability to
re-start the receiver. Also the only components involved in spark streaming are
Driver & Executor. Therefore, in case where Executor Fiails? Then,
it’s the Driver again who will take care of bringing up the Executor service in
order to provide Fault Tolerance.
And, further in case where Driver itself gets failed? Then, in
this situation we need to manually configure it out by setting Checkpoints() in
HDFS, and by saving the DAG periodically. And here we can also use
getOrCreate() option to priory Checkpoint that DAG is existing or needs to be
created. Make a note here that Checkpoint works only with HDFS where there is
replication data.
Note if Driver goes down then everything goes down i.e. Executors &
Receiver on HDFS side, resulting in loss of data over this period of time.
Whereas in case of executor we have in memory replication, which the driver can
replay in order to overcome the fault, And same be achieved with WAL in case of
Driver.
Spark Streaming has a facility similar to Hbase to overcome the Fault
tolerance called WAL. WAL is created on the executor side, Client uses it in
cases where we want to overcome the fault tolerance.
But in case if we go for using Kafka over Spark then there is no need
of WAL is here we can overcome the same by Kafka inbuilt ability of Replaying()
the log. But here in our case we want Spark itself to provide mechanism and
generate inbuilt capabilities of handling Data Loss. Therefore to achieve the
same in Spark Streaming data is first written to WAL then shared with Kafka.
Spark supports lot of Kafka API as its primarily developed using the
same during its early phases of incubation period. Kafka Direct is one of the
similar facility that enables Spark to read the data based on Offset in order
to process it. And it doesn’t implement the WAL as it is operated based on
OFFSET. Here the concept is that pull the data along with timestamp based on
OFFSET, process the data then increase the timestamp by referencing checkpoint.
Here also OFFSET are only took to serve the purpose of referencing checkpoint
not the data.
Here Kafka is used to remove the concept of Receivers sitting on the
individual nodes to receive data for that very associated node, thereby
enabling us to deal only with Driver and Executors.
Kafka uses the Create Direct Stream to copy the data. Steps to start
Kafka:-
1> Start the Zookeeper.
2> Start the Broker.
3> Get Producer to produce the data
Here in Kafka there is no data replication concept as there are no data
receivers.
Spark already has Boiler Plate Codes available for connectors i.e.
Kafka, Flume, Twitter, etc… Just all what we need to do is copy paste the code.
Make a note over here that here while accepting the messages from these
connectors we deal only in RDD not directly in data.
“_” i.e Underscore, in Scala is used to represent any Random Variable.
Scala also offers an Optional Variable, which is used in the cases
where user is not very sure about the result and is used to represent the state
where the value is optional i.e. whether a value will be returned or not.
FlatMap = Map + Transpose i.e. here we pass a line with N-words as an
input and will receive, M lines with M identical words bearing all the
count of occurrences of the associate word.
Here we go for FlatMap over the Map is that Map understands & deals
only with Key-Value pair, Whereas FlatMap enables us to provide an additional
key i.e. OFFSET on top of these key-value pairs.
In Spark Reduce happens Line by Line in an aggregation fashion unlike
traditional multi-level map-reduce process steps. Also here moving from batch
to spark is fairly more easy, all what we need to do is just mention the
receiving port number additionally. Also here we use the same code for batch by
operating on top of RDD.
In Spark Block Interval refers when to create Partition, Whereas Batch
interval refers when to create RDD. forEachRDD() & repartition() are
very powerful functions associated in dealing with Partitions. updateStateByKey() is
a function which takes another function as an argument.
Pair.Print() is used to print the result parallel.
Transform() is used to process & integrate the streaming data
with the offline data via a handle, by using Joins, Filters, Stats, All data
Cleansing functions, etc…
Window in spark refers to collection of Dstreams Batches, therefore
window must be defined in terms of batches. In case of count by window we don’t
take in consideration the dataset type of receiving data. Windows are used in
cases where we are afraid of data loss.
Incase of reduce by window we have to check the type of window as well
i.e. Key-Value. We can perform Joins on all possible combinations i.e.
Stream-Stream, Window-Window, Stream –Window.
Note:- Flink is more Senior and Advance than Spark in
dealing Streaming, whereas vice versa holds good in case of the batch
Processing.
Here for running any spark streaming its must to checkpoint the data
as spark dosent have any back up mechanism available for it.
Spark
Job Server:-
Spark Job Server is a web service that allows the users to submit &
run spark jobs, chechk their status & view results.
Running Multiple Jobs at same time at same context i.e. getting
multiple spark context under single JVM. Here the concept of the context is
replaced by the concept of Jobs which is different level independent of
context.
Leverages Spark as a query server i.e. use for submitting queries from
different data sources at one single given place.
Is designed to use Spark as a service (REST) i.e. it would be very easy
for any programming language to use the Job Server & integrate with Job
Server.
It allows multiple jobs to share same context and used to achieve high
performance by caching.
It can work with any spark streaming & any spark config.
It allows to persist Application config, Job configuration, Jars, Job
status(Error, Success, Why it Failed) & Job history. And this can be
actually persisted inside the database and by selecting the appropriate JDBC
driver. Also, we can share this database across multiple instances of the Job
server across the several database.
Here we can pass query parameter as a JSON blob or Configuration blob.
It supports both Synchronous & Asynchronous API’s and once the job
is out we returns the JSON format back to the caller.
It gives thread-safe(serialized) API to share the cached RDD & also
it takes care of concurrency i.e. when two jobs try to create same thing then
they done step over each other.
Here the Idea is to create a single shared context & cache the RDD
offering very low latency i.e. execute the query under a second, as multiple
context create multiple process under it which further delays the process &
increases the execution time.
Here we have a Job server which is a rest service. So the first thing
what we are going to do here is create a new Spark Context which internally has
the set of executors. The next thing what we are going to do here is load the
data in cache of our context ex-> load the data from Hbase or Cassandra
& the data then cached, is cached RDD. And once this cached RDD is
available, all what we can do here is start running & executing the query
jobs that run as spark transformation or spark SQL. Which finally returns the
result as JSON blob. Once the cache RDD is ready then we can go for submitting
the query jobs N-Number of time.
Make a note over here that its not the JOB which is responsible to
create spark context rather it’s the Job Server which has to create and manage
the spark context.
Steps
for Installation of Apache Spark:-
1. download scala IDE windows 64 bit
2. download spark pre built with hadoop
3. set ENV varibales:-
SPARK_HOME -> D:\Spark
Installation\1.5.0\spark-1.5.0-bin-hadoop2.6\spark-1.5.0-bin-hadoop2.6
HADOOP_HOME -> D:\winutils
PATH -> D:\Spark
Installation\1.5.0\spark-1.5.0-bin-hadoop2.6\spark-1.5.0-bin-hadoop2.6\bin;C:\Program
Files\Java\jdk1.7.0_79\bin
4. CHECK FROM SPARK-SHELL IF EVERYTHING IS WORKING FINE
FROM YOUR COMMAND PROMPT GO TO: <SPARK_BIN_PATH>/SPARK-SHELL
Note:- Here just type the Drive Name i.e. >D: &
then press Enter button in order to switch Directory.
And then thereafter use cd directory name in order to further
switch the directories. After this now you are ready to use below commands
· Other useful
commands:-
spark-shell -> To start the Spark Shell.
java –version -> To check the installed version of java.
mvn -> To check the Maven installation.
cd ` -> To come out of directory in command prompt.
Note:- While running the program under the Scala IDE, what Error we can
encounter while running the program even after incorporating all the
required Jar?
The Version of Scala & Version of the Library might be different, therefore
in order to overcome this issue what we can do here is that:-
Select the Scala Class -> RC -> BuildPath -> Add Libraries
-> Scala Compiler -> Compiler setting -> Select the appropriate
Compiler Version i.e. 2.10 or 2.11
For running any Spark project we require any of the one thing available
to us i.e.either we need to configure Maven Dependencies in our POM.xml Or, we
need to add the appropriate JAR accordingly. And both can be obtained from
the very same place i.e. MAVEN repository.