2014年6月18日 星期三

Apache Spark學習筆記(1) Quick Start

This tutorial provides a quick introduction to using Spark. We will first introduce the API through Spark’s interactive shell (in Python or Scala), then show how to write standalone applications in Java, Scala, and Python. See the programming guide for a more complete reference.
To follow along with this guide, first download a packaged release of Spark from the Spark website. Since we won’t be using HDFS, you can download a package for any version of Hadoop.

Interactive Analysis with the Spark Shell

Basics

Spark’s shell provides a simple way to learn the API, as well as a powerful tool to analyze data interactively. It is available in either Scala (which runs on the Java VM and is thus a good way to use existing Java libraries) or Python. Start it by running the following in the Spark directory:
./bin/spark-shell

@@在Windows啟動單機模式

c:\> type c:\bat\spark100.bat
@echo off
call c:\bat\jdk7.bat
call c:\bat\scala210.bat
set SPARK_HOME=D:\WORK\spark-1.0.0-bin-cdh4
echo "SPARK_HOME=%SPARK_HOME%"
cd %SPARK_HOME%
.\bin\spark-shell --master local
@@單機模式

.\bin\spark-shell
Spark assembly has been built with Hive, including Datanucleus jars on classpath
14/06/09 11:18:41 INFO SecurityManager: Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
14/06/09 11:18:41 INFO SecurityManager: Changing view acls to: root
14/06/09 11:18:41 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root)
14/06/09 11:18:41 INFO HttpServer: Starting HTTP Server
Welcome to
     ____              __
    / __/__  ___ _____/ /__
   _\ \/ _ \/ _ `/ __/  '_/
  /___/ .__/\_,_/_/ /_/\_\   version 1.0.0
     /_/

Using Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_33)
Type in expressions to have them evaluated.
Type :help for more information.
14/06/09 11:18:45 INFO SecurityManager: Changing view acls to: root
14/06/09 11:18:45 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root)
14/06/09 11:18:45 INFO Slf4jLogger: Slf4jLogger started
14/06/09 11:18:45 INFO Remoting: Starting remoting
14/06/09 11:18:45 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://spark@0a90e21c.cht.local:36909]
14/06/09 11:18:45 INFO Remoting: Remoting now listens on addresses: [akka.tcp://spark@0a90e21c.cht.local:36909]
14/06/09 11:18:45 INFO SparkEnv: Registering MapOutputTracker
14/06/09 11:18:45 INFO SparkEnv: Registering BlockManagerMaster
14/06/09 11:18:45 INFO DiskBlockManager: Created local directory at /tmp/spark-local-20140609111845-878b
14/06/09 11:18:45 INFO MemoryStore: MemoryStore started with capacity 294.4 MB.
14/06/09 11:18:45 INFO ConnectionManager: Bound socket to port 48562 with id = ConnectionManagerId(0a90e21c.cht.local,48562)
14/06/09 11:18:45 INFO BlockManagerMaster: Trying to register BlockManager
14/06/09 11:18:45 INFO BlockManagerInfo: Registering block manager 0a90e21c.cht.local:48562 with 294.4 MB RAM
14/06/09 11:18:45 INFO BlockManagerMaster: Registered BlockManager
14/06/09 11:18:45 INFO HttpServer: Starting HTTP Server
14/06/09 11:18:45 INFO HttpBroadcast: Broadcast server started at http://10.144.226.28:51297
14/06/09 11:18:45 INFO HttpFileServer: HTTP File server directory is /tmp/spark-2f53289e-04f6-4933-984f-3cecc78c1ee0
14/06/09 11:18:45 INFO HttpServer: Starting HTTP Server
14/06/09 11:18:46 INFO SparkUI: Started SparkUI at http://0a90e21c.cht.local:4040
14/06/09 11:18:46 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
14/06/09 11:18:46 INFO Executor: Using REPL class URI: http://10.144.226.28:48202
14/06/09 11:18:46 INFO SparkILoop: Created spark context..
Spark context available as sc.

scala>

Spark’s primary abstraction is a distributed collection of items called a Resilient Distributed Dataset (RDD). RDDs can be created from Hadoop InputFormats (such as HDFS files) or by transforming other RDDs. Let’s make a new RDD from the text of the README file in the Spark source directory:

scala> val textFile = sc.textFile("README.md")
textFile: spark.RDD[String] = spark.MappedRDD@2ee9b6e3
RDDs have actions, which return values, and transformations, which return pointers to new RDDs. Let’s start with a few actions:

scala> textFile.count() // Number of items in this RDD
res0: Long = 126
scala> textFile.first() // First item in this RDD
res1: String = # Apache Spark
Now let’s use a transformation. We will use the filter transformation to return a new RDD with a subset of the items in the file.

scala> val linesWithSpark = textFile.filter(line => line.contains("Spark"))
linesWithSpark: spark.RDD[String] = spark.FilteredRDD@7dd4af09
We can chain together transformations and actions:

scala> textFile.filter(line => line.contains("Spark")).count() // How many lines contain "Spark"?
res3: Long = 15
@@size=3,784,632,000, line=32,000,000
[root@0a90e21c s3log]# ls -l
-rw-r--r-- 1 root root 3784632000 Jun  9 11:21 S3log_2013012901_api1-8_cat
[root@0a90e21c s3log]# wc -l S3log_2013012901_api1-8_cat
32000000 S3log_2013012901_api1-8_cat
[root@0a90e21c s3log]# echo "`date +%Y%m%d%H%M%S.%N`";grep -e "GetObject" S3log_2013012901_api1-8_cat|wc -l;echo "`date +%Y%m%d%H%M%S.%N`"
201406091140.45.876870961
6400000
201406091141.06.133797872
[root@0a90e21c s3log]# echo "`date +%Y%m%d%H%M%S%N`";grep -e "GetObject" S3log_2013012901_api1-8_cat|wc -l;echo "`date +%Y%m%d%H%M%S%N`"
201406091144.26.962698374
6400000
201406091144.47.056321219


scala> val textFile = sc.textFile("/tmp/s3log/S3log_2013012901_api1-8_cat")
14/06/09 11:23:47 INFO MemoryStore: ensureFreeSpace(82970) called with curMem=0, maxMem=308713881
14/06/09 11:23:47 INFO MemoryStore: Block broadcast_0 stored as values to memory (estimated size 81.0 KB, free 294.3 MB)
textFile: org.apache.spark.rdd.RDD[String] = MappedRDD[1] at textFile at <console>:12
scala> textFile.count
14/06/09 11:24:30 INFO SparkContext: Job finished: count at <console>:15, took 3.467692653 s
res0: Long = 32000000
scala> textFile.first
14/06/09 11:28:31 INFO SparkContext: Job finished: first at <console>:15, took 0.02011654 s
res1: String = 20130129000106, user1, user1, 10.144.30.153, 10.144.129.1, user1Bkt1, PutObject, 200, -, 10485760, -, 10485760
scala> textFile.filter(_.contains("GetObject")).count()
14/06/09 11:43:35 INFO SparkContext: Job finished: count at <console>:15, took 3.536027546 s
res3: Long = 6400000
scala> textFile.filter(_.contains("GetObject")).count()
14/06/09 11:44:03 INFO SparkContext: Job finished: count at <console>:15, took 3.305920227 s
res4: Long = 6400000

scala> textFile.cache
res5: textFile.type = MappedRDD[1] at textFile at <console>:12
scala> textFile.filter(_.contains("GetObject")).count()
...
14/06/09 11:46:03 ERROR Executor: Exception in task ID 471
java.lang.OutOfMemoryError: Java heap space
       at scala.collection.mutable.ResizableArray$class.ensureSize(ResizableArray.scala:99)

.

More on RDD Operations

RDD actions and transformations can be used for more complex computations. Let’s say we want to find the line with the most words:
scala> textFile.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b)
res4: Long = 15

scala> textFile.map(_.split(" ").size).reduce((a,b)=>if (a>b) a else b)

This first maps a line to an integer value, creating a new RDD. reduce is called on that RDD to find the largest line count. The arguments to mapand reduce are Scala function literals (closures), and can use any language feature or Scala/Java library. For example, we can easily call functions declared elsewhere. We’ll use Math.max() function to make this code easier to understand:

scala> import java.lang.Math
import java.lang.Math
scala> textFile.map(line => line.split(" ").size).reduce((a, b) => Math.max(a, b))
res5: Int = 15
scala> textFile.map(_.split(" ").size).reduce(Math.max(_,_))

One common data flow pattern is MapReduce, as popularized by Hadoop. Spark can implement MapReduce flows easily:

scala> val wordCounts = textFile.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey((a, b) => a + b)
wordCounts: spark.RDD[(String, Int)] = spark.ShuffledAggregatedRDD@71f027b8
@@ wordcount
("line of file") -split-> ("line","of","file") -map-> (("line",1),("of",1),("file",1)) -flatMap> -reduceByKey-> RDD(("line",2),("of",100),("file"),1)
scala> val wordcounts=textFile.flatMap(_.split(" ").map((_,1))).reduceByKey(_+_)
scala> println(wordcounts.collect.mkString("\n"))
.

Here, we combined the flatMap, map and reduceByKey transformations to compute the per-word counts in the file as an RDD of (String, Int) pairs. To collect the word counts in our shell, we can use the collect action:

scala> wordCounts.collect()
res6: Array[(String, Int)] = Array((means,1), (under,2), (this,3), (Because,1), (Python,2), (agree,1), (cluster.,1), ...)

Caching

Spark also supports pulling data sets into a cluster-wide in-memory cache. This is very useful when data is accessed repeatedly, such as when querying a small “hot” dataset or when running an iterative algorithm like PageRank. As a simple example, let’s mark our linesWithSpark dataset to be cached:

scala> linesWithSpark.cache()
res7: spark.RDD[String] = spark.FilteredRDD@17e51082

scala> linesWithSpark.count()
res8: Long = 15

scala> linesWithSpark.count()
res9: Long = 15
@@size=457,808,000, line=4,000,000
scala> val s3File=sc.textFile("d:/work/myexamples/spark/S3log_2013012900_api01")
@@RDD沒有cache, 查詢時間約11秒

scala> val delobj2 = s3File.filter(_.contains("DeleteObject"))
14/06/04 17:30:28 INFO SparkContext: Job finished: count at <console>:18, took 11.093116473 s
res21: Long = 1600000
scala> val delobj2 = s3File.filter(_.contains("DeleteObject"))
14/06/04 17:31:06 INFO SparkContext: Job finished: count at <console>:18, took 11.383502804 s
res22: Long = 1600000
scala> val delobj2 = s3File.filter(_.contains("DeleteObject"))
14/06/04 17:31:38 INFO SparkContext: Job finished: count at <console>:18, took 11.334071317 s
res23: Long = 1600000
@@RDD cache, 查詢時間1st約14秒, 其後約4秒
scala> val delobj1=s3File.filter(_.contains("DeleteObject"))
scala> delobj1.count()
...
delobj1: org.apache.spark.rdd.RDD[String] = FilteredRDD[26] at filter at <console>:15
scala> delobj1.cache()
res24: delobj1.type = FilteredRDD[26] at filter at <console>:15
14/06/04 17:33:20 INFO SparkContext: Job finished: count at <console>:18, took 14.362551351 s
res25: Long = 1600000
scala> delobj1.count()
...
14/06/04 17:33:53 INFO SparkContext: Job finished: count at <console>:18, took 4.525529811 s
res26: Long = 1600000
scala> delobj1.count()
...
14/06/04 17:34:11 INFO SparkContext: Job finished: count at <console>:18, took 4.049726242 s
res27: Long = 1600000

It may seem silly to use Spark to explore and cache a 100-line text file. The interesting part is that these same functions can be used on very large data sets, even when they are striped across tens or hundreds of nodes. You can also do this interactively by connecting bin/spark-shellto a cluster, as described in the programming guide.

Standalone Applications

Now say we wanted to write a standalone application using the Spark API. We will walk through a simple application in both Scala (with SBT), Java (with Maven), and Python.
We’ll create a very simple Spark application in Scala. So simple, in fact, that it’s named SimpleApp.scala:
/* SimpleApp.scala */
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object SimpleApp {
 def main(args: Array[String]) {
   val logFile = "YOUR_SPARK_HOME/README.md" // Should be some file on your system
   val conf = new SparkConf().setAppName("Simple Application")
   val sc = new SparkContext(conf)
   val logData = sc.textFile(logFile, 2).cache()
   val numAs = logData.filter(line => line.contains("a")).count()
   val numBs = logData.filter(line => line.contains("b")).count()
   println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
 }
}
This program just counts the number of lines containing ‘a’ and the number containing ‘b’ in the Spark README. Note that you’ll need to replace YOUR_SPARK_HOME with the location where Spark is installed. Unlike the earlier examples with the Spark shell, which initializes its own SparkContext, we initialize a SparkContext as part of the program.
We pass the SparkContext constructor a SparkConf object which contains information about our application.
Our application depends on the Spark API, so we’ll also include an sbt configuration file, simple.sbt which explains that Spark is a dependency. This file also adds a repository that Spark depends on:
For sbt to work correctly, we’ll need to layout SimpleApp.scala and simple.sbt according to the typical directory structure. Once that is in place, we can create a JAR package containing the application’s code, then use the spark-submit script to run our program.

# Your directory layout should look like this
$ find .
.
./simple.sbt
./src
./src/main
./src/main/scala
./src/main/scala/SimpleApp.scala

# Package a jar containing your application
$ sbt package
...
[info] Packaging {..}/{..}/target/scala-2.10/simple-project_2.10-1.0.jar

# Use spark-submit to run your application
$ YOUR_SPARK_HOME/bin/spark-submit \
 --class "SimpleApp" \
 --master local[4] \
 target/scala-2.10/simple-project_2.10-1.0.jar
...
Lines with a: 46, Lines with b: 23

org.apache.spark.SparkConf
org.apache.spark.SparkContext
org.apache.spark.rdd.RDD

.

[root@0a90e21c packages]# mkdir -p /tmp/spark/packages/app01/src/main/scala;cd /tmp/spark/packages/app01
[root@0a90e21c app01]# vim src/main/scala/SimpleApp.scala
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object SimpleApp {
 def main(args: Array[String]) {
   val logFile = "/tmp/s3log/S3log_2013012901_api1-8_cat"
   val conf = new SparkConf().setAppName("Simple Application")
   val sc = new SparkContext(conf)
   val logData = sc.textFile(logFile, 2)
   val numAs = logData.filter(line => line.contains("GetObject")).count()
   val numBs = logData.filter(line => line.contains("DeleteObject")).count()
   println("arg1=[%s]".format(args(0)))
   println("Lines with GetObject: %s, Lines with DeleteObject: %s".format(numAs, numBs))
 }
}

[root@0a90e21c app01]# find .
.
./src
./src/main
./src/main/scala
./src/main/scala/SimpleApp.scala
./simple.sbt
[root@0a90e21c app01]# cat simple.sbt
name := "Simple Project"

version := "1.0"

scalaVersion := "2.10.4"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.0.0"
resolvers += "Akka Repository" at "http://repo.akka.io/releases/"

@@compile & package
[root@0a90e21c app01]# sbt package
...
[info] Packaging /tmp/spark/packages/app01/target/scala-2.10/simple-project_2.10-1.0.jar ...
[info] Done packaging.
[success] Total time: 506 s, completed Jun 9, 2014 1:36:37 PM
@@提交程式
[root@0a90e21c app01]# APP_NAME="SimpleApp";$SPARK_HOME/bin/spark-submit \
--class "SimpleApp" \
target/scala-2.10/simple-project_2.10-1.0.jar \
arg0 arg1 \
> $APP_NAME.log 2> $APP_NAME.err &
@@檢視程式stdout
[root@0a90e21c app01]# tail SimpleApp.log
arg1=[arg0]
Lines with GetObject: 6400000, Lines with DeleteObject: 6400000
@@檢視程式stderr
[root@0a90e21c app01]# tail SimpleApp.err
14/06/09 14:00:25 INFO DAGScheduler: Completed ResultTask(1, 108)
14/06/09 14:00:25 INFO TaskSetManager: Finished TID 221 in 467 ms on localhost (progress: 112/113)
14/06/09 14:00:25 INFO Executor: Serialized size of result for 224 is 597
14/06/09 14:00:25 INFO Executor: Sending result for 224 directly to driver
14/06/09 14:00:25 INFO Executor: Finished task ID 224
14/06/09 14:00:25 INFO DAGScheduler: Completed ResultTask(1, 111)
14/06/09 14:00:25 INFO TaskSetManager: Finished TID 224 in 362 ms on localhost (progress: 113/113)
14/06/09 14:00:25 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool
14/06/09 14:00:25 INFO DAGScheduler: Stage 1 (count at SimpleApp.scala:12) finished in 3.256 s
14/06/09 14:00:25 INFO SparkContext: Job finished: count at SimpleApp.scala:12, took 3.288064896 s
@@提交程式
[root@0a90e21c app01]# APP_NAME="SimpleApp";$SPARK_HOME/bin/spark-submit \
--class "SimpleApp" \
--master spark://10.144.226.28:7077 \
target/scala-2.10/simple-project_2.10-1.0.jar \
arg0 arg1 \
> $APP_NAME.log 2> $APP_NAME.err &
vim Simple.err
...
[28] 14/06/09 16:38:06 INFO AppClient$ClientActor: Executor added: app-20140609163806-0000/0 on worker-20140609105100-0a90e21f.cht.local-34804 (0a90e21f.cht.local:34804) with 24 cores
...
[30] 14/06/09 16:38:06 INFO AppClient$ClientActor: Executor added: app-20140609163806-0000/1 on worker-20140609105058-0a90e21d.cht.local-57627 (0a90e21d.cht.local:57627) with 24 cores
...
[32] 14/06/09 16:38:06 INFO AppClient$ClientActor: Executor added: app-20140609163806-0000/2 on worker-20140609105100-0a90e21e.cht.local-37050 (0a90e21e.cht.local:37050) with 24 cores
...
14/06/09 16:38:12 WARN TaskSetManager: Lost TID 15 (task 0.0:15)
14/06/09 16:38:12 WARN TaskSetManager: Loss was due to java.io.FileNotFoundException
java.io.FileNotFoundException: File file:/tmp/s3log/S3log_2013012901_api1-8_cat does not exist
.

.

Where to Go from Here

Congratulations on running your first Spark application!
  • For an in-depth overview of the API, start with the Spark programming guide, or see “Programming Guides” menu for other components.
  • For running applications on a cluster, head to the deployment overview.
  • Finally, Spark includes several samples in the examples directory (Scala, Java, Python). You can run them as follows:
# For Scala and Java, use run-example:
./bin/run-example SparkPi
# For Python examples, use spark-submit directly:
./bin/spark-submit examples/src/main/python/pi.py