2013-07-16 20:21:33 -04:00
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
#
|
|
|
|
|
2012-08-10 04:10:02 -04:00
|
|
|
import os
|
2013-01-21 19:42:24 -05:00
|
|
|
import shutil
|
2013-01-23 13:36:18 -05:00
|
|
|
import sys
|
|
|
|
from threading import Lock
|
2012-08-10 04:10:02 -04:00
|
|
|
from tempfile import NamedTemporaryFile
|
|
|
|
|
2013-01-20 04:57:44 -05:00
|
|
|
from pyspark import accumulators
|
|
|
|
from pyspark.accumulators import Accumulator
|
2012-08-25 16:59:01 -04:00
|
|
|
from pyspark.broadcast import Broadcast
|
2013-01-23 13:36:18 -05:00
|
|
|
from pyspark.files import SparkFiles
|
2012-08-10 04:10:02 -04:00
|
|
|
from pyspark.java_gateway import launch_gateway
|
2012-12-29 18:34:57 -05:00
|
|
|
from pyspark.serializers import dump_pickle, write_with_length, batched
|
2013-09-07 17:41:31 -04:00
|
|
|
from pyspark.storagelevel import StorageLevel
|
2012-08-18 19:07:10 -04:00
|
|
|
from pyspark.rdd import RDD
|
2012-08-10 04:10:02 -04:00
|
|
|
|
2012-08-25 21:00:25 -04:00
|
|
|
from py4j.java_collections import ListConverter
|
|
|
|
|
2012-08-10 04:10:02 -04:00
|
|
|
|
|
|
|
class SparkContext(object):
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
|
|
|
Main entry point for Spark functionality. A SparkContext represents the
|
|
|
|
connection to a Spark cluster, and can be used to create L{RDD}s and
|
|
|
|
broadcast variables on that cluster.
|
|
|
|
"""
|
2012-08-10 04:10:02 -04:00
|
|
|
|
2013-02-01 14:09:56 -05:00
|
|
|
_gateway = None
|
|
|
|
_jvm = None
|
|
|
|
_writeIteratorToPickleFile = None
|
|
|
|
_takePartition = None
|
2013-01-20 04:57:44 -05:00
|
|
|
_next_accum_id = 0
|
2013-01-23 13:36:18 -05:00
|
|
|
_active_spark_context = None
|
|
|
|
_lock = Lock()
|
2013-08-15 19:01:19 -04:00
|
|
|
_python_includes = None # zip and egg files that need to be added to PYTHONPATH
|
2012-08-10 04:10:02 -04:00
|
|
|
|
2012-12-27 22:59:04 -05:00
|
|
|
def __init__(self, master, jobName, sparkHome=None, pyFiles=None,
|
|
|
|
environment=None, batchSize=1024):
|
|
|
|
"""
|
|
|
|
Create a new SparkContext.
|
|
|
|
|
|
|
|
@param master: Cluster URL to connect to
|
|
|
|
(e.g. mesos://host:port, spark://host:port, local[4]).
|
|
|
|
@param jobName: A name for your job, to display on the cluster web UI
|
|
|
|
@param sparkHome: Location where Spark is installed on cluster nodes.
|
|
|
|
@param pyFiles: Collection of .zip or .py files to send to the cluster
|
|
|
|
and add to PYTHONPATH. These can be paths on the local file
|
|
|
|
system or HDFS, HTTP, HTTPS, or FTP URLs.
|
|
|
|
@param environment: A dictionary of environment variables to set on
|
|
|
|
worker nodes.
|
|
|
|
@param batchSize: The number of Python objects represented as a single
|
|
|
|
Java object. Set 1 to disable batching or -1 to use an
|
|
|
|
unlimited batch size.
|
|
|
|
"""
|
2013-01-23 13:36:18 -05:00
|
|
|
with SparkContext._lock:
|
|
|
|
if SparkContext._active_spark_context:
|
|
|
|
raise ValueError("Cannot run multiple SparkContexts at once")
|
|
|
|
else:
|
|
|
|
SparkContext._active_spark_context = self
|
2013-02-01 14:09:56 -05:00
|
|
|
if not SparkContext._gateway:
|
|
|
|
SparkContext._gateway = launch_gateway()
|
|
|
|
SparkContext._jvm = SparkContext._gateway.jvm
|
|
|
|
SparkContext._writeIteratorToPickleFile = \
|
|
|
|
SparkContext._jvm.PythonRDD.writeIteratorToPickleFile
|
|
|
|
SparkContext._takePartition = \
|
|
|
|
SparkContext._jvm.PythonRDD.takePartition
|
2012-08-10 04:10:02 -04:00
|
|
|
self.master = master
|
2012-12-27 22:59:04 -05:00
|
|
|
self.jobName = jobName
|
|
|
|
self.sparkHome = sparkHome or None # None becomes null in Py4J
|
|
|
|
self.environment = environment or {}
|
2012-12-26 20:34:24 -05:00
|
|
|
self.batchSize = batchSize # -1 represents a unlimited batch size
|
2012-12-27 22:59:04 -05:00
|
|
|
|
|
|
|
# Create the Java SparkContext through Py4J
|
2013-02-01 14:09:56 -05:00
|
|
|
empty_string_array = self._gateway.new_array(self._jvm.String, 0)
|
|
|
|
self._jsc = self._jvm.JavaSparkContext(master, jobName, sparkHome,
|
2012-12-27 22:59:04 -05:00
|
|
|
empty_string_array)
|
|
|
|
|
2013-01-20 04:57:44 -05:00
|
|
|
# Create a single Accumulator in Java that we'll send all our updates through;
|
|
|
|
# they will be passed back to us through a TCP server
|
|
|
|
self._accumulatorServer = accumulators._start_update_server()
|
|
|
|
(host, port) = self._accumulatorServer.server_address
|
|
|
|
self._javaAccumulator = self._jsc.accumulator(
|
2013-02-01 14:09:56 -05:00
|
|
|
self._jvm.java.util.ArrayList(),
|
|
|
|
self._jvm.PythonAccumulatorParam(host, port))
|
2013-01-20 04:57:44 -05:00
|
|
|
|
2013-01-10 10:45:12 -05:00
|
|
|
self.pythonExec = os.environ.get("PYSPARK_PYTHON", 'python')
|
2012-08-25 16:59:01 -04:00
|
|
|
# Broadcast's __reduce__ method stores Broadcast instances here.
|
|
|
|
# This allows other code to determine which Broadcast instances have
|
|
|
|
# been pickled, so it can determine which Java broadcast objects to
|
|
|
|
# send.
|
|
|
|
self._pickled_broadcast_vars = set()
|
2012-08-10 04:10:02 -04:00
|
|
|
|
2013-08-15 19:01:19 -04:00
|
|
|
SparkFiles._sc = self
|
|
|
|
root_dir = SparkFiles.getRootDirectory()
|
|
|
|
sys.path.append(root_dir)
|
|
|
|
|
2012-12-27 22:59:04 -05:00
|
|
|
# Deploy any code dependencies specified in the constructor
|
2013-08-15 19:01:19 -04:00
|
|
|
self._python_includes = list()
|
2012-12-27 22:59:04 -05:00
|
|
|
for path in (pyFiles or []):
|
|
|
|
self.addPyFile(path)
|
|
|
|
|
2013-02-01 14:48:11 -05:00
|
|
|
# Create a temporary directory inside spark.local.dir:
|
2013-09-01 03:32:28 -04:00
|
|
|
local_dir = self._jvm.org.apache.spark.util.Utils.getLocalDir()
|
2013-02-01 14:48:11 -05:00
|
|
|
self._temp_dir = \
|
2013-09-01 03:32:28 -04:00
|
|
|
self._jvm.org.apache.spark.util.Utils.createTempDir(local_dir).getAbsolutePath()
|
2013-02-01 14:48:11 -05:00
|
|
|
|
2012-12-27 22:59:04 -05:00
|
|
|
@property
|
|
|
|
def defaultParallelism(self):
|
|
|
|
"""
|
|
|
|
Default level of parallelism to use when not given by user (e.g. for
|
|
|
|
reduce tasks)
|
|
|
|
"""
|
|
|
|
return self._jsc.sc().defaultParallelism()
|
|
|
|
|
2012-08-10 04:10:02 -04:00
|
|
|
def __del__(self):
|
2013-01-23 13:36:18 -05:00
|
|
|
self.stop()
|
2012-08-10 04:10:02 -04:00
|
|
|
|
|
|
|
def stop(self):
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
|
|
|
Shut down the SparkContext.
|
|
|
|
"""
|
2013-01-23 13:36:18 -05:00
|
|
|
if self._jsc:
|
|
|
|
self._jsc.stop()
|
|
|
|
self._jsc = None
|
|
|
|
if self._accumulatorServer:
|
|
|
|
self._accumulatorServer.shutdown()
|
|
|
|
self._accumulatorServer = None
|
|
|
|
with SparkContext._lock:
|
|
|
|
SparkContext._active_spark_context = None
|
2012-08-10 04:10:02 -04:00
|
|
|
|
2012-08-18 19:07:10 -04:00
|
|
|
def parallelize(self, c, numSlices=None):
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
|
|
|
Distribute a local Python collection to form an RDD.
|
2013-07-29 00:09:11 -04:00
|
|
|
|
|
|
|
>>> sc.parallelize(range(5), 5).glom().collect()
|
|
|
|
[[0], [1], [2], [3], [4]]
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
2012-08-10 04:10:02 -04:00
|
|
|
numSlices = numSlices or self.defaultParallelism
|
2012-08-18 19:07:10 -04:00
|
|
|
# Calling the Java parallelize() method with an ArrayList is too slow,
|
|
|
|
# because it sends O(n) Py4J commands. As an alternative, serialized
|
|
|
|
# objects are written to a file and loaded through textFile().
|
2013-02-01 14:48:11 -05:00
|
|
|
tempFile = NamedTemporaryFile(delete=False, dir=self._temp_dir)
|
2013-07-29 00:09:11 -04:00
|
|
|
# Make sure we distribute data evenly if it's smaller than self.batchSize
|
|
|
|
if "__len__" not in dir(c):
|
|
|
|
c = list(c) # Make it a list so we can compute its length
|
|
|
|
batchSize = min(len(c) // numSlices, self.batchSize)
|
|
|
|
if batchSize > 1:
|
|
|
|
c = batched(c, batchSize)
|
2012-08-18 19:07:10 -04:00
|
|
|
for x in c:
|
2012-08-25 19:46:07 -04:00
|
|
|
write_with_length(dump_pickle(x), tempFile)
|
2012-08-10 04:10:02 -04:00
|
|
|
tempFile.close()
|
2013-02-01 14:09:56 -05:00
|
|
|
readRDDFromPickleFile = self._jvm.PythonRDD.readRDDFromPickleFile
|
|
|
|
jrdd = readRDDFromPickleFile(self._jsc, tempFile.name, numSlices)
|
2012-08-18 19:07:10 -04:00
|
|
|
return RDD(jrdd, self)
|
2012-08-10 04:10:02 -04:00
|
|
|
|
2012-08-25 16:59:01 -04:00
|
|
|
def textFile(self, name, minSplits=None):
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
|
|
|
Read a text file from HDFS, a local file system (available on all
|
|
|
|
nodes), or any Hadoop-supported file system URI, and return it as an
|
|
|
|
RDD of Strings.
|
|
|
|
"""
|
2012-08-25 16:59:01 -04:00
|
|
|
minSplits = minSplits or min(self.defaultParallelism, 2)
|
|
|
|
jrdd = self._jsc.textFile(name, minSplits)
|
2012-08-18 19:07:10 -04:00
|
|
|
return RDD(jrdd, self)
|
2012-08-25 16:59:01 -04:00
|
|
|
|
2013-01-20 16:59:45 -05:00
|
|
|
def _checkpointFile(self, name):
|
|
|
|
jrdd = self._jsc.checkpointFile(name)
|
|
|
|
return RDD(jrdd, self)
|
|
|
|
|
2012-08-25 21:00:25 -04:00
|
|
|
def union(self, rdds):
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
2012-12-27 22:59:04 -05:00
|
|
|
Build the union of a list of RDDs.
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
2012-08-25 21:00:25 -04:00
|
|
|
first = rdds[0]._jrdd
|
|
|
|
rest = [x._jrdd for x in rdds[1:]]
|
|
|
|
rest = ListConverter().convert(rest, self.gateway._gateway_client)
|
|
|
|
return RDD(self._jsc.union(first, rest), self)
|
|
|
|
|
2012-08-25 16:59:01 -04:00
|
|
|
def broadcast(self, value):
|
2012-12-27 20:55:33 -05:00
|
|
|
"""
|
|
|
|
Broadcast a read-only variable to the cluster, returning a C{Broadcast}
|
|
|
|
object for reading it in distributed functions. The variable will be
|
|
|
|
sent to each cluster only once.
|
|
|
|
"""
|
2012-08-25 19:46:07 -04:00
|
|
|
jbroadcast = self._jsc.broadcast(bytearray(dump_pickle(value)))
|
2012-10-19 13:24:49 -04:00
|
|
|
return Broadcast(jbroadcast.id(), value, jbroadcast,
|
2012-08-25 16:59:01 -04:00
|
|
|
self._pickled_broadcast_vars)
|
2012-12-27 22:59:04 -05:00
|
|
|
|
2013-01-20 04:57:44 -05:00
|
|
|
def accumulator(self, value, accum_param=None):
|
|
|
|
"""
|
2013-01-20 18:12:54 -05:00
|
|
|
Create an L{Accumulator} with the given initial value, using a given
|
|
|
|
L{AccumulatorParam} helper object to define how to add values of the
|
|
|
|
data type if provided. Default AccumulatorParams are used for integers
|
|
|
|
and floating-point numbers if you do not provide one. For other types,
|
|
|
|
a custom AccumulatorParam can be used.
|
2013-01-20 04:57:44 -05:00
|
|
|
"""
|
|
|
|
if accum_param == None:
|
|
|
|
if isinstance(value, int):
|
|
|
|
accum_param = accumulators.INT_ACCUMULATOR_PARAM
|
|
|
|
elif isinstance(value, float):
|
|
|
|
accum_param = accumulators.FLOAT_ACCUMULATOR_PARAM
|
|
|
|
elif isinstance(value, complex):
|
|
|
|
accum_param = accumulators.COMPLEX_ACCUMULATOR_PARAM
|
|
|
|
else:
|
|
|
|
raise Exception("No default accumulator param for type %s" % type(value))
|
|
|
|
SparkContext._next_accum_id += 1
|
|
|
|
return Accumulator(SparkContext._next_accum_id - 1, value, accum_param)
|
|
|
|
|
2012-12-27 22:59:04 -05:00
|
|
|
def addFile(self, path):
|
|
|
|
"""
|
2013-01-21 19:42:24 -05:00
|
|
|
Add a file to be downloaded with this Spark job on every node.
|
|
|
|
The C{path} passed can be either a local file, a file in HDFS
|
|
|
|
(or other Hadoop-supported filesystems), or an HTTP, HTTPS or
|
|
|
|
FTP URI.
|
|
|
|
|
|
|
|
To access the file in Spark jobs, use
|
|
|
|
L{SparkFiles.get(path)<pyspark.files.SparkFiles.get>} to find its
|
|
|
|
download location.
|
|
|
|
|
|
|
|
>>> from pyspark import SparkFiles
|
|
|
|
>>> path = os.path.join(tempdir, "test.txt")
|
|
|
|
>>> with open(path, "w") as testFile:
|
|
|
|
... testFile.write("100")
|
|
|
|
>>> sc.addFile(path)
|
|
|
|
>>> def func(iterator):
|
|
|
|
... with open(SparkFiles.get("test.txt")) as testFile:
|
|
|
|
... fileVal = int(testFile.readline())
|
|
|
|
... return [x * 100 for x in iterator]
|
|
|
|
>>> sc.parallelize([1, 2, 3, 4]).mapPartitions(func).collect()
|
|
|
|
[100, 200, 300, 400]
|
2012-12-27 22:59:04 -05:00
|
|
|
"""
|
|
|
|
self._jsc.sc().addFile(path)
|
|
|
|
|
|
|
|
def clearFiles(self):
|
|
|
|
"""
|
|
|
|
Clear the job's list of files added by L{addFile} or L{addPyFile} so
|
|
|
|
that they do not get downloaded to any new nodes.
|
|
|
|
"""
|
|
|
|
# TODO: remove added .py or .zip files from the PYTHONPATH?
|
|
|
|
self._jsc.sc().clearFiles()
|
|
|
|
|
|
|
|
def addPyFile(self, path):
|
|
|
|
"""
|
|
|
|
Add a .py or .zip dependency for all tasks to be executed on this
|
|
|
|
SparkContext in the future. The C{path} passed can be either a local
|
|
|
|
file, a file in HDFS (or other Hadoop-supported filesystems), or an
|
|
|
|
HTTP, HTTPS or FTP URI.
|
|
|
|
"""
|
|
|
|
self.addFile(path)
|
2013-08-15 19:01:19 -04:00
|
|
|
(dirname, filename) = os.path.split(path) # dirname may be directory or HDFS/S3 prefix
|
|
|
|
|
|
|
|
if filename.endswith('.zip') or filename.endswith('.ZIP') or filename.endswith('.egg'):
|
|
|
|
self._python_includes.append(filename)
|
|
|
|
sys.path.append(os.path.join(SparkFiles.getRootDirectory(), filename)) # for tests in local mode
|
2013-01-16 22:15:14 -05:00
|
|
|
|
|
|
|
def setCheckpointDir(self, dirName, useExisting=False):
|
|
|
|
"""
|
2013-01-20 18:31:41 -05:00
|
|
|
Set the directory under which RDDs are going to be checkpointed. The
|
|
|
|
directory must be a HDFS path if running on a cluster.
|
|
|
|
|
|
|
|
If the directory does not exist, it will be created. If the directory
|
|
|
|
exists and C{useExisting} is set to true, then the exisiting directory
|
|
|
|
will be used. Otherwise an exception will be thrown to prevent
|
|
|
|
accidental overriding of checkpoint files in the existing directory.
|
2013-01-16 22:15:14 -05:00
|
|
|
"""
|
|
|
|
self._jsc.sc().setCheckpointDir(dirName, useExisting)
|
2013-01-21 19:42:24 -05:00
|
|
|
|
2013-09-07 17:41:31 -04:00
|
|
|
def _getJavaStorageLevel(self, storageLevel):
|
|
|
|
"""
|
|
|
|
Returns a Java StorageLevel based on a pyspark.StorageLevel.
|
|
|
|
"""
|
|
|
|
if not isinstance(storageLevel, StorageLevel):
|
|
|
|
raise Exception("storageLevel must be of type pyspark.StorageLevel")
|
|
|
|
|
|
|
|
newStorageLevel = self._jvm.org.apache.spark.storage.StorageLevel
|
|
|
|
return newStorageLevel(storageLevel.useDisk, storageLevel.useMemory,
|
|
|
|
storageLevel.deserialized, storageLevel.replication)
|
|
|
|
|
2013-01-21 19:42:24 -05:00
|
|
|
def _test():
|
2013-02-01 14:48:11 -05:00
|
|
|
import atexit
|
2013-01-21 19:42:24 -05:00
|
|
|
import doctest
|
2013-02-01 14:48:11 -05:00
|
|
|
import tempfile
|
2013-01-21 19:42:24 -05:00
|
|
|
globs = globals().copy()
|
|
|
|
globs['sc'] = SparkContext('local[4]', 'PythonTest', batchSize=2)
|
|
|
|
globs['tempdir'] = tempfile.mkdtemp()
|
|
|
|
atexit.register(lambda: shutil.rmtree(globs['tempdir']))
|
2013-02-03 01:44:11 -05:00
|
|
|
(failure_count, test_count) = doctest.testmod(globs=globs)
|
2013-01-21 19:42:24 -05:00
|
|
|
globs['sc'].stop()
|
2013-02-03 01:44:11 -05:00
|
|
|
if failure_count:
|
|
|
|
exit(-1)
|
2013-01-21 19:42:24 -05:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
_test()
|