-
Notifications
You must be signed in to change notification settings - Fork 55
/
dispyscheduler.py
executable file
·2310 lines (2156 loc) · 99.7 KB
/
dispyscheduler.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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""
dispyscheduler: Schedule jobs to nodes running 'dispynode'; needed
when multiple processes may use same nodes simultaneously with
SharedJobCluster; see accompanying 'dispy' for more details.
"""
import os
import sys
import time
import socket
import stat
import re
import ssl
import atexit
import traceback
import tempfile
import shutil
import glob
import pickle
import hashlib
import struct
import platform
try:
import netifaces
except ImportError:
netifaces = None
import pycos
from pycos import Task, Pycos, AsyncSocket, Singleton, serialize, deserialize
import dispy
import dispy.httpd
import dispy.config
from dispy.config import MsgTimeout, MaxFileSize
from dispy import _Compute, DispyJob, _DispyJob_, _Node, DispyNode, NodeAllocate, \
_JobReply, auth_code, num_min, _parse_node_allocs, _XferFile, _dispy_version, \
_same_file, _node_ipaddr, logger
__author__ = "Giridhar Pemmasani (pgiri@yahoo.com)"
__email__ = "pgiri@yahoo.com"
__copyright__ = "Copyright 2011, Giridhar Pemmasani"
__contributors__ = []
__maintainer__ = "Giridhar Pemmasani (pgiri@yahoo.com)"
__license__ = "Apache 2.0"
__url__ = "https://dispy.org"
__status__ = "Production"
__version__ = _dispy_version
__all__ = []
# PyPI / pip packaging adjusts assertion below for Python 3.7+
assert sys.version_info.major == 3 and sys.version_info.minor < 7, \
('\n\n This file is not suitable for Python version %s.%s directly;\n'
' see installation instructions at %s\n' %
(sys.version_info.major, sys.version_info.minor, __url__))
class _Cluster(object):
"""Internal use only.
"""
def __init__(self, compute, node_allocs, scheduler):
self._compute = compute
# self.name = compute.name
self.name = '%s @ %s' % (compute.name, compute.scheduler_ip_addr)
self._node_allocs = _parse_node_allocs(node_allocs)
self._node_allocs = sorted(self._node_allocs, key=lambda na: na.ip_rex, reverse=True)
for na in self._node_allocs:
for dep in na.depends:
dep.compute_id = compute.id
self.scheduler = scheduler
self.cluster_status = None
self.pending_jobs = 0
self.pending_results = 0
self._jobs = []
self._dispy_nodes = {}
self.cpu_time = 0
self.start_time = time.time()
self.end_time = None
self.job_sched_time = 0
self.zombie = False
self.exclusive = False
self.last_pulse = time.time()
self.client_ip_addr = None
self.client_port = None
self.client_sock_family = None
self.client_job_result_port = None
self.client_auth = None
self.ip_addr = None
self.dest_path = None
self.file_uses = {}
def __getstate__(self):
state = dict(self.__dict__)
for var in ('_node_allocs', 'scheduler', 'cluster_status', '_jobs', '_dispy_nodes'):
state.pop(var, None)
return state
def node_jobs(self, node, from_node=False, task=None):
jobs = Task(self.scheduler.node_jobs, self, node, from_node, get_uids=False).value()
return jobs
def cancel(self, job):
return self.scheduler.cancel_job(self, job.id)
def allocate_node(self, node_alloc):
if not isinstance(node_alloc, list):
node_alloc = [node_alloc]
node_allocs = _parse_node_allocs(node_alloc)
Task(self.scheduler.allocate_node, self, node_allocs)
def set_node_cpus(self, node, cpus):
return Task(self.scheduler.set_node_cpus, node, cpus).value()
class _Scheduler(object, metaclass=Singleton):
"""Internal use only.
See dispy's JobCluster and SharedJobCluster for documentation.
"""
def __init__(self, nodes=[], hosts=[], ext_hosts=[], ipv4_udp_multicast=False,
pulse_interval=None, ping_interval=None, cooperative=False, cleanup_nodes=False,
node_secret='', cluster_secret='', node_keyfile=None, node_certfile=None,
cluster_keyfile=None, cluster_certfile=None, dest_path_prefix=None, clean=False,
scheduler_alg=None, zombie_interval=60, http_server=False):
self.ipv4_udp_multicast = bool(ipv4_udp_multicast)
self.addrinfos = []
if not hosts:
hosts = [None]
for i in range(len(hosts)):
addrinfo = dispy.host_addrinfo(host=hosts[i], ipv4_multicast=self.ipv4_udp_multicast)
if not addrinfo:
logger.warning('Ignoring invalid host %s', hosts[i])
continue
if i < len(ext_hosts):
ext_host = dispy._node_ipaddr(ext_hosts[i])
if ext_host:
addrinfo.ext_ip = ext_host
else:
logger.warning('Ignoring invalid ext_host %s', ext_hosts[i])
self.addrinfos.append(addrinfo)
if not self.addrinfos:
raise Exception('No valid IP address found')
self.ip_addrs = []
self.port = eval(dispy.config.ClientPort)
self.node_port = eval(dispy.config.NodePort)
self.scheduler_port = eval(dispy.config.SharedSchedulerPort)
if not nodes:
nodes = ['*']
self._node_allocs = _parse_node_allocs(nodes)
self._nodes = {}
self.node_secret = node_secret
self.node_keyfile = node_keyfile
self.node_certfile = node_certfile
self.cluster_secret = cluster_secret
self.cluster_keyfile = cluster_keyfile
self.cluster_certfile = cluster_certfile
if not dest_path_prefix:
dest_path_prefix = os.path.join(tempfile.gettempdir(), 'dispy', 'scheduler')
self.dest_path_prefix = os.path.abspath(dest_path_prefix.strip()).rstrip(os.sep)
if clean:
shutil.rmtree(self.dest_path_prefix, ignore_errors=True)
if not os.path.isdir(self.dest_path_prefix):
os.makedirs(self.dest_path_prefix)
os.chmod(self.dest_path_prefix, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
self.cooperative = bool(cooperative)
self.cleanup_nodes = bool(cleanup_nodes)
if pulse_interval:
try:
self.pulse_interval = float(pulse_interval)
assert 0.1 <= self.pulse_interval <= 1000
except Exception:
raise Exception('Invalid pulse_interval; must be between 0.1 and 1000')
else:
self.pulse_interval = None
if ping_interval:
try:
self.ping_interval = float(ping_interval)
assert 1.0 <= self.ping_interval <= 1000
except Exception:
raise Exception('Invalid ping_interval; must be between 1 and 1000')
else:
self.ping_interval = None
if zombie_interval:
self.zombie_interval = 60 * zombie_interval
if self.pulse_interval:
self.pulse_interval = min(self.pulse_interval, self.zombie_interval / 5.0)
else:
self.pulse_interval = self.zombie_interval / 5.0
else:
self.zombie_interval = None
self.pycos = Pycos()
atexit.register(self.shutdown)
self._clusters = {}
self.unsched_clusters = []
self.pending_clusters = {}
self._sched_jobs = {}
self._sched_event = pycos.Event()
# once a _job is done (i.e., final result for it is
# received from node), it is added to done_jobs, so same
# object is not reused by Python (when a new job is
# submitted) until the result is sent back to client
# (otherwise, 'id' may be duplicate)
self.done_jobs = {}
self.terminate = False
self.sign = hashlib.sha1(os.urandom(20))
for addrinfo in self.addrinfos:
self.sign.update(addrinfo.ip.encode())
self.sign = self.sign.hexdigest()
self.cluster_auth = auth_code(self.cluster_secret, self.sign)
self.node_auth = auth_code(self.node_secret, self.sign)
with open(os.path.join(self.dest_path_prefix, 'config'), 'wb') as fd:
config = {
'hosts': [ai.ip for ai in self.addrinfos],
'ext_hosts': [ai.ext_ip for ai in self.addrinfos],
'port': self.port, 'sign': self.sign,
'cluster_secret': self.cluster_secret, 'cluster_auth': self.cluster_auth,
'node_secret': self.node_secret, 'node_auth': self.node_auth
}
pickle.dump(config, fd)
if scheduler_alg == 'fair_cluster':
self.select_job_node_cluster = self.fair_cluster_schedule
elif scheduler_alg == 'fcfs_cluster':
self.select_job_node_cluster = self.fcfs_cluster_schedule
else:
self.select_job_node_cluster = self.fsfs_job_schedule
self.start_time = time.time()
if http_server:
self.httpd = dispy.httpd.DispyHTTPServer(None)
else:
self.httpd = None
self.timer_task = Task(self.timer_proc)
self.job_scheduler_task = Task(self._schedule_jobs)
self.tcp_tasks = []
self.udp_tasks = []
self.scheduler_tasks = []
udp_addrinfos = {}
for addrinfo in self.addrinfos:
self.tcp_tasks.append(Task(self.tcp_server, addrinfo))
self.scheduler_tasks.append(Task(self.scheduler_server, addrinfo))
if os.name == 'nt':
bind_addr = addrinfo.ip
elif sys.platform == 'darwin':
if addrinfo.family == socket.AF_INET and (not self.ipv4_udp_multicast):
bind_addr = ''
else:
bind_addr = addrinfo.broadcast
else:
bind_addr = addrinfo.broadcast
udp_addrinfos[bind_addr] = addrinfo
for bind_addr, addrinfo in udp_addrinfos.items():
self.udp_tasks.append(Task(self.udp_server, bind_addr, addrinfo))
def udp_server(self, bind_addr, addrinfo, task=None):
task.set_daemon()
udp_sock = AsyncSocket(socket.socket(addrinfo.family, socket.SOCK_DGRAM))
udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, 'SO_REUSEPORT'):
try:
udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except Exception:
pass
while not self.port:
yield task.sleep(0.2)
udp_sock.bind((bind_addr, self.port))
if addrinfo.family == socket.AF_INET:
if self.ipv4_udp_multicast:
mreq = socket.inet_aton(addrinfo.broadcast) + socket.inet_aton(addrinfo.ip)
udp_sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
else: # addrinfo.family == socket.AF_INET6:
mreq = socket.inet_pton(addrinfo.family, addrinfo.broadcast)
mreq += struct.pack('@I', addrinfo.ifn)
udp_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
try:
udp_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
except Exception:
pass
Task(self.broadcast_ping, addrinfos=[addrinfo])
self.send_ping_cluster(self._node_allocs, set())
while 1:
msg, addr = yield udp_sock.recvfrom(1000)
if msg.startswith(b'PING:'):
try:
info = deserialize(msg[len(b'PING:'):])
if info['version'] != _dispy_version:
logger.warning('Ignoring %s due to version mismatch', addr[0])
continue
assert info['port'] > 0
assert info['ip_addr']
# socket.inet_aton(status['ip_addr'])
except Exception:
logger.debug('Ignoring node %s', addr[0])
logger.debug(traceback.format_exc())
continue
if info['port'] == self.port:
continue
auth = auth_code(self.node_secret, info['sign'])
node = self._nodes.get(info['ip_addr'], None)
if node:
if node.auth == auth:
continue
sock = AsyncSocket(socket.socket(addrinfo.family, socket.SOCK_STREAM),
keyfile=self.node_keyfile, certfile=self.node_certfile)
sock.settimeout(MsgTimeout)
msg = {'port': self.port, 'sign': self.sign, 'version': _dispy_version}
msg['ip_addrs'] = self.ip_addrs
try:
yield sock.connect((info['ip_addr'], info['port']))
yield sock.sendall(auth)
yield sock.send_msg(b'PING:' + serialize(msg))
except Exception:
logger.debug(traceback.format_exc())
finally:
sock.close()
elif msg.startswith(b'TERMINATED:'):
try:
info = deserialize(msg[len(b'TERMINATED:'):])
node = self._nodes[info['ip_addr']]
assert node.auth == auth_code(self.secret, info['sign'])
except Exception:
# logger.debug(traceback.format_exc())
pass
else:
self.delete_node(node)
else:
pass
def tcp_server(self, addrinfo, task=None):
# generator
task.set_daemon()
sock = socket.socket(addrinfo.family, socket.SOCK_STREAM)
sock = AsyncSocket(sock, keyfile=self.node_keyfile, certfile=self.node_certfile)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((addrinfo.ip, self.port))
except Exception:
logger.debug('Could not bind TCP to %s:%s', addrinfo.ip, self.port)
raise StopIteration
logger.debug('TCP server at %s:%s', addrinfo.ip, self.port)
self.ip_addrs.append(addrinfo.ip)
sock.listen(32)
while 1:
try:
conn, addr = yield sock.accept()
except ssl.SSLError as err:
logger.debug('SSL connection failed: %s', str(err))
continue
except GeneratorExit:
break
except Exception:
logger.debug(traceback.format_exc())
continue
Task(self.tcp_req, conn, addr)
def tcp_req(self, conn, addr, task=None):
# generator
conn.settimeout(MsgTimeout)
msg = yield conn.recv_msg()
if msg.startswith(b'JOB_REPLY:'):
try:
info = deserialize(msg[len(b'JOB_REPLY:'):])
except Exception:
logger.warning('Invalid job reply from %s:%s ignored', addr[0], addr[1])
else:
yield self.job_reply_process(info, len(msg), conn, addr)
conn.close()
elif msg.startswith(b'PULSE:'):
msg = msg[len(b'PULSE:'):]
try:
info = deserialize(msg)
except Exception:
logger.warning('Ignoring pulse message from %s', addr[0])
conn.close()
raise StopIteration
node = self._nodes.get(info['ip_addr'], None)
if node:
# assert 0 <= info['cpus'] <= node.cpus
node.last_pulse = time.time()
yield conn.send_msg(b'PULSE')
if info['avail_info']:
node.avail_info = info['avail_info']
for cluster in node.clusters:
dispy_node = cluster._dispy_nodes.get(node.ip_addr, None)
if dispy_node:
dispy_node.avail_info = info['avail_info']
dispy_node.update_time = node.last_pulse
Task(self.send_node_status, cluster, dispy_node, DispyNode.AvailInfo)
if cluster.cluster_status:
cluster.cluster_status(DispyNode.AvailInfo, dispy_node, None)
conn.close()
elif msg.startswith(b'PONG:'):
conn.close()
try:
info = deserialize(msg[len(b'PONG:'):])
assert info['auth'] == self.node_auth
except Exception:
logger.warning('Ignoring node %s due to "secret" mismatch', addr[0])
else:
self.add_node(info)
elif msg.startswith(b'PING:'):
sock_family = conn.family
conn.close()
try:
info = deserialize(msg[len(b'PING:'):])
if info['version'] != _dispy_version:
logger.warning('Ignoring node %s due to version mismatch', addr[0])
raise Exception('')
assert info['port'] > 0
assert info['ip_addr']
except Exception:
logger.debug('Ignoring node %s', addr[0])
logger.debug(traceback.format_exc())
raise StopIteration
if info['port'] != self.port:
auth = auth_code(self.node_secret, info['sign'])
node = self._nodes.get(info['ip_addr'], None)
if node:
if node.auth == auth:
raise StopIteration
sock = AsyncSocket(socket.socket(sock_family, socket.SOCK_STREAM),
keyfile=self.node_keyfile, certfile=self.node_certfile)
sock.settimeout(MsgTimeout)
msg = {'port': self.port, 'sign': self.sign, 'version': _dispy_version}
msg['ip_addrs'] = self.ip_addrs
try:
yield sock.connect((info['ip_addr'], info['port']))
yield sock.sendall(auth)
yield sock.send_msg(b'PING:' + serialize(msg))
except Exception:
logger.debug(traceback.format_exc())
finally:
sock.close()
elif msg.startswith(b'FILEXFER:'):
try:
xf = deserialize(msg[len(b'FILEXFER:'):])
msg = yield conn.recv_msg()
job_reply = deserialize(msg)
yield self.xfer_to_client(job_reply, xf, conn, addr)
except Exception:
logger.debug(traceback.format_exc())
conn.close()
elif msg.startswith(b'TERMINATED:'):
conn.close()
try:
info = deserialize(msg[len(b'TERMINATED:'):])
node = self._nodes[info['ip_addr']]
assert node.auth == auth_code(self.secret, info['sign'])
except Exception:
# logger.debug(traceback.format_exc())
pass
else:
self.delete_node(node)
elif msg.startswith(b'NODE_CPUS:'):
conn.close()
try:
info = deserialize(msg[len(b'NODE_CPUS:'):])
node = self._nodes.get(info['ip_addr'], None)
if not node:
raise StopIteration
auth = auth_code(self.node_secret, info['sign'])
if auth != node.auth:
logger.warning('Invalid signature from %s', node.ip_addr)
raise StopIteration
cpus = info['cpus']
except Exception:
logger.debug(traceback.format_exc())
raise StopIteration
if cpus < 0:
logger.warning('Node requested using %s CPUs, disabling it', node.ip_addr, cpus)
cpus = 0
logger.debug('Setting cpus for %s to %s', node.ip_addr, cpus)
# TODO: set node.cpus to min(cpus, node.cpus)?
node.cpus = cpus
if cpus > node.avail_cpus:
node.avail_cpus = cpus
setup_computations = []
for cluster in self._clusters.values():
if cluster in node.clusters:
continue
compute = cluster._compute
for node_alloc in cluster._node_allocs:
cpus = node_alloc.allocate(cluster, node.ip_addr, node.name,
node.avail_cpus)
if cpus <= 0:
continue
if cluster.exclusive or self.cooperative:
node.cpus = min(node.avail_cpus, cpus)
setup_computations.append((node_alloc.depends, node_alloc.setup_args,
compute))
break
if setup_computations:
Task(self.setup_node, node, setup_computations)
yield self._sched_event.set()
else:
node.avail_cpus = cpus
for cluster in node.clusters:
dispy_node = cluster._dispy_nodes.get(node.ip_addr, None)
if dispy_node:
dispy_node.cpus = cpus
elif msg.startswith(b'RELAY_INFO:'):
try:
info = deserialize(msg[len(b'RELAY_INFO:'):])
assert info['version'] == _dispy_version
msg = {'sign': self.sign, 'ip_addrs': [info['scheduler_ip_addr']],
'port': self.port}
if 'auth' in info and info['auth'] != self.node_auth:
msg = None
except Exception:
msg = None
yield conn.send_msg(serialize(msg))
conn.close()
else:
logger.warning('Invalid message from %s:%s ignored', addr[0], addr[1])
conn.close()
def schedule_cluster(self, task=None):
while self.unsched_clusters:
cluster = self.unsched_clusters[0]
if self._clusters:
if cluster.exclusive:
raise StopIteration
for cur_cluster in self._clusters.values():
if cur_cluster.exclusive:
raise StopIteration
break
self.unsched_clusters.pop(0)
reply_sock = socket.socket(cluster.client_sock_family, socket.SOCK_STREAM)
reply_sock = AsyncSocket(reply_sock, keyfile=self.cluster_keyfile,
certfile=self.cluster_certfile)
reply_sock.settimeout(MsgTimeout)
reply = {'compute_id': cluster._compute.id, 'pulse_interval': self.pulse_interval}
self._clusters[cluster._compute.id] = cluster
try:
yield reply_sock.connect((cluster.client_ip_addr, cluster.client_job_result_port))
yield reply_sock.send_msg('SCHEDULED:'.encode() + serialize(reply))
msg = yield reply_sock.recv_msg()
assert msg == 'ACK'.encode()
self.add_cluster(cluster)
except Exception:
self._clusters.pop(cluster._compute.id, None)
logger.debug('Ignoring computation %s / %s from %s:%s',
cluster._compute.name, cluster._compute.id,
cluster.client_ip_addr, cluster.client_job_result_port)
continue
finally:
reply_sock.close()
def scheduler_server(self, addrinfo, task=None):
task.set_daemon()
sock = socket.socket(addrinfo.family, socket.SOCK_STREAM)
sock = AsyncSocket(sock, keyfile=self.cluster_keyfile, certfile=self.cluster_certfile)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((addrinfo.ip, self.scheduler_port))
except Exception:
logger.warning('Could not bind scheduler server to %s:%s',
addrinfo.ip, self.scheduler_port)
raise StopIteration
logger.debug('Scheduler at %s:%s', addrinfo.ip, self.scheduler_port)
sock.listen(32)
while 1:
conn, addr = yield sock.accept()
Task(self.scheduler_req, conn, addr)
def scheduler_req(self, conn, addr, task=None):
# generator
def _job_request(self, cluster, node, _job):
# generator
_job.uid = id(_job)
for xf in _job.xfer_files:
xf.name = os.path.join(cluster.dest_path, xf.dest_path.replace(xf.sep, os.sep),
xf.name.split(xf.sep)[-1])
xf.sep = os.sep
job = DispyJob(None, (), {})
job.id = _job.uid
_job.job = job
yield conn.send_msg(serialize(_job.uid))
ack = yield conn.recv_msg()
if ack != b'ACK':
raise StopIteration
if node:
_job.pinned = node
node.pending_jobs.append(_job)
else:
_job.pinned = None
cluster._jobs.append(_job)
logger.debug('Submitted job %s / %s', _job.uid, job.submit_time)
cluster.pending_jobs += 1
cluster.last_pulse = job.submit_time
self._sched_event.set()
if cluster.cluster_status:
cluster.cluster_status(DispyJob.Created, None, job)
def _compute_req(self, msg):
# function
try:
req = deserialize(msg)
compute = req['compute']
node_allocs = req['node_allocs']
exclusive = req['exclusive']
except Exception:
return serialize(('Invalid computation').encode())
compute.id = id(compute)
for xf in compute.xfer_files:
if MaxFileSize and xf.stat_buf.st_size > MaxFileSize:
return serialize(('File "%s" is too big; limit is %s' %
(xf.name, MaxFileSize)).encode())
xf.compute_id = compute.id
if self.terminate:
return serialize(('Scheduler is closing').encode())
if self.cleanup_nodes and not compute.cleanup:
compute.cleanup = True
cluster = _Cluster(compute, node_allocs, self)
cluster.ip_addr = conn.getsockname()[0]
cluster.exclusive = exclusive
dest = compute.scheduler_ip_addr
if os.name == 'nt':
dest = dest.replace(':', '_')
dest = os.path.join(self.dest_path_prefix, dest)
if not os.path.isdir(dest):
try:
os.mkdir(dest)
except Exception:
return serialize(('Could not create destination directory').encode())
if compute.dest_path and isinstance(compute.dest_path, str):
# TODO: get os.sep from client and convert (in case of mixed environments)?
if compute.dest_path.startswith(os.sep):
cluster.dest_path = compute.dest_path
else:
cluster.dest_path = os.path.join(dest, compute.dest_path)
if not os.path.isdir(cluster.dest_path):
try:
os.makedirs(cluster.dest_path)
except Exception:
return serialize(('Could not create destination directory').encode())
else:
cluster.dest_path = tempfile.mkdtemp(prefix=compute.name + '_', dir=dest)
cluster.client_job_result_port = compute.job_result_port
cluster.client_ip_addr = compute.scheduler_ip_addr
cluster.client_port = compute.scheduler_port
cluster.client_sock_family = conn.family
cluster.client_auth = compute.auth
compute.job_result_port = self.port
compute.scheduler_port = self.port
compute.auth = hashlib.sha1(os.urandom(10)).hexdigest()
cluster.last_pulse = time.time()
for xf in compute.xfer_files:
xf.compute_id = compute.id
xf.name = os.path.join(cluster.dest_path, xf.dest_path.replace(xf.sep, os.sep),
xf.name.split(xf.sep)[-1])
xf.sep = os.sep
with open(os.path.join(self.dest_path_prefix,
'%s_%s' % (compute.id, cluster.client_auth)), 'wb') as fd:
pickle.dump(cluster, fd)
self.pending_clusters[cluster._compute.id] = cluster
logger.debug('New computation %s: %s, %s',
compute.id, compute.name, cluster.dest_path)
return serialize({'compute_id': cluster._compute.id, 'auth': cluster.client_auth})
def xfer_from_client(self, msg):
# generator
try:
xf = deserialize(msg)
except Exception:
logger.debug('Ignoring file trasnfer request from %s', addr[0])
raise StopIteration(serialize(-1))
cluster = self.pending_clusters.get(xf.compute_id, None)
if not cluster:
# if file is transfered for 'dispy_job_depends', cluster would be active
cluster = self._clusters.get(xf.compute_id, None)
if not cluster:
logger.error('Computation "%s" is invalid', xf.compute_id)
raise StopIteration(serialize(-1))
tgt = os.path.join(cluster.dest_path, xf.dest_path.replace(xf.sep, os.sep),
xf.name.split(xf.sep)[-1])
if os.path.isfile(tgt) and _same_file(tgt, xf):
if tgt in cluster.file_uses:
cluster.file_uses[tgt] += 1
else:
cluster.file_uses[tgt] = 2
raise StopIteration(serialize(xf.stat_buf.st_size))
logger.debug('Copying file %s to %s (%s)', xf.name, tgt, xf.stat_buf.st_size)
try:
if not os.path.isdir(os.path.dirname(tgt)):
os.makedirs(os.path.dirname(tgt))
with open(tgt, 'wb') as fd:
recvd = 0
while recvd < xf.stat_buf.st_size:
yield conn.send_msg(serialize(recvd))
data = yield conn.recvall(min(xf.stat_buf.st_size-recvd, 1024000))
if not data:
break
fd.write(data)
recvd += len(data)
assert recvd == xf.stat_buf.st_size
os.utime(tgt, (xf.stat_buf.st_atime, xf.stat_buf.st_mtime))
os.chmod(tgt, stat.S_IMODE(xf.stat_buf.st_mode))
if tgt in cluster.file_uses:
cluster.file_uses[tgt] += 1
else:
cluster.file_uses[tgt] = 1
logger.debug('Copied file %s', tgt)
except Exception:
logger.warning('Copying file "%s" failed with "%s"',
xf.name, traceback.format_exc())
recvd = -1
try:
os.remove(tgt)
if len(os.listdir(cluster.dest_path)) == 0:
os.rmdir(cluster.dest_path)
except Exception:
pass
raise StopIteration(serialize(recvd))
def send_file(self, msg):
# generator
try:
msg = deserialize(msg)
node = self._nodes.get(msg['node'], None)
xf = msg['xf']
except Exception:
logger.debug('Ignoring file trasnfer request from %s', addr[0])
raise StopIteration(serialize(-1))
cluster = self._clusters.get(xf.compute_id, None)
if not cluster or not node:
logger.error('send_file "%s" is invalid', xf.name)
raise StopIteration(serialize(-1))
dispy_node = cluster._dispy_nodes.get(node.ip_addr)
if not dispy_node:
logger.error('send_file "%s" is invalid', xf.name)
raise StopIteration(serialize(-1))
if _same_file(xf.name, xf):
resp = yield node.xfer_file(xf)
if resp < 0:
raise StopIteration(serialize(-1))
else:
node.tx += resp
dispy_node.tx += resp
raise StopIteration(serialize(xf.stat_buf.st_size))
node_sock = AsyncSocket(socket.socket(node.sock_family, socket.SOCK_STREAM),
keyfile=self.node_keyfile, certfile=self.node_certfile)
node_sock.settimeout(MsgTimeout)
try:
yield node_sock.connect((node.ip_addr, node.port))
yield node_sock.sendall(node.auth)
yield node_sock.send_msg('FILEXFER:'.encode() + serialize(xf))
recvd = yield node_sock.recv_msg()
recvd = deserialize(recvd)
while recvd < xf.stat_buf.st_size:
yield conn.send_msg(serialize(recvd))
data = yield conn.recvall(min(xf.stat_buf.st_size-recvd, 1024000))
if not data:
break
yield node_sock.sendall(data)
recvd = yield node_sock.recv_msg()
recvd = deserialize(recvd)
node.tx += recvd
dispy_node.tx += recvd
except Exception:
logger.error('Could not transfer %s to %s: %s', xf.name, node.ip_addr, recvd)
logger.debug(traceback.format_exc())
# TODO: mark this node down, reschedule on different node?
recvd = -1
finally:
node_sock.close()
raise StopIteration(serialize(recvd))
# scheduler_req begins here
conn.settimeout(MsgTimeout)
resp = None
try:
req = yield conn.recvall(len(self.cluster_auth))
except Exception:
logger.warning('Failed to read message from %s: %s', str(addr), traceback.format_exc())
conn.close()
raise StopIteration
if req != self.cluster_auth:
msg = yield conn.recv_msg()
if msg.startswith(b'CLIENT:'):
try:
req = deserialize(msg[len(b'CLIENT:'):])
if req['version'] != _dispy_version:
logger.warning('Ignoring %s due to version mismatch', addr[0])
raise Exception('')
if not req['ip_addr']:
req['ip_addr'] = addr[0]
reply = {'ip_addr': req['ip_addr'], 'port': self.scheduler_port,
'sign': self.sign, 'version': _dispy_version}
yield conn.send_msg(serialize(reply))
except Exception:
pass
else:
logger.warning('Invalid/unauthorized request ignored')
conn.close()
raise StopIteration
msg = yield conn.recv_msg()
if not msg:
logger.info('Closing connection')
conn.close()
raise StopIteration
if msg.startswith(b'JOB:'):
msg = msg[len(b'JOB:'):]
try:
req = deserialize(msg)
_job = req['job']
cluster = self._clusters[_job.compute_id]
assert cluster.client_auth == req['auth']
node = req['node']
if node:
node = self._nodes[node]
except Exception:
pass
else:
yield _job_request(self, cluster, node, _job)
resp = None
elif msg.startswith(b'PULSE:'):
msg = msg[len(b'PULSE:'):]
try:
info = deserialize(msg)
except Exception:
logger.warning('Ignoring pulse message from %s', addr[0])
conn.close()
raise StopIteration
if 'client_port' in info:
for cluster in self._clusters.values():
if (cluster.client_ip_addr == addr[0] and
cluster.client_port == info['client_port']):
cluster.last_pulse = time.time()
conn.close()
elif msg.startswith(b'COMPUTE:'):
msg = msg[len(b'COMPUTE:'):]
resp = _compute_req(self, msg)
elif msg.startswith(b'SCHEDULE:'):
msg = msg[len(b'SCHEDULE:'):]
try:
req = deserialize(msg)
cluster = self.pending_clusters[req['compute_id']]
assert cluster.client_auth == req['auth']
for xf in cluster._compute.xfer_files:
assert os.path.isfile(xf.name)
self.unsched_clusters.append(cluster)
self.pending_clusters.pop(cluster._compute.id)
except Exception:
logger.debug('Ignoring schedule request from %s', addr[0])
resp = 'NAK'.encode()
else:
resp = 'ACK'.encode()
Task(self.schedule_cluster)
elif msg.startswith(b'CLOSE:'):
msg = msg[len(b'CLOSE:'):]
try:
req = deserialize(msg)
auth = req['auth']
except Exception:
logger.warning('Invalid compuation for deleting')
conn.close()
raise StopIteration
cluster = self._clusters.get(req['compute_id'], None)
if cluster is None or cluster.client_auth != auth:
# this cluster is closed
conn.close()
raise StopIteration
cluster.zombie = True
terminate_pending = req.get('terminate_pending', False)
Task(self.cleanup_computation, cluster, terminate_pending=bool(terminate_pending))
elif msg.startswith(b'FILEXFER:'):
msg = msg[len(b'FILEXFER:'):]
resp = yield xfer_from_client(self, msg)
elif msg.startswith(b'SENDFILE:'):
msg = msg[len(b'SENDFILE:'):]
resp = yield send_file(self, msg)
elif msg.startswith(b'NODE_JOBS:'):
msg = msg[len(b'NODE_JOBS:'):]
try:
req = deserialize(msg)
cluster = self._clusters.get(req['compute_id'], None)
if cluster is None or cluster.client_auth != req['auth']:
job_uids = []
else:
node = req['node']
from_node = req['from_node']
# assert req['get_uids'] == True
job_uids = yield self.node_jobs(cluster, node, from_node,
get_uids=True, task=task)
except Exception:
job_uids = []
resp = serialize(job_uids)
elif msg.startswith(b'TERMINATE_JOB:'):
msg = msg[len(b'TERMINATE_JOB:'):]
try:
req = deserialize(msg)
uid = req['uid']
cluster = self._clusters[req['compute_id']]
assert cluster.client_auth == req['auth']
except Exception:
logger.warning('Invalid job cancel message')
conn.close()
raise StopIteration
self.cancel_job(cluster, uid)
elif msg.startswith(b'RESEND_JOB_RESULTS:'):
msg = msg[len(b'RESEND_JOB_RESULTS:'):]
try:
info = deserialize(msg)
compute_id = info['compute_id']
auth = info['auth']
except Exception:
resp = serialize(0)
else:
cluster = self._clusters.get(compute_id, None)
if cluster is None or cluster.client_auth != auth:
try:
with open(os.path.join(self.dest_path_prefix,
'%s_%s' % (compute_id, auth)), 'rb') as fd:
cluster = pickle.load(fd)
except Exception:
pass
if cluster is None:
resp = 0
else:
resp = cluster.pending_results + cluster.pending_jobs
yield conn.send_msg(serialize(resp))
conn.close()
if resp > 0:
yield self.resend_job_results(cluster, task=task)
raise StopIteration
elif msg.startswith(b'PENDING_JOBS:'):
msg = msg[len(b'PENDING_JOBS:'):]
reply = {'done': [], 'pending': 0}
try:
info = deserialize(msg)
compute_id = info['compute_id']
auth = info['auth']
except Exception:
pass
else:
cluster = self._clusters.get(compute_id, None)
if cluster is None or cluster.client_auth != auth:
with open(os.path.join(self.dest_path_prefix,
'%s_%s' % (compute_id, auth)), 'rb') as fd:
cluster = pickle.load(fd)
if cluster is not None and cluster.client_auth == auth:
done = []
if cluster.pending_results:
for result_file in glob.glob(os.path.join(cluster.dest_path,
'_dispy_job_reply_*')):
result_file = os.path.basename(result_file)
try:
uid = int(result_file[len('_dispy_job_reply_'):])
except Exception:
pass
else:
done.append(uid)
# limit so as not to take up too much time
if len(done) > 50: