-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathspark.py
More file actions
349 lines (286 loc) · 14.7 KB
/
spark.py
File metadata and controls
349 lines (286 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# Copyright (C) 2016 Regents of the University of California
#
# Licensed 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.
import logging
import multiprocessing
import os
import subprocess
import time
from toil.job import Job
from toil.lib.docker import STOP, dockerCheckOutput
_log = logging.getLogger(__name__)
_SPARK_MASTER_PORT = "7077"
def spawn_spark_cluster(job,
numWorkers,
sparkMasterContainer="quay.io/ucsc_cgl/apache-spark-master:1.5.2",
sparkWorkerContainer="quay.io/ucsc_cgl/apache-spark-worker:1.5.2",
cores=None,
memory=None,
disk=None,
overrideLeaderIP=None):
'''
:param numWorkers: The number of worker nodes to have in the cluster. \
Must be greater than or equal to 1.
:param sparkMasterContainer: The Docker image to run for the Spark master.
:param sparkWorkerContainer: The Docker image to run for the Spark worker.
:param cores: Optional parameter to set the number of cores per node. \
If not provided, we use the number of cores on the node that launches \
the service.
:param memory: Optional parameter to set the memory requested per node.
:param disk: Optional parameter to set the disk requested per node.
:type numWorkers: int
:type sparkMasterContainer: str
:type sparkWorkerContainer: str
:type leaderMemory: int or string convertable by bd2k.util.humanize.human2bytes to an int
:type cores: int
:type memory: int or string convertable by bd2k.util.humanize.human2bytes to an int
:type disk: int or string convertable by bd2k.util.humanize.human2bytes to an int
'''
if numWorkers < 1:
raise ValueError("Must have more than one worker. %d given." % numWorkers)
leaderService = SparkService(sparkMasterContainer,
cores=cores,
memory=memory,
disk=disk,
overrideLeaderIP=overrideLeaderIP)
leaderIP = job.addService(leaderService)
for i in range(numWorkers):
job.addService(WorkerService(leaderIP,
sparkWorkerContainer,
cores=cores,
disk=disk,
memory=memory),
parentService=leaderService)
return leaderIP
def _checkContainerStatus(sparkContainerID,
hdfsContainerID,
sparkNoun='leader',
hdfsNoun='namenode'):
containers = subprocess.check_output(["docker", "ps", "-q"])
# docker ps emits shortened versions of the hash
# these shortened hashes are 12 characters long
shortSpark = sparkContainerID[0:11]
shortHdfs = hdfsContainerID[0:11]
if ((sparkContainerID not in containers and
shortSpark not in containers) or
(hdfsContainerID not in containers and
shortHdfs not in containers)):
raise RuntimeError('Lost both Spark %s and HDFS %s.' % (sparkNoun, hdfsNoun))
elif sparkContainerID not in containers and shortSpark not in containers:
raise RuntimeError('Lost Spark %s. %r' % sparkNoun)
elif hdfsContainerID not in containers and shortHdfs not in containers:
raise RuntimeError('Lost HDFS %s. %r' % hdfsNoun)
else:
return True
class SparkService(Job.Service):
"""
A Service job that spins up a Spark cluster that child jobs can then attach
to. If the job that spawns this job is run with `checkpoint = True`, then
this service will robustly restart the Spark cluster upon the loss of any
nodes in the cluster.
"""
def __init__(self,
sparkContainer,
memory=None,
disk=None,
cores=None,
overrideLeaderIP=None):
"""
:param sparkContainer: The Docker container name to run for Spark.
:param memory: The amount of memory to be requested for the Spark leader. Optional.
:param disk: The amount of disk to be requested for the Spark leader. Optional.
:param cores: Optional parameter to set the number of cores per node. \
If not provided, we use the number of cores on the node that launches \
the service.
:type sparkContainer: str
:type memory: int or string convertable by bd2k.util.humanize.human2bytes to an int
:type disk: int or string convertable by bd2k.util.humanize.human2bytes to an int
:type cores: int
"""
if cores is None:
cores = multiprocessing.cpu_count()
self.hostname = overrideLeaderIP
self.sparkContainer = sparkContainer
Job.Service.__init__(self, memory=memory, cores=cores, disk=disk)
def start(self, job):
"""
Start spark and hdfs master containers
:param job: The underlying job.
"""
if self.hostname is None:
self.hostname = subprocess.check_output(["hostname", "-f",])[:-1]
_log.info("Started Spark master container.")
self.sparkContainerID = dockerCheckOutput(job=job,
defer=STOP,
workDir=os.getcwd(),
tool=self.sparkContainer,
dockerParameters=["--net=host",
"-d",
"-v", "/var/run/docker.sock:/var/run/docker.sock",
"-v", "/mnt/ephemeral/:/ephemeral/:rw",
"-e", "SPARK_MASTER_IP=" + self.hostname,
"-e", "SPARK_LOCAL_DIRS=/ephemeral/spark/local",
"-e", "SPARK_WORKER_DIR=/ephemeral/spark/work"],
parameters=[self.hostname])[:-1]
_log.info("Started HDFS Datanode.")
self.hdfsContainerID = dockerCheckOutput(job=job,
defer=STOP,
workDir=os.getcwd(),
tool="quay.io/ucsc_cgl/apache-hadoop-master:2.6.2",
dockerParameters=["--net=host",
"-d"],
parameters=[self.hostname])[:-1]
return self.hostname
def stop(self, job):
"""
Stop and remove spark and hdfs master containers
:param job: The underlying job.
"""
subprocess.call(["docker", "exec", self.sparkContainerID, "rm", "-r", "/ephemeral/spark"])
subprocess.call(["docker", "stop", self.sparkContainerID])
subprocess.call(["docker", "rm", self.sparkContainerID])
_log.info("Stopped Spark master.")
subprocess.call(["docker", "stop", self.hdfsContainerID])
subprocess.call(["docker", "rm", self.hdfsContainerID])
_log.info("Stopped HDFS namenode.")
return
def check(self):
"""
Checks to see if Spark master and HDFS namenode are still running.
"""
status = _checkContainerStatus(self.sparkContainerID, self.hdfsContainerID)
return status
class WorkerService(Job.Service):
"""
Service Job that implements the worker nodes in a Spark/HDFS cluster.
Should not be called outside of `SparkService`.
"""
def __init__(self, masterIP, sparkContainer, memory=None, cores=None, disk=None):
"""
:param masterIP: The IP of the Spark master.
:param sparkContainer: The container to run for Spark.
:param memory: The memory requirement for each node in the cluster. Optional.
:param disk: The disk requirement for each node in the cluster. Optional.
:param cores: Optional parameter to set the number of cores per node. \
If not provided, we use the number of cores on the node that launches \
the service.
:type masterIP: str
:type sparkContainer: str
:type memory: int or string convertable by bd2k.util.humanize.human2bytes to an int
:type disk: int or string convertable by bd2k.util.humanize.human2bytes to an int
:type cores: int
"""
self.masterIP = masterIP
self.sparkContainer = sparkContainer
if cores is None:
cores = multiprocessing.cpu_count()
Job.Service.__init__(self, memory=memory, cores=cores, disk=disk)
def start(self, job):
"""
Start spark and hdfs worker containers
:param job: The underlying job.
"""
# start spark and our datanode
self.sparkContainerID = dockerCheckOutput(job=job,
defer=STOP,
workDir=os.getcwd(),
tool=self.sparkContainer,
dockerParameters=["--net=host",
"-d",
"-v", "/var/run/docker.sock:/var/run/docker.sock",
"-v", "/mnt/ephemeral/:/ephemeral/:rw",
"-e",
"\"SPARK_MASTER_IP=" + self.masterIP + ":" + _SPARK_MASTER_PORT + "\"",
"-e", "SPARK_LOCAL_DIRS=/ephemeral/spark/local",
"-e", "SPARK_WORKER_DIR=/ephemeral/spark/work"],
parameters=[self.masterIP + ":" + _SPARK_MASTER_PORT])[:-1]
self.__start_datanode(job)
# fake do/while to check if HDFS is up
hdfs_down = True
retries = 0
while hdfs_down and (retries < 5):
_log.info("Sleeping 30 seconds before checking HDFS startup.")
time.sleep(30)
clusterID = ""
try:
clusterID = subprocess.check_output(["docker",
"exec",
self.hdfsContainerID,
"grep",
"clusterID",
"-R",
"/opt/apache-hadoop/logs"])
except:
# grep returns a non-zero exit code if the pattern is not found
# we expect to not find the pattern, so a non-zero code is OK
pass
if "Incompatible" in clusterID:
_log.warning("Hadoop Datanode failed to start with: %s", clusterID)
_log.warning("Retrying container startup, retry #%d.", retries)
retries += 1
_log.warning("Removing ephemeral hdfs directory.")
subprocess.check_call(["docker",
"exec",
self.hdfsContainerID,
"rm",
"-rf",
"/ephemeral/hdfs"])
_log.warning("Killing container %s.", self.hdfsContainerID)
subprocess.check_call(["docker",
"kill",
self.hdfsContainerID])
# todo: this is copied code. clean up!
_log.info("Restarting datanode.")
self.__start_datanode(job)
else:
_log.info("HDFS datanode started up OK!")
hdfs_down = False
if retries >= 5:
raise RuntimeError("Failed %d times trying to start HDFS datanode." % retries)
return
def __start_datanode(self, job):
"""
Launches the Hadoop datanode.
:param job: The underlying job.
"""
self.hdfsContainerID = dockerCheckOutput(job=job,
defer=STOP,
workDir=os.getcwd(),
tool="quay.io/ucsc_cgl/apache-hadoop-worker:2.6.2",
dockerParameters=["--net=host",
"-d",
"-v", "/mnt/ephemeral/:/ephemeral/:rw"],
parameters=[self.masterIP])[:-1]
def stop(self, fileStore):
"""
Stop spark and hdfs worker containers
:param job: The underlying job.
"""
subprocess.call(["docker", "exec", self.sparkContainerID, "rm", "-r", "/ephemeral/spark"])
subprocess.call(["docker", "stop", self.sparkContainerID])
subprocess.call(["docker", "rm", self.sparkContainerID])
_log.info("Stopped Spark worker.")
subprocess.call(["docker", "exec", self.hdfsContainerID, "rm", "-r", "/ephemeral/hdfs"])
subprocess.call(["docker", "stop", self.hdfsContainerID])
subprocess.call(["docker", "rm", self.hdfsContainerID])
_log.info("Stopped HDFS datanode.")
return
def check(self):
"""
Checks to see if Spark worker and HDFS datanode are still running.
"""
status = _checkContainerStatus(self.sparkContainerID,
self.hdfsContainerID,
sparkNoun='worker',
hdfsNoun='datanode')
return status