forked from shpakoo/YAP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StepsLibrary.py
executable file
·2921 lines (2385 loc) · 104 KB
/
StepsLibrary.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
########################################################################################
## This file is a part of YAP package of scripts. https://github.com/shpakoo/YAP
## Distributed under the MIT license: http://www.opensource.org/licenses/mit-license.php
## Copyright (c) 2011-2013 Sebastian Szpakowski
########################################################################################
#################################################
## A library of "steps" or program wrappers to construct pipelines
## Pipeline steps orchestration, grid management and output handling.
#################################################
import YAPGlobals
import sys, tempfile, shlex, glob, os, stat, hashlib, time, datetime, re, curses
import shutil
import threading
from threading import *
import dummy_threading
import subprocess
from subprocess import *
from MothurCommandInfoWrapper import *
from collections import defaultdict
from collections import deque
from random import *
from Queue import *
import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import traceback
import pdb
##threading redefines enumerate() with no arguments. as a kludge, we drop it here
globals().pop('enumerate',None)
_author="Sebastian Szpakowski"
_date="2012/09/20"
_version="Version 2"
def rmrf(targ_path):
if os.path.islink(targ_path):
os.remove(targ_path)
elif os.path.exists(targ_path):
if os.path.isdir(targ_path):
shutil.rmtree(targ_path)
else:
try:
os.remove(targ_path)
except:
pass
def clean_flag_file(fname):
rmrf(fname)
check_flag_str_OK = "OK"
check_flag_str_Fail = "Fail"
def check_flag_file(fname):
## try multiple times while the content of flag file
## is inconclusive or file does not exist, in order to
## let shared file system view get updated
n_max_tries = 4
sec_wait = 5
i_try = 1
while True:
try:
if os.path.isfile(fname):
with open(fname,"r") as inp:
cont = inp.read()
cont = cont.strip()
if cont == check_flag_str_OK:
return True
elif cont == check_flag_str_Fail:
return False
if i_try >= n_max_tries:
return False
time.sleep(sec_wait)
i_try += 1
except:
pass
return False
def pseudo_shuffle(strings,skip=0):
"""Shuffle strings deterministically (by hash).
Keep the original position of the first 'skip' elements"""
it = iter(strings)
for i in xrange(skip):
yield next(it)
pairs = [ (hashlib.md5("{}.{}".format(t[1],t[0])).hexdigest(),t[1]) for t in enumerate(it) ]
for t in sorted(pairs):
yield t[1]
#################################################
## Classes
##
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
class StoppableDummyThread(dummy_threading.Thread):
"""Dummy Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop = dummy_threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
class ReportingThread(StoppableThread):
def __init__(self):
super(ReportingThread, self).__init__()
def run(self):
#attempting to catch threads dying
#stack trace should be printed anyway
#for non-daemon threads, so this will
#probably give us no benefit, just trying
try:
self.do_run()
except:
traceback.print_exc()
raise
class ReportingDummyThread(StoppableDummyThread):
def __init__(self):
super(ReportingDummyThread, self).__init__()
def run(self):
#attempting to catch threads dying
#stack trace should be printed anyway
#for non-daemon threads, so this will
#probably give us no benefit, just trying
try:
self.do_run()
except:
traceback.print_exc()
raise
class BufferedOutputHandler(ReportingThread):
def __init__(self, usecurses=False):
super(BufferedOutputHandler, self).__init__()
self.shutdown=False
self.cache = deque()
self.registered=0
self.ids = list()
self.wrap = 140
self.starttime = time.time()
#### init log
try:
self.otptfile = open("logfile.txt", 'a')
self.toPrint("-----", "GLOBAL", "Appending to a logfile.txt...")
except:
self.otptfile = open("logfile.txt", 'w')
self.toPrint("-----", "GLOBAL", "Creating a new logfile.txt...")
command = " ".join(sys.argv)
self.otptfile.write("command: %s\n" % command)
#### init output (curses)
self.usecurses = usecurses
if (self.usecurses):
self.stdscr=curses.initscr()
curses.savetty()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
self.textbuffer= list()
self.stself.stdscr.refresh()
self.cursestrackbuffer = 100
self.scrollpad = curses.newpad(self.cursestrackbuffer*2, self.wrap*2)
self.spacerpad = curses.newpad(1,1000)
self.updatepad = curses.newpad(10,1000)
self.rows, self.cols = self.stdscr.getmaxyx()
else:
self.stdscr=None
self.start()
def do_run(self):
self.toPrint("-----", "GLOBAL", "Setting up the pipeline...")
self.flush()
time.sleep(5)
while YAPGlobals.step_dummy_thread or (activeCount()>3 or self.registered>0 or len(self.cache) > 0):
self.flush()
time.sleep(1)
if self.stopped():
break
self.flush()
endtime = time.time()
text = "+%s [fin]" % (str(datetime.timedelta(seconds=round(endtime-self.starttime,0))).rjust(17))
self.toPrint("-----", "GLOBAL", text)
command = "%spython %straverser.py" % (binpath, scriptspath)
p = Popen(shlex.split(command), stdout = PIPE, stderr = PIPE, close_fds=True)
dot, err = p.communicate()
with open("workflow.dot", "w") as x:
x.write(dot)
x.write("\n")
#DEBUG:
skipDot = True #dot was getting into endless loop
if not skipDot:
for format in ["svg", "svgz", "png", "pdf"]:
command = "dot -T%s -o workflow.%s" % (format, format)
p = Popen(shlex.split(command), stdin = PIPE, stdout = PIPE, stderr = PIPE, close_fds=True)
out, err = p.communicate(dot)
self.toPrint("-----", "GLOBAL", "Check out workflow.{svg,png,jpg} for an overview of what happened.")
else:
self.toPrint("-----", "GLOBAL", "Skipping call to dot graphics generation")
self.flush()
self.otptfile.close()
self.closeDisplay()
self.mailLog()
def register(self, id):
if(id in set(self.ids)):
msg = "CRITICAL: Attempt to register duplicate Step ID: {}".format(id)
self.toPrint("-----", "GLOBAL", msg)
#this is called in the main thread
raise ValueError(msg)
self.registered+=1
self.ids.append(id)
def deregister(self):
self.registered-=1
def collapseIDs(self, text ):
for id in self.ids:
if len(id)>5:
text = re.sub(id, "[{0}~]".format(id[:5]), text)
return (text)
def flush(self):
while len(self.cache) > 0:
id, name, line, date = self.cache.popleft()
tag = "[{2}] [{0}] {1:<20} > ".format( id, name, time.asctime(date) )
line = "{0!s}".format(line)
#line = self.collapseIDs(line)
otpt = "{0}{1}".format(tag, line[:self.wrap])
self.otptfile.write("{0}{1}\n".format(tag, line))
line = line[self.wrap:]
self.outputScroll(otpt)
while len(line)>=self.wrap:
otpt = "{0}\t{1}".format(tag, line[:self.wrap])
line = line[self.wrap:]
self.outputScroll(otpt)
if len(line)>0:
otpt = "{0:<30}\t\t{1}".format("", line)
line = line
self.outputScroll(otpt)
self.redrawScreen()
def mailLog(self):
log = loadLines("logfile.txt")
log.reverse()
paths = os.getcwd()
paths = "%s/" % (paths)
dirs = glob.glob("*OUTPUT*")
dirs.sort()
for d in dirs:
paths = "%s\n\t%s/*" % (paths, d)
header = "Hi,\nYAP has just finished. Most, if not all, of your data should be in:\n\n%s\n\n-see the log below just to make sure...\nThe attached work-flow graph can be opened in your browser.\nYours,\n\n~YAP" % (paths)
log = "".join(log)
msgtext = "%s\n\n<LOG>\n\n%s\n</LOG>\n\n" % (header, log)
try:
me = __email__
toaddr = [me]
msg = MIMEMultipart()
msg['To'] = COMMASPACE.join(toaddr)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = '[AUTOMATED] YAP is done.'
if me != __admin__:
ccaddr = [__admin__]
msg['BCC'] = COMMASPACE.join(ccaddr)
toaddr = toaddr + ccaddr
msg.attach(MIMEText(msgtext))
files = ["workflow.pdf"]
for f in files:
try:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
except:
pass
s = smtplib.SMTP('mail.jcvi.org')
s.sendmail(me, toaddr , msg.as_string())
s.quit()
except:
pass
def redrawScreen(self):
try:
y,x = self.stdscr.getmaxyx()
### enough screen to print:
if y>20 and x>20:
if len(self.textbuffer) < (y-10):
self.scrollpad.refresh(0, 0, 0, 0, y-10, x-5)
else:
self.scrollpad.refresh(self.cursestrackbuffer-y+10 , 0, 0, 0, y-10, x-5)
self.updatepad.refresh(0, 0, y-8, 10 , y-3, x-5)
### when screen too small
else:
self.scrollpad.refresh(0,0,0,0,0,0)
self.updatepad.refresh(0,0,0,0,0,0)
except:
self.closeDisplay()
self.usecurses=False
#
def toPrint(self, id, name, line, date=None):
if date is None:
date = time.localtime()
self.cache.append((id, name, line, date))
def outputScroll(self, k):
if self.usecurses:
self.textbuffer.append("%s\n" %(k))
self.scrollpad.clear()
for k in self.textbuffer[-self.cursestrackbuffer:]:
self.scrollpad.addstr(k)
else:
print k
def outputUpdate(self,k):
if self.usecurses:
self.updatepad.clear()
for k in k.strip().split("\n"):
self.updatepad.addstr("%s\n" % k)
def closeDisplay(self):
if self.usecurses:
self.stdscr.clear()
self.stdscr.refresh()
curses.curs_set(1)
curses.nocbreak()
curses.echo()
curses.resetty()
curses.endwin()
class TaskQueueStatus(ReportingThread):
def __init__(self, update=1, maxnodes=10):
if YAPGlobals.step_dummy_thread:
self.quiet = True
else:
self.quiet = False
ReportingThread.__init__(self)
self.active=True
self.maxnodes = maxnodes
self.available = self.maxnodes
self.update = update
#### queue of grid jobs to run
self.scheduled = Queue()
#### to keep track of things popped off the queue
self.processing = dict()
#### inventory of what ran
#### tuple (jid, status) indexed by command
#### status: new/running/done/remove
#### new upon registering
#### running when submitted to the grid
#### done when completed
self.registered = dict()
#### inventory of completed jobs
self.bestqueue = "default.q"
self.pollqueues()
self.running=0
self.stats=dict()
self.previous =""
## All task submitters with wait for this condition,
## that will be signalled in task.setCompleted method.
## All waited tasks will get notified and check for their isCompleted status (that will be
## serialized because lock has to be acquired by Condition.wait()).
## The task that was set as completed will exit the wait loop.
## A much more straightforward use of Event associated with every
## Task would however consumed one handle per event object, probably
## leading to thread resource errors that we have seen before.
self.any_task_completed = threading.Condition()
self.start()
def do_run(self):
BOH.toPrint("-----","BATCH","Setting up the grid...")
time.sleep(5)
while not self.stopped():
#while YAPGlobals.step_dummy_thread or (activeCount()>3 or self.running>0 or self.scheduled.qsize()>0):
self.pollfinished()
self.pollqueues()
self.pollrunning()
self.dispatch()
self.cleanup()
if not self.quiet:
BOH.toPrint("-----","BATCH","{}".format(self))
time.sleep(self.update)
BOH.toPrint("-----","BATCH","{}\nGrid Offline.".format(self))
print self
print "Queue status shutting down."
def cleanup(self):
toremove = set()
for key, tup in self.registered.items():
id, status = tup
if status == "remove":
toremove.add(key)
for key in toremove:
del self.registered[key]
def flagRemoval(self, task):
id, status = self.registered[task.getUniqueID()]
if status =="done":
self.registered[task.getUniqueID()] = [id, "remove"]
else:
print "cannot flag yet:", id, status
def pollfinished(self):
# donejobs = set()
#
# ### only 100 recent jobs shown, which could be a problem ;-)
# p = Popen(shlex.split("qstat -s z"), stdout=PIPE, stderr=PIPE, close_fds=True)
#
# out,err = p.communicate()
#
# lines = out.split("\n")
# tmp = set()
# if len(lines)>2:
# for line in lines[2:]:
# line = line.strip().split()
# if len(line)>0:
# donejobs.add(line[0])
#
#if len(donejobs)>0:
for key, tup in self.registered.items():
id, status = tup
#if (status == "running") and (id in donejobs):
if (status == "running") and (self.isJobDone(id)):
tmp = self.registered[key][1]= "done"
self.processing[key].setCompleted()
self.available += 1
del self.processing[key]
def isJobDone(self, jid):
if jid == -1:
BOH.toPrint("-----","BATCH","Impossible job id for qstat {}, marking as done...".format(jid))
return True
err = ""
for i_try in range(3):
time.sleep(2**(i_try+1)-2)
p = Popen(shlex.split("qstat -j %s" % jid), stdout=PIPE, stderr=PIPE, close_fds=True)
out,err = p.communicate()
if err.find("jobs do not exist")>-1:
return True
elif p.returncode == 0:
break
if not self.quiet:
BOH.toPrint("-----","BATCH","qstat error {}, trying again...".format(err))
else:
if not self.quiet:
BOH.toPrint("-----","BATCH","isJobDone() multiple qstat errors {}, giving up.".format(err))
return False
def pollqueues(self):
qstat_ok = False
command="qstat -g c"
err = ""
for i_try in range(3):
time.sleep(2**(i_try+1)-2)
p = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, close_fds=True )
out,err = p.communicate()
#no point to continue if host configured to never submit
assert err.find("neither submit nor admin host")==-1
if p.returncode == 0:
qstat_ok = True
break
if not self.quiet:
BOH.toPrint("-----","BATCH","qstat error {}, trying again...".format(err))
else:
if not self.quiet:
BOH.toPrint("-----","BATCH","pollqueues() multiple qstat errors {}, giving up.".format(err))
if qstat_ok:
#else we just keep the previous attribute values
queues = defaultdict(float)
out = out.strip().split("\n")
fullqueues = set()
#cache queue information
for q in out[2:]:
queue, cqload, used, res, avail, total, acds, cdsu = q.split()
avail = float(avail)
total = float(total)
if total>0:
queues[queue] = avail
if avail==0:
fullqueues.add(queue)
# determine which queue is the best
#for k in ("default.q", "medium.q", "fast.q", "himem.q"):
#for k in ("fast.q", "medium.q", "default.q"):
#for k in ("himem.q", "medium.q", "default.q"):
if ("medium.q" in fullqueues) and ("default.q" in fullqueues) and "himem" in queues.keys() :
if queues["himem.q"]>0:
self.bestqueue = "himem.q"
else:
self.bestqueue = "medium.q"
else:
for k in ("medium.q", "default.q"):
if queues[k] >= queues[self.bestqueue]:
self.bestqueue = k
if YAPGlobals.large_run:
if self.bestqueue not in ("himem.q", "default.q"):
## this queue has no wall clock time limit. make.shared was running out
## of 12 hour limit in medium.q for 3K samples
self.bestqueue = "default.q"
### sanity check, this should match the counters
def pollrunning(self):
tmp=defaultdict(int)
for jid, value in self.registered.values():
tmp[value]+=1
self.stats = tmp
self.running = self.stats["running"]
def dispatch(self):
while self.nodesAvailable():
if not self.scheduled.empty():
tmp = self.scheduled.get()
self.processing[tmp.getUniqueID()]=tmp
#print "submitting", tmp.getUniqueID()
jid = tmp.submit()
#print jid
if jid==-1:
#whate happens if SGE is temporarily not availabe:
#job is marked as running but with
#non-existing job ID -1; it is found as "finished" by the
#next polling cycle and eventually marked as failed by the
#Step thread. However, isJobDone() as it is written will
#not mark such -1 job as done as long as SGE is not
#available. self.pollqueues() will likely raise in that
#case the way it is written now, causing this thread to
#terminate.
pass
self.registered[tmp.getUniqueID()] = [tmp.getGridId(), "running"]
self.available-=1
else:
break
def pickQ(self):
return self.bestqueue
def register(self, task):
#this is called from Step threads; it could be preemptied
#by other methods in this thread between the next two lines.
#The present order should work OK if preemptied by
#dispatch()
self.registered[task.getUniqueID()]=[-1, "new"]
self.scheduled.put(task)
def shutdown(self):
self.active=False
print "Queue status shutting down..."
def nodesAvailable(self):
return (self.available > 0)
def __str__(self):
otpt ="Currently running/waiting: %s/%s\n" % (self.running, self.scheduled.qsize())
otpt ="%savailable/total: %s/%s" % (otpt, self.available, self.maxnodes)
# for key, tup in self.registered.items():
# id, status = tup
# if id != -1:
# otpt = "%s\n\t%s\t%s\t%s" % (otpt, id, status, key[0:10])
for key, val in self.stats.items():
otpt = "%s\n\t%s\t%s" % (otpt, key, val)
otpt = "%s\n\nbest queue: %s" % (otpt, self.bestqueue)
return (otpt)
#################################################
### a thread that will track of a qsub job
### templates adapted to JCVIs grid
###
class GridTask():
def __init__(self, template="default.q", command = "", name="default",
cpu="1", dependson=list(), cwd=".", debug=None, mem_per_cpu=2,
sleep_start=0, flag_completion=False):
if debug is None:
debug = YAPGlobals.debug_grid_tasks
self.flag_file = None
self.gridjobid=-1
self.completed=False
self.queue=template
self.inputcommand = command
self.cwd=cwd
self.project = __projectid__
self.email = __email__
### remove *e##, *pe## *o## *po##
self.retainstreams=" -o /dev/null -e /dev/null "
### debug flag
self.debugflag = debug
ncpu = 1
try:
ncpu = int(cpu)
except:
pass
### the only queue that has 4 CPUs allowed in pe
if ncpu>4:
self.queue = "himem.q"
mem = mem_per_cpu * ncpu
## this is the max currently allowed - go figure...
if mem > 40:
mem = 40
if mem > 32:
self.queue = "himem.q"
mem_per_cpu = int(mem/ncpu)
## -l memory interacts with -pe threaded, resulting in a multiple of them
## for the total memory requested
if mem_per_cpu != 0:
mem_spec = "-l memory={}G".format(mem_per_cpu)
else:
mem_spec = ""
if len(dependson)>0:
holdfor = "-hold_jid "
for k in dependson:
raise ValueError("Job dependencies do not work yet because jobs are submitted from a separate thread and getGridId() returns -1 at this point")
holdfor = "%s%s," % (holdfor, k.getGridId())
holdfor=holdfor.strip(",")
sleep_start = max(sleep_start,10) # let files on shared FS to appear
else:
holdfor = ""
### keep po pe o e streams for debugging purposes
if self.debugflag:
self.retainstreams=""
### To source the proper environment, create a script with the command,
### and first source the RC file, then invoke that instead of submitting
### the command directly. Note that the -V option to qsub does not
### propagate LD_LIBRARY_PATH, which is squashed by the kernel for sudo
### programs (which is SGE exec daemon). Note (AT): -V just does not work
### for me at all - jobs silently fail (2014-04-10).
px = "tmp.%s.%s.%s.%s." % (randrange(1,100),randrange(1,100),randrange(1,100),randrange(1,100))
sx = ".%s.%s.%s.%s.sh" % (randrange(1,100),randrange(1,100),randrange(1,100),randrange(1,100))
##### to avoid too many opened files OSError
pool_open_files.acquire()
### bounded semaphore should limit throttle the files opening for tasks created around the same time
try:
try:
scriptfile, scriptfilepath = tempfile.mkstemp(suffix=sx, prefix=px, dir=self.cwd, text=True)
finally:
os.close(scriptfile)
self.scriptfilepath = scriptfilepath
os.chmod(self.scriptfilepath, 0777 )
if sleep_start > 0:
import random
sleep_cmd = "sleep {}".format(sleep_start+random.randint(1,5))
else:
sleep_cmd = ""
input= "#!/bin/bash\n. {}\n{}\n{}\n".format(rcfilepath,sleep_cmd,self.inputcommand)
if flag_completion:
try:
flag_fobj, flag_file = tempfile.mkstemp(suffix="flagfile", prefix=px, dir=self.cwd, text=True)
os.write(flag_fobj,"Created\n")
finally:
os.close(flag_fobj)
self.flag_file = flag_file
flag_file_base = os.path.basename(self.flag_file)
input += """\nif [[ "$?" != "0" ]]; then (echo {check_flag_str_Fail} > {flag_file_base}); else (echo {check_flag_str_OK} > {flag_file_base}); fi\nsync\n""".\
format(flag_file_base=flag_file_base,
check_flag_str_OK=check_flag_str_OK,
check_flag_str_Fail=check_flag_str_Fail)
with open(self.scriptfilepath, "w") as scriptfile:
scriptfile.write(input)
finally:
pool_open_files.release()
####
self.templates=dict()
self.templates["himem.q"] = 'qsub %s -P %s -N jh.%s -cwd -pe threaded %s %s -l "himem" -M %s -m a %s "%s" ' % (self.retainstreams, self.project, name, cpu, mem_spec, self.email, holdfor, self.scriptfilepath)
self.templates["default.q"] = 'qsub %s -P %s -N jd.%s -cwd -pe threaded %s %s -M %s -m a %s "%s" ' % (self.retainstreams, self.project, name, cpu, mem_spec, self.email, holdfor, self.scriptfilepath)
self.templates["fast.q"] = 'qsub %s -P %s -N jf.%s -cwd -pe threaded %s %s -l "fast" -M %s -m a %s "%s" ' % (self.retainstreams, self.project, name,cpu, mem_spec, self.email, holdfor, self.scriptfilepath)
self.templates["medium.q"] = 'qsub %s -P %s -N jm.%s -cwd -pe threaded %s %s -l "medium" -M %s -m a %s "%s" ' % (self.retainstreams, self.project, name, cpu, mem_spec, self.email, holdfor, self.scriptfilepath)
self.templates["himemCHEAT"] = 'qsub %s -P %s -N jH.%s -cwd -pe threaded %s %s -l "himem" -M %s -m a %s "%s" ' % (self.retainstreams, self.project, name, 1, mem_spec, self.email, holdfor, self.scriptfilepath)
self.templates["mpi"] = 'qsub %s -P %s -N jP.%s -cwd -pe orte %s %s -M %s -m a %s mpirun -np %s "%s" ' % (self.retainstreams, self.project, name, cpu, mem_spec, self.email, holdfor, cpu, self.scriptfilepath )
self.command = ""
QS.register(self);
def submit(self):
if not self.queue in self.templates.keys():
self.queue = QS.pickQ()
self.command = self.templates[self.queue]
BOH.toPrint("-----","BATCH","command: '{}'".format(self.command))
if YAPGlobals.dummy_grid_tasks:
check_call(["bash",self.scriptfilepath],cwd=self.cwd, close_fds=True)
self.gridjobid = 0
else:
err = ""
for i_try in range(3):
time.sleep(2**(i_try+1)-2)
p = Popen(shlex.split(self.command), stdout=PIPE, stderr=PIPE, cwd=self.cwd, close_fds=True)
out, err = p.communicate()
err = err.strip()
out = out.strip()
if p.returncode == 0:
assert out.endswith("has been submitted"),"Unexpected content in qsub output: {}".format(out)
self.gridjobid = out.split(" ")[2]
BOH.toPrint("-----","BATCH","qsub output '{}'".format(out))
BOH.toPrint("-----","BATCH","getGridId {}".format(self.getGridId()))
break
BOH.toPrint("-----","BATCH","qsub error '{}', trying again...".format(err))
else:
BOH.toPrint("-----","BATCH","submit() multiple qsub errors '{}', giving up".format(err))
return (self.getGridId())
def getGridId(self):
return self.gridjobid
def getUniqueID(self):
return "%s_%s_%s" % (id(self), self.cwd, self.inputcommand)
def setCompleted(self):
try:
if not self.debugflag:
os.remove(self.scriptfilepath)
except OSError, error:
print( "%s already gone" % self.scriptfilepath)
QS.flagRemoval(self)
with QS.any_task_completed:
self.completed = True
QS.any_task_completed.notify_all()
def isCompleted(self):
return self.completed
def wait(self):
with QS.any_task_completed:
while not self.isCompleted():
QS.any_task_completed.wait()
if self.flag_file:
return check_flag_file(self.flag_file)
else:
return True
#################################################
### Iterator over input fasta file.
### Only reading when requested
### Useful for very large FASTA files
### with many sequences
class FastaParser:
def __init__ (self, x):
self.filename = x
self.fp = open(x, "r")
self.currline = ""
self.currentFastaName = ""
self.currentFastaSequence = ""
self.lastitem=False
def __iter__(self):
return(self)
#####
def next(self):
for self.currline in self.fp:
if self.currline.startswith(">"):
self.currline = self.currline[1:]
if self.currentFastaName == "":
self.currentFastaName = self.currline
else:
otpt = (self.currentFastaName.strip(), self.currentFastaSequence.strip())
self.currentFastaName = self.currline
self.currentFastaSequence = ""
self.previoustell = self.fp.tell()
return (otpt)
else:
self.addSequence(self.currline)
if not self.lastitem:
self.lastitem=True
return (self.currentFastaName.strip(), self.currentFastaSequence.strip())
else:
raise StopIteration
def addSequence(self, x):
self.currentFastaSequence = "%s%s" % (self.currentFastaSequence, x.strip())
def __str__():
return ("reading file: %s" %self.filename)
class GeneralPurposeParser:
def __init__(self, file, skip=0, sep="\t", skip_empty=True):
self.skip_empty = skip_empty
self.filename = file
self.fp = open(self.filename, "rU")
self.sep = sep
self.skip = skip
self.linecounter = 0
self.currline=""
while self.skip>0:
self.next()
self.skip-=1
def __iter__(self):
return (self)
def next(self):
for currline in self.fp:
currline = currline.strip()
self.linecounter = self.linecounter + 1
if not self.skip_empty or currline:
currline = currline.split(self.sep)
self.currline = currline
return(currline)
raise StopIteration
def __str__(self):
return "%s [%s]\n\t%s" % (self.filename, self.linecounter, self.currline)
#################################################
### The mother of all Steps:
###
if YAPGlobals.step_dummy_thread:
DefaultStepBase = ReportingDummyThread
else:
DefaultStepBase = ReportingThread
class DefaultStep(DefaultStepBase):
#This limits the number of concurrent ("submitted") step instances,
#in other words, the number of threads on which start() has been
#called. The code creating instances of derived classes will block
#until the semaphore is acquired.
semaphore = BoundedSemaphore(YAPGlobals.step_threads_max)
def __init__(self):
#### thread init
DefaultStepBase.__init__(self)
self.random = uniform(0, 10000)
self.name = ("%s[%s]" % (self.name, self.random))
#### hash of the current step-path (hash digest of previous steps + current inputs + arguments + control)
self.workpathid = None
#### path where the step stores its files
self.stepdir = ""
#### what needs to be completed for this step to proceed
#### a list of steps
self.previous = list()
#### mapping type - path for files
self.inputs = defaultdict(set)
#### mapping type - name for files
self.outputs = defaultdict(set)
#### mapping arg val for program's arguments
self.arguments= dict()
#### mapping arg val for step's control parameters
self.control= dict()
#### ID of the step...
self.stepname = ""
#### flag for completion
self.completed = False
self.completedpreviously=False
self.failed = False
#### keep track of time elapsed
self.starttime = 0
self.endtime = 0
#### special flag, some steps might not want to delete the inputs (argcheck)
self.removeinputs = True