forked from mhulsman/cluster_manager
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cluster
executable file
·1573 lines (1394 loc) · 56.6 KB
/
cluster
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/env python
import curses, curses.textpad, curses.ascii
import os
import subprocess, sys, getopt, time,shlex
from subprocess import Popen
import thread
import threading
import cluster_storage
from collections import defaultdict
import sysv_ipc
import socket
from dns import resolver,reversename
from SimpleXMLRPCServer import SimpleXMLRPCServer
import random
import psutil
import shutil
import numpy
import datetime
from IPython.parallel import Client
WHITE=0
RED=1
GREEN=2
YELLOW=3
MAGENTA=4
BLUE=5
CYAN=6
TIMEOUT = 1200
PURGE_INTERVAL = 1800
_DEFAULT_SEMAPHORE_KEY = 691990
_SEMAPHORE_VALUE = 100
#current screen info
class gb:
scr = None
lock = None
wlog = None
wlog_currow = 0
wlog_size = (0,0)
wcom = None
wcom_status = None
wstatus = None
wstatus_progress = None
class status:
envname = None
address = None
port = None
iport = None
recover = False
lock = None
semaphore = None
semaphore_key = _DEFAULT_SEMAPHORE_KEY
controller = False
controller_monitor = None
taskclient = None
queue_status = defaultdict(int)
queue_ids = None
controller_cpu = 0.0
controller_mem = 0.0
local_engines = []
pbs_engines = []
pbs_stats = (0,0,0)
grid_engines = []
grid_engines_count = []
grid_status = dict()
grid_count_status = defaultdict(int)
codeid = ""
engine_type_count = defaultdict(int)
engine_type_stats = dict()
should_restart = False
last_purge = -1
@staticmethod
def initialize_semaphore(key) :
try :
sem = sysv_ipc.Semaphore(key, flags = sysv_ipc.IPC_CREX, initial_value = _SEMAPHORE_VALUE)
except :
sem = sysv_ipc.Semaphore(key)
return sem
NOSTAT = (0.0, 0.0, 0.0, 0.0, 0.0)
def check_output(string, ignore_list = ['no version information available']) :
lines = string.split('\n')
for line in lines :
line = line.strip()
if line == '' :
continue
should_ignore = False
for ignore in ignore_list :
#add_log_line(gb, '%s | %s | %s' % (line, ignore, str(ignore in line)), RED)
if ignore in line :
should_ignore = True
break
if not should_ignore :
return False
return True
def process_queue(status, ids) :
failed, pending, scheduled, ready = 0, 0, 0, 0
for key, value in status.items() :
if key == 'failed' :
failed += value
elif key == 'tasks' :
pending += value
elif key == 'queue' :
scheduled += value
elif key == 'unassigned' :
scheduled += value
elif key == 'completed' :
ready += value
elif isinstance(key, int) :
node_id = key
node = value
if not node_id in ids :
failed += node.get('failed', 0) + node.get('tasks', 0) + node.get('queue', 0) + node.get('unassigned', 0)
ready += node.get('completed', 0)
else :
failed += node.get('failed', 0)
pending += node.get('tasks', 0)
scheduled += node.get('unassigned', 0)
scheduled += node.get('queue', 0)
ready += node.get('completed', 0)
return (failed, pending, scheduled, ready)
#create a bordered window
def border_win(parent,height,width,x,y,**kwargs):
if(not 'notop' in kwargs):
parent.hline(x,y,'.',width)
height -= 1
x += 1
if(not 'nobottom' in kwargs):
parent.hline(x+height-1,y,'.',width)
height -= 1
if(not 'noleft' in kwargs):
parent.vline(x,y,'.',height)
width -= 1
y += 1
if(not 'noright' in kwargs):
parent.vline(x,y+width-1,'.',height)
width -= 1
w = parent.subwin(height, width,x,y)
w.noutrefresh()
parent.refresh()
return w
#threaded output of a file to the log window
def thread_log_output(file, gb, color, filter):
while 1 :
line = file.readline()
if (not line):
break
if (filter and len([f for f in filter if f in line]) > 0) :
pass
else:
add_log_line(gb,line,color)
def log_output(file, gb, color = 0, filter = []):
t = thread.start_new_thread(thread_log_output, (file, gb, color, filter))
return t
def get_pbs_stats(status):
if (not status.pbs_engines):
return (0, 0, 0)
status.lock.acquire()
try:
cmd = "qstat " + " ".join(status.pbs_engines)
args = shlex.split(cmd)
p = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
cmd = "gawk '{print $5}'"
args = shlex.split(cmd)
p2 = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=p.stdout)
output = p2.communicate()[0]
z = defaultdict(int)
for k in output[2:]:
z[k] += 1
res = (len(status.pbs_engines),z['Q'],z['R'])
finally:
status.lock.release()
return res
def get_stat_str(stats):
cpu,memp,mempmax,mem,memmax = stats
if(cpu < 0.50 or mempmax > 0.90):
color = RED
elif(cpu < 0.80 or mempmax > 0.70):
color = YELLOW
else:
color = GREEN
descr = "(" + '{:.2%}'.format(cpu) + " CPU, " + \
'{:.2%}'.format(memp) + "/" + '{:.2%}'.format(mempmax) + "/" + \
'{}'.format(int(mem)) + "MB MEM)"
return descr,color
#thread display status
def thread_display_status(gb,status):
while not status.stop_status_display:
status.lock.acquire()
gb.lock.acquire()
try:
if(gb.wcom_status and gb.wcom_status.getmaxyx()[1] > 50):
sizey = gb.wcom_status.getmaxyx()[1]
gb.wcom_status.erase()
gb.wcom_status.addstr(1,1,"Controller: ")
if controller_online(status) :
r = status.controller_cpu / 100.0
mem = status.controller_mem
if (r > 0.80 or mem >= 4096.0):
color = RED
elif(r > 0.50 or mem >= 2048.0):
color = YELLOW
else:
color = GREEN
if mem >= 4096.0 :
status.should_restart = True
gb.wcom_status.addstr(1,18,"ONLINE", curses.color_pair(color))
gb.wcom_status.addstr(1,52,"(" + '{:.2%}'.format(r) + " CPU, " + '%.2f' % mem + "MB MEM)",curses.color_pair(color))
else:
gb.wcom_status.addstr(1,18,"OFFLINE",curses.color_pair(YELLOW))
gb.wcom_status.addstr(3,1,"Local engines: ")
unaccounted = len(status.local_engines) - status.engine_type_count['LOCAL']
if(status.local_engines and not unaccounted != 0):
color = GREEN
else:
color = YELLOW
if(unaccounted != 0):
gb.wcom_status.addstr(3,18,str(len(status.local_engines)) + "("+str(-unaccounted) +")",curses.color_pair(color))
else:
gb.wcom_status.addstr(3,18,str(len(status.local_engines)),curses.color_pair(color))
if(sizey > 90 and status.local_engines):
stats = status.engine_type_stats.get("LOCAL",NOSTAT)
descr,color = get_stat_str(stats)
gb.wcom_status.addstr(3,52,descr,curses.color_pair(color))
gb.wcom_status.addstr(5,1,"PBS engines: ")
stats = get_pbs_stats(status)
status.pbs_stats = stats
unaccounted = stats[2] - status.engine_type_count['PBS']
if(stats[2] and not unaccounted != 0):
color = GREEN
else:
color = YELLOW
if(unaccounted != 0):
gb.wcom_status.addstr(3,18,str(stats[2]) + "("+str(-unaccounted) +")",curses.color_pair(color))
else:
gb.wcom_status.addstr(5,18,str(stats[2]),curses.color_pair(color))
if(stats[1]):
gb.wcom_status.addstr(5,28,'Queued: ' + str(stats[1]),curses.color_pair(YELLOW))
failed = stats[0] - (stats[1] + stats[2])
if(failed):
gb.wcom_status.addstr(5,40,'Failed: ' + str(failed),curses.color_pair(RED))
if(sizey > 90 and status.pbs_engines):
stats = status.engine_type_stats.get("PBS",NOSTAT)
descr,color = get_stat_str(stats)
gb.wcom_status.addstr(5,52,descr,curses.color_pair(color))
gb.wcom_status.addstr(7,1,"GRID engines: ")
running = status.grid_count_status['running']
queued = status.grid_count_status['scheduled'] + status.grid_count_status['submitted'] + \
status.grid_count_status['waiting'] + status.grid_count_status['ready']
failed = status.grid_count_status['done (success)'] + status.grid_count_status['cleared'] + \
status.grid_count_status['aborted']
unaccounted = running - status.engine_type_count['GRID']
if(running and not unaccounted != 0):
color = GREEN
else:
color = YELLOW
if(unaccounted != 0):
gb.wcom_status.addstr(7,18,str(running) + "("+str(-unaccounted) +")",curses.color_pair(color))
else:
gb.wcom_status.addstr(7,18,str(running),curses.color_pair(color))
if(queued):
gb.wcom_status.addstr(7,28,'Queued: ' + str(queued),curses.color_pair(YELLOW))
if(failed):
gb.wcom_status.addstr(7,40,'Failed: ' + str(failed),curses.color_pair(RED))
if(sizey > 90 and status.grid_engines):
stats = status.engine_type_stats.get("GRID",NOSTAT)
descr,color = get_stat_str(stats)
gb.wcom_status.addstr(7,52,descr,curses.color_pair(color))
if (status.queue_status) :
failed, pending, scheduled, ready = process_queue(status.queue_status, status.queue_ids)
descr = "Failed: " + str(failed)
descr += " Pending: " + str(pending)
descr += " Scheduled: " + str(scheduled)
descr += " Ready: " + str(ready)
gb.wcom_status.addstr(9, 1, "Queue:")
gb.wcom_status.addstr(9, 18, descr)
gb.wcom_status.refresh()
except Exception,e:
add_log_line(gb,"Exception in display thread: " + str(e), RED)
finally:
gb.lock.release()
status.lock.release()
time.sleep(1)
def start_status_display(gb,status):
status.stop_status_display = False
t = threading.Thread(target=thread_display_status,args=(gb,status))
t.daemon=True
t.start()
return t
def stop_status_display(status,t):
set_status_message(gb, "Waiting for status thread to terminate..", YELLOW)
status.stop_status_display = True
t.join()
def controller_online(status):
return (status.controller and status.controller.poll() is None)
#initialize windows/lock, etc.
def build_windows(gb):
if(not gb.lock):
gb.lock = threading.RLock()
gb.lock.acquire()
try:
#clear screen in curses does not work somehow.
print "\033[2J"
gb.scr.erase()
gb.scr.refresh()
curses.start_color()
# Invisibility mode of the cursor may not be supported by the terminal
try :
curses.curs_set(0)
except :
pass
#curses getmaxyx does not work for resize screens to smaller sizes. Use stty instead.
rows, columns = os.popen('stty size', 'r').read().split()
size = (int(rows), int(columns))
com_win_rows = max(0,min(20,size[0]-2))
status_win_rows = max(0,min(2,size[0] - com_win_rows))
log_win_rows = max(0,size[0] - com_win_rows - status_win_rows)
#init colors
curses.init_pair(RED,curses.COLOR_RED,curses.COLOR_BLACK)
curses.init_pair(GREEN,curses.COLOR_GREEN,curses.COLOR_BLACK)
curses.init_pair(YELLOW,curses.COLOR_YELLOW,curses.COLOR_BLACK)
curses.init_pair(MAGENTA,curses.COLOR_MAGENTA,curses.COLOR_BLACK)
curses.init_pair(BLUE,curses.COLOR_BLUE,curses.COLOR_BLACK)
curses.init_pair(CYAN,curses.COLOR_CYAN,curses.COLOR_BLACK)
#log window
if(log_win_rows > 2):
gb.wlog = border_win(gb.scr,log_win_rows,size[1],0,0)
gb.wlog_size = gb.wlog.getmaxyx()
gb.wlog_currow = 0
gb.wlog.setscrreg(0,gb.wlog_size[0]-1)
gb.wlog.idlok(True)
gb.wlog.scrollok(True)
gb.wlog.refresh()
else:
gb.wlog = None
#com window
if(com_win_rows > 10):
com_win_cols = size[1] / 2
if(com_win_cols > 55):
comlog_win_cols = size[1] - 55
com_win_cols = 55
gb.wcom_status = border_win(gb.scr,com_win_rows,comlog_win_cols,log_win_rows,com_win_cols,notop=True,noleft=True)
gb.wcom_status.refresh()
else:
com_win_cols = size[1]
gb.wcom_status = None
gb.wcom = border_win(gb.scr,com_win_rows,com_win_cols,log_win_rows,0,notop=True)
gb.wcom.refresh()
else:
gb.wcom = None
gb.wcom_status = None
#status window
if(status_win_rows == 2):
gb.wstatus = gb.scr.subwin(status_win_rows,size[1],log_win_rows + com_win_rows,0)
gb.wstatus.refresh()
else:
gb.wstatus = None
init_commands(gb)
gb.scr.refresh()
finally:
gb.lock.release()
#add line to log windows
def add_log_line(gb, line, color=0):
str_now = datetime.datetime.now().strftime("%B %d %Y %I:%M%p")
prefix = '[%s] ' % str_now
line = prefix + line
gb.lock.acquire()
try:
if (line and line[-1] == '\n'):
gb.log_file.write(line)
else :
gb.log_file.write(line + '\n')
gb.log_file.flush()
if (gb.wlog):
try:
line = str(line.decode('ascii'))
except UnicodeDecodeError:
line = "Invalid line format (unicode) encountered"
color = RED
line = line[:(gb.wlog_size[1] - 2)]
if(line and line[-1] == '\n'): line = line[:-1]
if(gb.wlog_currow < gb.wlog_size[0]):
gb.wlog.addstr(gb.wlog_currow,1,line,curses.color_pair(color))
gb.wlog_currow += 1
else:
gb.wlog.scroll()
gb.wlog.addstr(gb.wlog_size[0] - 1,1,line,curses.color_pair(color))
gb.wlog.refresh()
except Exception, e:
pass
finally:
gb.lock.release()
#set status message iin status window
def set_status_message(gb, line, color = 0):
gb.lock.acquire()
try:
if (gb.wstatus) :
gb.wstatus.addstr(0,0,line,curses.color_pair(color))
gb.wstatus.clrtoeol()
gb.wstatus.refresh()
except Exception, e:
pass
finally:
gb.lock.release()
def set_progress_bar(gb,s):
gb.lock.acquire()
try:
if(gb.wstatus):
if(s < 0.0 or s > 1.0):
add_log_line(gb, "Progress bar value out of range: " + str(s),RED)
else:
size = gb.wstatus.getmaxyx()
total_i = size[1] - 3
full_i = int(s * total_i)
rem_i = total_i - full_i
line = "[" + ('#' * full_i) + (' ' * rem_i) + "]"
gb.wstatus.addstr(1,0,line,curses.color_pair(MAGENTA))
gb.wstatus.clrtoeol()
gb.wstatus.refresh()
except Exception,e:
add_log_line(gb,"Exception in set_progress_bar: " + str(e),RED)
finally:
gb.lock.release()
def stop_progress_bar(gb):
gb.lock.acquire()
try:
if(gb.wstatus):
gb.wstatus.addstr(1,0,"")
gb.wstatus.clrtoeol()
gb.wstatus.refresh()
except Exception, e:
pass
finally:
gb.lock.release()
#print commands in command windows
def init_commands(gb):
gb.lock.acquire()
try:
if not gb.wcom is None:
gb.wcom.addstr(1,1,"Start/stop controller: a/z")
gb.wcom.addstr(2,1,"Start/stop local engines: s/x [n]")
gb.wcom.addstr(3,1,"Start/stop PBS engines: d/c [n]")
gb.wcom.addstr(4,1,"Start/stop GRID engines: f/v [n]")
gb.wcom.addstr(5,1,"Reload all engines: w")
gb.wcom.addstr(6,1,"Restart all engines: e")
gb.wcom.addstr(7,1,"Restart controller: y")
gb.wcom.addstr(8,1,"Restart client: p")
gb.wcom.addstr(10,1,"Shutdown: q")
gb.wcom.refresh()
except Exception, e:
pass
finally:
gb.lock.release()
#enter command in command window
def enter_command(gb,argument="Command: "):
if gb.wcom is None:
return
gb.lock.acquire()
try:
command = ""
size = gb.wcom.getmaxyx()
x = size[0] - 1
gb.wcom.addstr(x,1,argument)
gb.wcom.clrtoeol()
gb.wcom.refresh()
while 1:
gb.lock.release()
c = gb.scr.getch()
gb.lock.acquire()
if c == curses.ascii.LF:
break
elif c == curses.ascii.DEL:
command = command[:-1]
else:
if(c > 256):
set_status_message(gb,"Keycode not supported: " + str(c))
else:
command += chr(c)
gb.wcom.addstr(x,1,argument + command[:(size[1] - len(argument) - 2)])
gb.wcom.clrtoeol()
gb.wcom.refresh()
gb.wcom.addstr(x,1,"")
gb.wcom.clrtoeol()
gb.wcom.refresh()
finally:
gb.lock.release()
return command
def get_number(gb,argument,default=0):
cmd = enter_command(gb,argument)
if(not cmd):
n = default
else:
try:
n = int(cmd)
except ValueError:
set_status_message(gb,"Number of engines should be a number",YELLOW)
n = None
return n
#start ipython cluster controller
def start_controller(gb,status):
set_status_message(gb,"Waiting for controller to finish initialization...",YELLOW)
set_progress_bar(gb,0.0)
status.lock.acquire()
internal = range(int(status.iport) + 10000, int(status.iport) + 10005)
try:
cwd = os.getcwd()
engine_json_path = "./profile/security/ipcontroller-engine.json"
client_json_path = "./profile/security/ipcontroller-client.json"
cmd = "ipcontroller --HubFactory.notifier_port=%d" % (internal[4], ) + \
" --HubFactory.iopub=%d,%d" % (internal[3], int(status.iport) + 6) + \
" --HubFactory.task=%d,%d" % (internal[2], int(status.iport) + 5) + \
" --HubFactory.mux=%d,%d" % (internal[1], int(status.iport) + 4) + \
" --HubFactory.control=%d,%d" % (internal[0], int(status.iport) + 3) + \
" --HubFactory.hb=%d,%d" % (int(status.iport) + 1, int(status.iport) + 2) + \
" --port=" + str(status.iport) + \
" --nodb --quiet --location=" + status.address + \
" --hwm=" + str(status.hwm) + \
" --usethreads" + \
" --ip=*" + \
" --ProfileDir.location=" + cwd + "/profile/"
if status.recover:
cmd = "ipcontroller --HubFactory.notifier_port=%d" % (internal[4], ) + \
" --HubFactory.iopub=%d,%d" % (internal[3], int(status.iport) + 6) + \
" --HubFactory.task=%d,%d" % (internal[2], int(status.iport) + 5) + \
" --HubFactory.mux=%d,%d" % (internal[1], int(status.iport) + 4) + \
" --HubFactory.control=%d,%d" % (internal[0], int(status.iport) + 3) + \
" --HubFactory.hb=%d,%d" % (int(status.iport) + 1, int(status.iport) + 2) + \
" --port=" + str(status.iport) + \
" --reuse --restore --quiet --nodb --location=" + status.address + \
" --hwm=" + str(status.hwm) + \
" --usethreads" + \
" --ip=*" + \
" --ProfileDir.location=" + cwd + "/profile/"
add_log_line(gb,"Executing: " + cmd, GREEN)
args = shlex.split(cmd)
pc = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
status.controller = pc
status.controller_monitor = psutil.Process(pc.pid)
status.should_restart = False
finally:
status.lock.release()
log_output(pc.stdout, gb, WHITE, ['distributing Tasks', 'Getting task result', 'Queuing task', 'sync properties', 'Clearing', 'Cleared'])
log_output(pc.stderr, gb, RED)
set_progress_bar(gb,0.4)
while(pc.poll() is None and not os.path.exists(engine_json_path)):
time.sleep(1)
if(not pc.poll() is None):
set_status_message(gb,"Controller startup failed!",RED)
else:
retry = 3
set_status_message(gb,"Starting controller client...",YELLOW)
time.sleep(5)
while retry > 0 :
try :
status.taskclient = Client(client_json_path)
break
except Exception, e :
retry -= 1
if retry == 0 :
break
else :
time.sleep(5)
stop_progress_bar(gb)
if retry > 0 :
set_status_message(gb, "Controller online", GREEN)
add_log_line(gb, "Controller brought online", MAGENTA)
else :
set_status_message(gb, "Controller online (client offline)", RED)
add_log_line(gb, "Controller brought online, but client is offline", MAGENTA)
def restart_client(gb, status) :
set_status_message(gb, "Restarting client...", YELLOW)
cwd = os.getcwd()
client_json_path = "./profile/security/ipcontroller-client.json"
status.lock.acquire()
try :
if status.taskclient is not None :
status.taskclient.close()
status.taskclient = None
add_log_line(gb, "Client offline", MAGENTA)
retry = 3
set_status_message(gb, "Starting controller client...", YELLOW)
time.sleep(5)
while retry > 0 :
try :
status.taskclient = Client(client_json_path)
break
except Exception, e :
retry -=1
if retry == 0 :
break
else :
time.sleep(5)
stop_progress_bar(gb)
if retry > 0 :
set_status_message(gb, "Client online", GREEN)
add_log_line(gb, "Client brought online", GREEN)
else :
set_status_message(gb, "Client offline", RED)
add_log_line(gb, "Could not attach client", RED)
finally :
status.lock.release()
#start ipython cluster controller
def restart_controller(gb, status):
set_status_message(gb, "Restarting controller...", YELLOW)
set_progress_bar(gb, 0.0)
cwd = os.getcwd()
engine_json_path = "./profile/security/ipcontroller-engine.json"
client_json_path = "./profile/security/ipcontroller-client.json"
status.lock.acquire()
try :
if status.taskclient is not None :
status.taskclient.close()
status.taskclient = None
if controller_online(status) :
shutil.move(client_json_path, client_json_path + '.bak')
shutil.move(engine_json_path, engine_json_path + '.bak')
status.controller.kill()
status.controller = None
status.controller_monitor = None
status.controller_cpu, status.controller_mem = 0.0, 0.0
status.should_restart = False
finally :
status.lock.release()
time.sleep(4) #finishes log output, lets threads terminate
internal=range(int(status.iport)+10000,int(status.iport)+10004)
cmd = "ipcontroller --HubFactory.iopub=%d,%d" % (internal[3], int(status.iport) + 7) + \
" --HubFactory.task=%d,%d" % (internal[2], int(status.iport) + 6) + \
" --HubFactory.mux=%d,%d" % (internal[1], int(status.iport) + 5) + \
" --HubFactory.control=%d,%d" % (internal[0], int(status.iport) + 4) + \
" --HubFactory.hb=%d,%d" % (int(status.iport) + 2, int(status.iport) + 3) + \
" --port=" + str(status.iport) + \
" --reuse --restore --quiet --nodb --location=" + status.address + \
" --hwm=" + str(status.hwm) + \
" --usethreads" + \
" --ip=*" + \
" --ProfileDir.location=" + cwd + "/profile/"
status.lock.acquire()
try :
shutil.move(client_json_path + '.bak', client_json_path)
shutil.move(engine_json_path + '.bak', engine_json_path)
add_log_line(gb, "Executing: " + cmd, GREEN)
args = shlex.split(cmd)
pc = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
status.controller = pc
status.controller_monitor = psutil.Process(pc.pid)
finally :
status.lock.release()
log_output(pc.stdout, gb, WHITE, ['distributing Tasks', 'Getting task result', 'Queuing task', 'sync properties', 'Clearing', 'Cleared'])
log_output(pc.stderr, gb, RED)
set_progress_bar(gb, 0.4)
while (pc.poll() is None and not os.path.exists(engine_json_path)) :
time.sleep(1)
if (not pc.poll() is None) :
set_status_message(gb, "Controller startup failed!", RED)
else:
retry = 3
set_status_message(gb, "Starting controller client...", YELLOW)
time.sleep(5)
while retry > 0 :
try:
status.taskclient = Client(client_json_path)
break
except Exception, e :
retry -=1
if retry == 0 :
break
else:
time.sleep(5)
stop_progress_bar(gb)
if retry > 0 :
set_status_message(gb, "Controller online", GREEN)
add_log_line(gb, "Controller brought online", MAGENTA)
else :
set_status_message(gb, "Controller online (client offline)", RED)
add_log_line(gb, "Controller brought online, but client is offline", MAGENTA)
#stop ipython cluster controller
def stop_controller(gb,status):
status.lock.acquire()
try:
if(status.local_engines):
stop_locals(gb,status,len(status.local_engines))
if(status.pbs_engines):
stop_pbs(gb,status,len(status.pbs_engines))
if(status.grid_engines):
stop_grid(gb,status,sum(status.grid_engines_count))
if status.taskclient is not None :
status.taskclient.close()
status.taskclient = None
set_status_message(gb,"Waiting for controller to terminate..", YELLOW)
if (controller_online(status)) :
status.controller.terminate()
status.controller = None
status.controller_monitor = None
status.controller_cpu, status.controller_mem = 0.0, 0.0
time.sleep(2) #finishes log output, lets threads terminate
status.should_restart = False
finally:
status.lock.release()
set_status_message(gb, "Controller offline..", YELLOW)
add_log_line(gb,"Controller stopped", MAGENTA)
def start_locals(gb,status,n):
status.lock.acquire()
try:
if(not controller_online(status)):
set_status_message(gb,"Controller is not online", YELLOW)
elif(n < 0):
set_status_message(gb,"Invalid number of engines to be started: " + str(n), YELLOW)
else:
set_status_message(gb,"Starting local engines", YELLOW)
chief_path = os.path.dirname(os.path.realpath(__file__)) + "/ipengine_chief"
cmd = chief_path + " -t LOCAL -a " + str(status.address) + " -p " + str(status.port)
add_log_line(gb,"Starting engines using: " + cmd, GREEN)
args = shlex.split(cmd)
set_progress_bar(gb,0.0)
for i in range(n):
e = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
log_output(e.stderr,gb,RED)
status.local_engines.append(e)
time.sleep(1)
set_progress_bar(gb,float(i+1) / float(n))
time.sleep(2)
stop_progress_bar(gb)
set_status_message(gb,"Local engines started", GREEN)
add_log_line(gb,str(n) + " local engines started", MAGENTA)
finally:
status.lock.release()
def stop_locals(gb,status,n):
status.lock.acquire()
try:
if(not status.local_engines and n != 0):
set_status_message(gb,"No local engines running",YELLOW)
elif(n < 0 or n > len(status.local_engines)):
set_status_message(gb,"Invalid number of engines to be stopped: " + str(n),YELLOW)
else:
set_status_message(gb,"Stopping local engines",YELLOW)
stop_engines = status.local_engines[:n]
status.local_engines = status.local_engines[n:]
for e in stop_engines:
if (e.poll() is None) :
e.terminate()
del stop_engines[:]
time.sleep(3)
set_status_message(gb,"Local engines stopped",GREEN)
add_log_line(gb,str(n) + " local engines stopped",MAGENTA)
finally:
status.lock.release()
def start_pbs(gb,status,n):
status.lock.acquire()
try:
if(not controller_online(status)):
set_status_message(gb,"Controller is not online",YELLOW)
elif(n < 0):
set_status_message(gb,"Invalid number of engines to be started: " + str(n),YELLOW)
else:
set_status_message(gb,"Starting PBS engines",YELLOW)
engine_path = os.path.dirname(os.path.realpath(__file__))
cmd = "qsub -N ipython_engine -k n -V -v EPATH=" + engine_path + ",ADDRESS=" + status.address + ",PORT=" + status.port + " " + engine_path + "/ipython_engine"
add_log_line(gb,"Starting engines using: " + cmd,GREEN)
args = shlex.split(cmd)
for i in range(n):
eid = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0]
status.pbs_engines.append(eid)
time.sleep(2)
set_status_message(gb,"PBS engines queued",GREEN)
add_log_line(gb,str(n) + " PBS engines queued",MAGENTA)
finally:
status.lock.release()
def stop_pbs(gb,status,n):
status.lock.acquire()
try:
if(not status.pbs_engines and n != 0):
set_status_message(gb,"No PBS engines running",YELLOW)
elif(n < 0 or n > len(status.pbs_engines)):
set_status_message(gb,"Invalid number of engines to be stopped: " + str(n),YELLOW)
else:
set_status_message(gb,"Stopping PBS engines",YELLOW)
stop_engines = status.pbs_engines[-n:]
status.pbs_engines = status.pbs_engines[:-n]
set_progress_bar(gb,0.0)
for i,eid in enumerate(stop_engines):
cmd = "qdel " + eid
args = shlex.split(cmd)
p = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
log_output(p.stdout,gb,WHITE)
log_output(p.stderr,gb,RED)
p.wait()
set_progress_bar(gb,float(i+1)/float(n))
time.sleep(2)
stop_progress_bar(gb)
set_status_message(gb,"PBS engines stopped",GREEN)
add_log_line(gb,str(n) + " PBS engines stopped",MAGENTA)
finally:
status.lock.release()
def start_grid(gb,status,n,selgrid="all"):
status.lock.acquire()
try:
if(not controller_online(status)):
set_status_message(gb,"Controller is not online",YELLOW)
elif(not status.grid_engines and not upload_code(gb,status)):
add_log_line(gb,"Grid engines startup failed",RED)
else:
tmp_jdl = 'cluster.jdl'
if(os.path.isfile(tmp_jdl)):
os.remove(tmp_jdl)
if selgrid == "all":
selgrid = ""
else:
selgrid = '"\\( RegExp\\(\\"' + selgrid + '\\"\\, other\\.GlueCEUniqueID\\) \\) \\&\\& "'
engine_path = os.path.dirname(os.path.realpath(__file__))
cmd = "sed -e s:XXSELGRIDXX:" + selgrid + ":g -e s:XXNJOBXX:" + str(n) + ":g -e s:XXADDRESSXX:" + status.address + ":g -e s:XXPORTXX:" + str(status.port) + ":g -e s#XXENVPATHXX#" + status.envname + "#g -e s:XXAPPPATHXX:" + engine_path + ":g " + engine_path + "/ipengine.jdl"
args = shlex.split(cmd)
Popen(args,stdout=open(tmp_jdl,'w')).wait()
cmd = "glite-wms-job-submit -d " + os.environ["USER"] + " --nomsg " + tmp_jdl
args = shlex.split(cmd)
out = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
if not check_output(out[1]) :
add_log_line(gb,"GRID job submission failed",RED)
for line in out[1].split('\n'):
add_log_line(gb,line,RED)
else:
jobid = out[0].strip().strip('\n')
status.grid_engines.append(jobid)
status.grid_engines_count.append(n)
add_log_line(gb,"GRID job for " + str(n) + " engines submitted: " + jobid,GREEN)
finally:
status.lock.release()
def stop_grid(gb,status,n):
status.lock.acquire()
try:
if(not status.grid_engines and n != 0):
set_status_message(gb,"No GRID engines running",YELLOW)
elif(n < 0 or n > sum(status.grid_engines_count)):
set_status_message(gb,"Invalid number of engines to be stopped: " + str(n),YELLOW)
else:
while(n > 0):
complete_cancel = [pos for pos,c in enumerate(status.grid_engines_count) if c <= n]
if(len(complete_cancel) > 0):
pos = complete_cancel[0]
id = status.grid_engines.pop(pos)
_cancel_grid([id])
n -= status.grid_engines_count.pop(pos)
add_log_line(gb,"GRID job " + id + " cancelled",GREEN)
else:
pos = numpy.array(status.grid_engines_count).argmin()
id = status.grid_engines[pos]
ids = _get_subids_grid(id)
_cancel_grid(ids[:n])
status.grid_engines_count[pos] -= n
n = 0
add_log_line(gb,"GRID job " + id + " partially cancelled (" + str(status.grid_engines_count[pos]) + " engines left)",GREEN)
finally:
status.lock.release()
def _get_subids_grid(id):
idstatus = dict()
cmd = "/usr/bin/python /usr/bin/glite-wms-job-status --noint -v 0 " + id
args = shlex.split(cmd)
env = os.environ.copy()
del env['PYTHONPATH']
r = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,env=env).communicate()
if(r[1]):
add_log_line(gb,"Error while inquiring GRID status:",RED)
for line in r[1].split('\n'):
add_log_line(gb,line,RED)
else:
res = r[0].split('\n')
skipfirst = True
for line in res:
if('Status' in line):
field = line.split(': ')[1]
if('info' in line):
id = field
else:
state = field.strip()
if(skipfirst):
skipfirst = False
else:
idstatus[id] = state.lower()
id_by_state = defaultdict(list)
for id,state in idstatus.iteritems():
id_by_state[state].append(id)
res = id_by_state.pop('submitted',[]) + id_by_state.pop('waiting',[]) + id_by_state.pop('ready',[]) + \
id_by_state.pop('scheduled',[]) + id_by_state.pop('running',[]) + id_by_state.pop('done (success',[])
for values in id_by_state.itervalues():
res += values
return res
def _cancel_grid(ids):
while ids:
cancel_ids = ids[:10]
ids = ids[10:]
cmd = "glite-wms-job-cancel --noint " + " ".join(cancel_ids)
args = shlex.split(cmd)
r = Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
#if(r[1]):
# add_log_line(gb,"Error while performing GRID cancel",RED)
# for line in r[1].split('\n'):
# add_log_line(gb,line,RED)
def upload_code(gb,status):
code_path = "/tmp/__code_" + str(status.port) + "_.tgz"
exclude_path = "exclude.dat"
cmd = "tar -czf " + code_path + " ./ "
if(os.path.isfile(exclude_path)):