Debian Codegraph @

cgecore/cmdline.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 """ THIS MODULE CONTAINS ALL THE SHARED WRAPPER FUNCTIONS """
3 ################################################################################
4 # CGE FUNCTION MODULE #
5 ################################################################################
6 # This script is part of the CGE Pipeline structure
7 import sys, os
8 from subprocess import Popen, PIPE
•9 from shlex import quote
10 from time import time, sleep
11 from datetime import timedelta
12
13 # CGE modules
14 from .utility import debug, open_, mkpath
15
16 ############# CLASSES #############
17 class ProgramList(object):
18 ''' This Class keeps track of all the programs
19 USAGE:
20 proglist = ProgramList()
21 proglist.add2list(prog_obj)
22 for progname in proglist.list: proglist[progname].wait()
23 proglist.print_timers()
24 '''
25 def __init__(self):
26 ''' '''
27 self.timer = -time() # Wrapper timer
28 self.list = []
29 def __getitem__(self, key):
30 ''' '''
31 return getattr(self, key)
32 def add_program(self, prog_obj):
33 ''' '''
34 setattr(self, prog_obj.name, prog_obj)
35 self.list.append(prog_obj.name)
36 return prog_obj
37 def empty_list(self, forcefully=False):
38 ''' '''
39 removed = [self.remove_program(name, forcefully=forcefully) for name in self.list]
40 if all(removed):
41 return True
42 else:
43 return False
44 def remove_name_from_list(self, name):
45 ''' '''
46 self.list[:] = (ent for ent in self.list if ent != name)
47 def remove_program(self, name, forcefully=False):
48 ''' '''
49 # Check if program in list
50 if name in self.list:
51 # Check if program object is a local attribute
52 if name in dir(self):
53 # Check if program have completed
54 prog_obj = getattr(self, name)
55 if prog_obj.status != 'Executing' or forcefully:
56 # Remove program from list
57 delattr(self, name)
58 self.remove_name_from_list(name)
59 return True
60 else:
61 debug.log("Warning: Program %s status %s!"%(
62 name, prog_obj.status))
63 return False
64 else:
65 self.remove_name_from_list(name)
66 return True
67 else:
68 self.remove_name_from_list(name)
69 return True
70 def add2list(self, prog_obj):
71 ''' '''
72 setattr(self, prog_obj.name, prog_obj)
73 self.list.append(prog_obj.name)
74 def exists(self, name):
75 ''' Checks whether the program exists in the program list. '''
76 return name in dir(self)
77 def return_timer(self, name, status, timer):
78 ''' Return a text formatted timer '''
79 timer_template = '%s %s %s : %s : %9s'
80 t = str(timedelta(0, timer)).split(',')[-1].strip().split(':')
81 #t = str(timedelta(0, timer)).split(':')
82 if len(t) == 4:
83 h, m, s = int(t[0])*24 + int(t[1]), int(t[2]), float(t[3])
84 elif len(t) == 3: h, m, s = int(t[0]), int(t[1]), float(t[2])
85 else: h, m, s = 0, 0, str(t)
86 return timer_template%(
87 name[:20].ljust(20),
88 status[:7].ljust(7),
89 '%3d'%h if h != 0 else ' --',
90 '%2d'%m if m != 0 else '--',
91 '%.6f'%s if isinstance(s, float) else s
92 )
93 def print_timers(self):
94 ''' PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS '''
95 self.timer += time()
96 total_time = self.timer
97 tmp = '* %s *'
98 debug.log(
99 '',
100 '* '*29,
101 tmp%(' '*51),
102 tmp%('%s %s %s'%('Program Name'.ljust(20), 'Status'.ljust(7), 'Execute Time (H:M:S)')),
103 tmp%('='*51)
104 )
105 for name in self.list:
106 if self.exists(name):
107 timer = getattr(self, name).get_time()
108 status = getattr(self, name).get_status()
109 self.timer -= timer
110 debug.log(tmp%(self.return_timer(name, status, timer)))
111 else:
112 debug.log(tmp%("%s %s -- : -- : --"%(name[:20].ljust(20),' '*8)))
113 debug.log(
114 tmp%(self.return_timer('Wrapper', '', self.timer)),
115 tmp%('='*51),
116 tmp%(self.return_timer('Total', '', total_time)),
117 tmp%(' '*51),
118 '* '*29,
119 ''
120 )
121
122
123 class Program:
124 """ This class defines a program structure for the CGE system
125 OPTIONS:
126 name - Set the name of the program.
127 path - Set the path to the program.
128 timer - Set the initial time expenditure for the program.
129 ptype - Set the program type (EG. python or /bin/bash).
130 wdir - Set the working directory for the program.
131 server - Set the server for which to execute the program on.
132 queue - The name of the TORQUE queue to use. If not set, the
133 program is executed as a normal subprocess.
134 forcewait - Set to True to make the script wait for the program to
135 finish.
136 args - Provide arguments for the program.
137 walltime - Set the max limit for how many hours the program may run.
138 mem - Set the max limit of how much memory the program may use.
139 procs - Set the amount of processors to reserve for the program.
140 """
141 def __init__(self, name, path=None, timer=0, ptype=None, wdir='',
142 queue=None, wait=False, args=None, walltime=2, mem=4, procs=1,
143 server=None):
144 debug.log('\n\nInitiating %s...'%name)
145 # INIT VALUES
146 self.path = path
147 self.name = name
148 self.timer = timer
149 self.ptype = ptype
150 self.queue = queue
151 self.forcewait = wait
152 self.args = []
153 self.unquoted_args = []
154 self.stderr = "%s.err"%(name)
155 self.stdout = "%s.out"%(name)
156 self.walltime = walltime # Maximum amount of hours required to run program
157 self.mem = mem # GB RAM allocation requirement
158 self.procs = procs # Number of processors required for the job
159 self.p = None # The Subprocess Object
160 self.server = server
161 self.status = 'Initialised'
162 self.verbose = False # If True, Error messages are written to stdout.
163 if args: self.append_args(args)
164 self.wdir = ''
165 if wdir is not None:
166 if wdir != '' and not os.path.exists(wdir):
167 try:
168 # Create working directory
169 mkpath(wdir)
170 except Exception as e:
171 debug.graceful_exit(("Error: The specified working directory "
172 "(%s) does not exist, and could not be "
173 "created!")%(wdir))
174 self.wdir = wdir
175 def get_time(self):
176 """ This function returns the amount of time used by the program
177 (in seconds).
178 """
179 return self.timer
180 def get_status(self):
181 """ This function returns the amount of time used by the program
182 (in seconds).
183 """
184 # debug.log('status (%s): %s\n'%(self.name, self.status))
185 return self.status
186 def get_cmd(self):
187 """ This function combines and return the commanline call of the program.
188 """
189 cmd = []
190 if self.path is not None:
191 if '/' in self.path and not os.path.exists(self.path):
192 debug.log('Error: path contains / but does not exist: %s'%self.path)
193 else:
194 if self.ptype is not None:
195 if os.path.exists(self.ptype):
196 cmd.append(self.ptype)
197 elif '/' not in self.ptype:
198 for path in os.environ["PATH"].split(os.pathsep):
199 path = path.strip('"')
200 ppath = os.path.join(path, self.ptype)
201 if os.path.isfile(ppath):
202 cmd.append(ppath)
203 break
204 cmd.append(self.path)
205 if sys.version_info < (3, 0):
206 cmd.extend([str(x) if not isinstance(x, (unicode)) else x.encode('utf-8') for x in [quote(str(x)) for x in self.args]+self.unquoted_args])
207 else:
208 cmd.extend([str(x) for x in [quote(str(x)) for x in self.args]+self.unquoted_args])
209 else:
210 debug.log('Error: Program path not set!')
211 return ' '.join(cmd)
212 def update_timer(self, time):
213 """ This function updates the program timer. """
214 self.timer += time
215 def append_args(self, arg):
216 """ This function appends the provided arguments to the program object.
217 """
218 debug.log("Adding Arguments: %s"%(arg))
219 if isinstance(arg, (int,float)): self.args.append(str(arg))
220 if isinstance(arg, str): self.args.append(arg)
221 if isinstance(arg, list):
222 if sys.version_info < (3, 0):
223 self.args.extend([str(x) if not isinstance(x, (unicode)) else x.encode('utf-8') for x in arg])
224 else:
225 self.args.extend([str(x) for x in arg])
226 def execute(self):
227 """ This function Executes the program with set arguments. """
228 prog_cmd = self.get_cmd().strip()
229 if prog_cmd == '':
230 self.status = 'Failure'
231 debug.log("Error: No program to execute for %s!"%self.name)
232 debug.log(("Could not combine path and arguments into cmdline:"
233 "\n%s %s)\n")%(self.path, ' '.join(self.args)))
234 else:
235 debug.log("\n\nExecute %s...\n%s" % (self.name, prog_cmd))
236 # Create shell script
237 script = '%s.sh'%self.name
238 if self.wdir != '':
239 script = '%s/%s'%(self.wdir, script)
240 else:
241 script = '%s/%s'%(os.getcwd(), script)
242 with open_(script, 'w') as f:
243 f.write('#!/bin/bash\n')
244 if self.wdir != '':
245 f.write('cd {workdir}\n'.format(workdir=self.wdir))
246 f.write(
247 ('touch {stdout} {stderr}\n'
248 'chmod a+r {stdout} {stderr}\n'
249 '{cmd} 1> {stdout} 2> {stderr}\n'
250 'ec=$?\n').format(
251 stdout=self.stdout,
252 stderr=self.stderr,
253 cmd=prog_cmd
254 )
255 )
256 if not self.forcewait:
257 f.write(('if [ "$ec" -ne "0" ]; then echo "Error" >> {stderr}; '
258 'else echo "Done" >> {stderr}; fi\n').format(
259 stderr=self.stderr))
260 f.write('exit $ec\n')
261 os.chmod(script, 0o755)
262
263 if self.queue is not None:
264 # Setup execution of shell script through TORQUE
265 other_args = ''
266 if self.forcewait: other_args += "-K " # ADDING -K argument if wait() is forced
267 # QSUB INFO :: run_time_limit(walltime, dd:hh:mm:ss),
268 # memory(mem, up to 100GB *gigabyte),
269 # processors(ppn, up to 16) # USE AS LITTLE AS NEEDED!
270 cmd = ('/usr/bin/qsub '
271 '-l nodes=1:ppn={procs},walltime={hours}:00:00,mem={mem}g '
272 '-r y {workdir_arg} {other_args} {cmd}').format(
273 procs=self.procs,
274 hours=self.walltime,
275 mem=self.mem,
276 workdir_arg="-d %s"%(self.wdir) if self.wdir != '' else '',
277 other_args=other_args,
278 cmd=script)
279 debug.log("\n\nTORQUE SETUP %s...\n%s\n" % (self.name, cmd))
280 else:
281 cmd = script
282
283 if self.server is not None:
284 cmd = "ssh {server} {cmd}".format(
285 server=self.server,
286 cmd=quote(cmd)
287 )
288 self.status = 'Executing'
289 # EXECUTING PROGRAM
290 self.update_timer(-time()) # TIME START
291 if self.forcewait:
292 self.p = Popen(cmd)
293 ec = self.p.wait()
294 if ec == 0:
295 debug.log("Program finished successfully!")
296 self.status = 'Done'
297 else:
298 debug.log("Program failed on execution!")
299 self.status = 'Failure'
300 self.p = None
301 else: # WaitOn should be called to determine if the program has ended
302 debug.log("CMD: %s"%cmd)
303 self.p = Popen(cmd) # shell=True, executable="/bin/bash"
304 self.update_timer(time()) # TIME END
305 debug.log("timed: %s" % (self.get_time()))
306 def wait(self, pattern='Done', interval=None,
307 epatterns=['error','Error','STACK','Traceback']):
308 """ This function will wait on a given pattern being shown on the last
309 line of a given outputfile.
310
311 OPTIONS
312 pattern - The string pattern to recognise when a program
313 finished properly.
314 interval - The amount of seconds to wait between checking the
315 log file.
316 epatterns - A list of string patterns to recognise when a program
317 has finished with an error.
318 """
319 increasing_interval = False
320 if interval is None:
321 increasing_interval = True
322 interval = 10
323 if self.wdir != '':
324 stderr = "%s/%s"%(self.wdir, self.stderr)
325 else:
326 stderr = self.stderr
327 debug.log("\nWaiting for %s to finish..."%str(self.name))
328 if self.status == 'Executing':
329 self.update_timer(-time()) # TIME START
330 found = False
331 if self.queue is not None:
332 # Handling programs running on the compute servers
333 # Waiting for error log to be created.
334 # Prolonged waiting can be caused by the queue being full, or the
335 # server being unavailable.
336 debug.log(" Waiting for the error log to be created (%s)..."%(
337 stderr))
338 # Set maximum amount of seconds to wait on the errorlog creation,
339 # before assuming queue failure.
340 max_queued_time = 10800
341 while ( not os.path.exists(stderr)
342 and time()+self.timer < max_queued_time
343 and time()+self.timer > 0
344 ):
345 debug.log(" Waiting... (max wait time left: %s seconds)"%(
346 str(max_queued_time-time()-self.timer)))
347 sleep(interval)
348 if increasing_interval:
349 interval *= 1.1
350
351 if os.path.exists(stderr):
352 if increasing_interval:
353 interval = 10
354 # File created looking for pattern
355 debug.log('\nError log created, waiting for program to finish...')
356 # calculate max loops left based on set walltime and check interval
357 max_time = time() + self.walltime * 60 * 60
358 while time() < max_time:
359 with open_(stderr) as f:
360 for l in f.readlines()[-5:]: # last five lines
361 if pattern in l:
362 found = True
363 max_time = 0
364 break
365 elif any([ep in l for ep in epatterns]):
366 found = False
367 max_time = 0
368 break
369 if max_time > 0:
370 debug.log(' Waiting... (max wait-time left: %s seconds)'%(
371 str(max_time-time())))
372 sleep(interval)
373 if found:
374 debug.log(" Program finished successfully!")
375 self.status = 'Done'
376 else:
377 debug.log("Error: Program took too long, or finished with error!")
378 if self.verbose:
379 debug.print_out(
380 "Technical error occurred!\n",
381 "The service was not able to produce a result.\n",
382 ("Please check your settings are correct, and the file "
383 "type matches what you specified.\n"),
384 ("Try again, and if the problem persists please notify the"
385 " technical support.\n")
386 )
387 self.status = 'Failure'
388 else:
389 debug.log(
390 ("Error: %s still does not exist!\n")%(stderr),
391 ("This error might be caused by the cgebase not being "
392 "available!")
393 )
394 if self.verbose:
395 debug.print_out(
396 "Technical error occurred!\n",
397 ("This error might be caused by the server not being "
398 "available!\n"),
399 ("Try again later, and if the problem persists please notify "
400 "the technical support.\n"),
401 "Sorry for any inconvenience.\n"
402 )
403 self.status = 'Failure'
404 if not self.p is None:
405 self.p.wait()
406 self.p = None
407 else:
408 # Handling wrappers running on the webserver
409 if self.p is None:
410 debug.log("Program not instanciated!")
411 self.status = 'Failure'
412 else:
413 ec = self.p.wait()
414 if ec != 0:
415 debug.log("Program failed on execution!")
416 self.status = 'Failure'
417 elif os.path.exists(stderr):
418 with open_(stderr) as f:
419 for l in f.readlines()[-5:]: # last five lines
420 if pattern in l:
421 found = True
422 break
423 elif any([ep in l for ep in epatterns]):
424 found = False
425 break
426 if found:
427 debug.log(" Program finished successfully!")
428 self.status = 'Done'
429 else:
430 debug.log("Error: Program failed to finish properly!")
431 if self.verbose:
432 debug.print_out("Technical error occurred!\n",
433 "The service was not able to produce a result.\n",
434 "Please check your settings are correct, and the file "+
435 "type matches what you specified.", "Try again, and if "+
436 "the problem persists please notify the technical "+
437 "support.\n")
438 self.status = 'Failure'
439 else:
440 debug.log(("Error: %s does not exist!\n")%(stderr),
441 "This error might be caused by the cgebase not being "+
442 "available!")
443 if self.verbose:
444 debug.print_out("Technical error occurred!\n",
445 "This error might be caused by the server not being "+
446 "available!\n", "Try again later, and if the problem "+
447 "persists please notify the technical support.\n",
448 "Sorry for any inconvenience.\n")
449 self.status = 'Failure'
450 self.p = None
451 self.update_timer(time()) # TIME END
452 debug.log(" timed: %s"%(self.get_time()))
453 else:
454 debug.log(" The check-out of the program has been sorted previously.")
455 def print_stdout(self):
456 """ This function will read the standard out of the program and print it
457 """
458 # First we check if the file we want to print does exists
459 if self.wdir != '':
460 stdout = "%s/%s"%(self.wdir, self.stdout)
461 else:
462 stdout = self.stdout
463 if os.path.exists(stdout):
464 with open_(stdout, 'r') as f:
465 debug.print_out("\n".join([line for line in f]))
466 else: # FILE DOESN'T EXIST
467 debug.log("Error: The stdout file %s does not exist!"%(stdout))
468 def find_out_var(self, varnames=[]):
469 """ This function will read the standard out of the program, catch
470 variables and return the values
471
472 EG. #varname=value
473 """
474 if self.wdir != '':
475 stdout = "%s/%s"%(self.wdir, self.stdout)
476 else:
477 stdout = self.stdout
478 response = [None]*len(varnames)
479 # First we check if the file we want to print does exists
480 if os.path.exists(stdout):
481 with open_(stdout, 'r') as f:
482 for line in f:
483 if '=' in line:
484 var = line.strip('#').split('=')
485 value = var[1].strip()
486 var = var[0].strip()
487 if var in varnames: response[varnames.index(var)] = value
488 else: # FILE DOESN'T EXIST
489 debug.log("Error: The stdout file %s does not exist!"%(stdout))
490 return response
491 def find_err_pattern(self, pattern):
492 """ This function will read the standard error of the program and return
493 a matching pattern if found.
494
495 EG. prog_obj.FindErrPattern("Update of mySQL failed")
496 """
497 if self.wdir != '':
498 stderr = "%s/%s"%(self.wdir, self.stderr)
499 else:
500 stderr = self.stderr
501 response = []
502 # First we check if the file we want to print does exists
503 if os.path.exists(stderr):
504 with open_(stderr, 'r') as f:
505 for line in f:
506 if pattern in line:
507 response.append(line.strip())
508 else: # FILE DOESN'T EXIST
509 debug.log("Error: The stderr file %s does not exist!"%(stderr))
510 return response
511 def find_out_pattern(self, pattern):
512 """ This function will read the standard error of the program and return
513 a matching pattern if found.
514
515 EG. prog_obj.FindErrPattern("Update of mySQL failed")
516 """
517 if self.wdir != '':
518 stdout = "%s/%s"%(self.wdir, self.stdout)
519 else:
520 stdout = self.stdout
521 response = []
522 # First we check if the file we want to print does exists
523 if os.path.exists(stdout):
524 with open_(stdout, 'r') as f:
525 for line in f:
526 if pattern in line:
527 response.append(line.strip())
528 else: # FILE DOESN'T EXIST
529 debug.log("Error: The stdout file %s does not exist!"%(stdout))
530 return response
531
532 def cmd2list(cmd):
533 ''' Executes a command through the operating system and returns the output
534 as a list, or on error a string with the standard error.
535 EXAMPLE:
536 >>> from subprocess import Popen, PIPE
537 >>> CMDout2array('ls -l')
538 '''
539 p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
540 stdout, stderr = p.communicate()
541 if p.returncode != 0 and stderr != '':
542 return "ERROR: %s\n"%(stderr)
543 else:
544 return stdout.split('\n')
545
546 # Initiate Shared Global Objects
547 proglist = ProgramList()