-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallel.py
197 lines (183 loc) · 6.43 KB
/
parallel.py
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
"""
Main master parallelization code. Functionality for claiming a cluster, and sending map/apply jobs.
"""
import cPickle
import multiprocessing
import random
import socket
import string
import subprocess
import sys
import time
import xmlrpclib
import zlib
import zmq
from common import *
ALL_INSTS = []
AVAILABLE = []
UNAVAILABLE = []
MAP_NUM = 0
APL_NUM = 0
CTX = zmq.Context()
if CONF['fast']:
map_snd = CTX.socket(zmq.PUSH)
map_rcv = CTX.socket(zmq.PULL)
else:
map_snd = CTX.socket(zmq.PUB)
map_rcv = CTX.socket(zmq.ROUTER)
map_rcv.RCVTIMEO = CONF['map_timeout']
apl_rdy = CTX.socket(zmq.PUB)
apl_wkr = CTX.socket(zmq.ROUTER)
apl_wkr.RCVTIMEO = CONF['apply_timeout']
def claim_cluster(name):
global ALL_INSTS, AVAILABLE, UNAVAILABLE
cluster = get_instances(name)
if not cluster:
raise ValueError(colorize("Cluster '{}' does not exist".format(name)))
ALL_INSTS = cluster.keys()
AVAILABLE = ALL_INSTS[:]
ports = []
sock = CTX.socket(zmq.REQ)
for _ in range(4):
ports.append(sock.bind_to_random_port('tcp://*'))
sock.close()
proxies = {}
for inst, info in cluster.items():
proxies[inst] = xmlrpclib.ServerProxy('http://{}:8000'.format(info['ext_ip']))
print("Claiming cluster '{}'...".format(name))
for inst, proxy in proxies.items():
try:
rc = proxy.run(sys.argv[0], sys.argv[1:], ports)
except socket.error:
print colorize("WARNING: could not connect to '{}'".format(inst))
UNAVAILABLE.append(inst)
AVAILABLE.remove(inst)
continue # TODO: do some error handling
if type(rc) is list:
if rc[0] == sys.argv:
ports = rc[1]
break
else:
raise ValueError(colorize("Cluster '{}' is already claimed".format(name)))
elif rc != SUCCESS:
UNAVAILABLE.append(inst)
AVAILABLE.remove(inst)
map_snd.bind('tcp://*:{}'.format(ports[0]))
map_rcv.bind('tcp://*:{}'.format(ports[1]))
apl_rdy.bind('tcp://*:{}'.format(ports[2]))
apl_wkr.bind('tcp://*:{}'.format(ports[3]))
def fast_parallel_map(func, args_lst):
result_lst = []
chunked = []
chunk_size = 1 # (len(args_lst) // len(ALL_INSTS)) + 1
for i in range(0, len(args_lst), chunk_size):
chunk = args_lst[i:i+chunk_size]
chunked.append(chunk)
chunks = range(len(chunked))
time.sleep(20) #TODO: well this ain't no good
for ch in chunks:
print 'sending chunk ' + str(ch)
map_snd.send(cPickle.dumps((ch, func, chunked[ch])))
all_chunks = set(chunks)
received = set()
while True:
while True:
try:
result_str = map_rcv.recv()
except zmq.error.Again:
break
chunk, result = cPickle.loads(result_str)
print 'received results for chunk ' + str(chunk)
received.add(chunk)
result_lst.extend(result)
if len(result_lst) == len(args_lst):
return result_lst
for ch in all_chunks - received:
print 'resending chunk {}'.format(ch)
map_snd.send(cPickle.dumps((ch, func, chunked[ch])))
def reliable_parallel_map(func, args_lst):
global MAP_NUM
MAP_NUM += 1
chunked = []
chunk_size = 1 # (len(args_lst) // len(ALL_INSTS)) + 1
for i in range(0, len(args_lst), chunk_size):
chunked.append(args_lst[i:i+chunk_size])
num_chunks = len(chunked)
result_lst = [None for _ in range(num_chunks)]
sent = [False for _ in range(num_chunks)]
ch = 0
num_fails = 0
while True:
map_snd.send(cPickle.dumps(MAP_NUM))
try:
id, _, msg = map_rcv.recv_multipart()
except zmq.error.Again:
num_fails += 1
print colorize('num fails: {}'.format(num_fails))
if num_fails == 100:
for ch in range(len(chunked)):
if result_lst[ch] is None:
sent[ch] = False
continue
if id in UNAVAILABLE:
map_rcv.send_multipart([id, b'', END_MSG])
continue
if msg != RDY_MSG:
s, chunk, results = cPickle.loads(zlib.decompress(msg))
if s != MAP_NUM:
map_rcv.send_multipart([id, b'', END_MSG])
continue
if result_lst[chunk] is None:
print 'received results for chunk ' + str(chunk)
num_chunks -= 1
result_lst[chunk] = results
if num_chunks == 0:
break
if not all(sent):
while sent[ch]:
ch = (ch + 1) % len(chunked)
msg = cPickle.dumps((MAP_NUM, ch, func, chunked[ch]))
sent[ch] = True
print 'sending chunk ' + str(ch)
map_rcv.send_multipart([id, b'', msg])
ch = (ch + 1) % len(chunked)
for id in AVAILABLE:
map_rcv.send_multipart([id, b'', END_MSG])
return [item for chunk in result_lst for item in chunk]
parallel_map = fast_parallel_map if CONF['fast'] else reliable_parallel_map
def apply_on_all_insts(func, args):
global AVAILABLE, UNAVAILABLE, APL_NUM
APL_NUM += 1
wf(colorize('applying on slaves... ', 'yellow'))
insts_left = ALL_INSTS[:]
results = []
func_call = cPickle.dumps((APL_NUM, func, args))
for _ in range(CONF['apply_tries']):
apl_rdy.send(b'')
while True:
try:
id, _, msg = apl_wkr.recv_multipart()
except zmq.error.Again:
break
if msg == RDY_MSG:
apl_wkr.send_multipart([id, b'', func_call])
else:
result = cPickle.loads(zlib.decompress(msg))
results.append(result)
apl_wkr.send_multipart([id, b'', END_MSG])
insts_left.remove(id)
if not insts_left:
UNAVAILABLE = []
AVAILABLE = ALL_INSTS[:]
print(colorize('done', 'green'))
return results
if not CONF['fast']:
for id in insts_left:
map_rcv.send_multipart([id, b'', END_MSG])
UNAVAILABLE = insts_left
AVAILABLE = list(set(ALL_INSTS) - set(UNAVAILABLE))
if not AVAILABLE:
raise ValueError('No instances available')
print(colorize('done', 'green'))
print(colorize('UNAVAILABLE: {}'.format(UNAVAILABLE)))
return results