Python wrapper for running instances of trisurf-ng
Samo Penic
2017-01-07 d50227ea034dae0fb6ee75a9a3941f786facaf16
commit | author | age
8ab985 1 import argparse
SP 2 import paramiko
3 from . import Remote
4 from . import trisurf
5 import socket
6 import os,sys
7 import tabulate
8 import subprocess,re
9 import psutil
10 #import http.server
11 #import socketserver
12 if sys.version_info>=(3,0):
13     from urllib.parse import urlparse
14     from . import WebTrisurf
15 else:
16     from urlparse import urlparse
17     from vtk import *
18     from . import VTKRendering
19 #import io
20
21 from IPython import embed
22
f0131d 23 import __main__ as main
SP 24
8ab985 25 #Color definitions for terminal
SP 26 class bcolors:
27     HEADER = '\033[95m'
28     OKBLUE = '\033[94m'
29     OKGREEN = '\033[92m'
30     WARNING = '\033[93m'
31     FAIL = '\033[91m'
32     ENDC = '\033[0m'
33     BOLD = '\033[1m'
34     UNDERLINE = '\033[4m'
35
36 #parses Command Line Arguments and returns the list of parsed values
37 def ParseCLIArguments(arguments):
38     parser = argparse.ArgumentParser(description='Manages (start, stop, status) multiple simulation processes of trisurf according to the configuration file.')
39     parser.add_argument('proc_no', metavar='PROC_NO', nargs='*',
40                 help='process number at host. If hostname is not specified, localhost is assumed. If no processes are specified all processes on all hosts are assumed.')
41     action_group=parser.add_mutually_exclusive_group(required=True)
42     action_group.add_argument('-c','--comment',nargs=1, help='append comment to current comment')
86c973 43     action_group.add_argument('--analysis', nargs='+', help='runs analysis function defined in configuration file')
8ab985 44     action_group.add_argument('--delete-comment', help='delete comment',action='store_true')
SP 45     action_group.add_argument('-k','--kill','--stop','--suspend', help='stop/kill the process', action='store_true')
46     action_group.add_argument('-r','--run','--start','--continue', help='start/continue process', action='store_true')
47     action_group.add_argument('-s','--status',help='print status of the processes',action='store_true')
48     action_group.add_argument('-v','--version', help='print version information and exit', action='store_true')
49     action_group.add_argument('--web-server', type=int,metavar="PORT", nargs=1, help='EXPERIMENTAL: starts web server and never exist.')
50     action_group.add_argument('--jump-to-ipython', help='loads the variables and jumps to IPython shell', action="store_true")
51     action_group.add_argument('-p','--preview',help='preview last VTU shape',action='store_true')
52     parser.add_argument('--force', help='if dangerous operation (killing all the processes) is requested, this flag is required to execute the operation. Otherwise, the request will be ignored.', action="store_true")
1c8250 53     parser.add_argument('-H', '--host', nargs='+', help='specifies which host is itended for the operation. Defauts to localhost for all operations except --status and --version, where all configured hosts are assumed.')
8ab985 54     parser.add_argument('--html', help='Generate HTML output', action="store_true")
SP 55     parser.add_argument('-n', nargs='+', metavar='PROC_NO', type=int, help='OBSOLETE. Specifies process numbers.')
56     parser.add_argument('-R','--raw',help='print status and the rest of the information in raw format', action="store_true")
57     parser.add_argument('-x','--local-only',help='do not attempt to contact remote hosts. Run all operations only on local machine',action='store_true')
58     args = parser.parse_args(arguments)
59     return args
60
61
62 #gets version of trisurf currently running
63 def getTrisurfVersion():
64     p = subprocess.Popen('trisurf --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
65     lines=p.stdout.readlines()
66     version=re.findall(r'[0-9a-f]{7}(?:-dirty)?', lines[0].decode('ascii'))
67     p.wait()
68     if(len(version)):
69         return version[0]
70     else:
71         return "unknown version"
72
73
74
75 def copyConfigAndConnect(hosts):
76     print("Connecting to remote hosts and copying config files, tapes and snapshots")
d7e21a 77     #create a list of files to be copied across all the remote hosts
SP 78     file_list=[]
79     for h in hosts:
80         for r in h['runs']:
81             if(r.isFromSnapshot):
82                 file_list.append(r.snapshotFilename)
83             else:
84                 file_list.append(r.tapeFilename)
85     file_list.append(main.__file__)
8ab985 86     for host in hosts:
SP 87         if(host['name'] !=socket.gethostname()): #if I am not the computer named in host name
88             try:
89                 username=host['username']
90             except:
91                 username=os.getusername() #default username is current user user's name
92             try:
93                 port=host['port']
94             except:
95                 port=22 #default ssh port
96             rm=Remote.Connection(hostname=host['address'],username=username, port=port)
97             rm.connect()
f0131d 98 #            print ("Sendind file:"+main.__file__)
d7e21a 99             if('remotebasepath' in host):
SP 100                 remote_dir=host['remotebasepath']
101             else:
102                 remote_dir='trisurf_simulations'
103             rm.send_multiple_files_in_directory(file_list,remote_dir)
104 #            rm.send_file(main.__file__,'remote_control.py')
105 #            for run in host['runs']:
106 #                try:
107 #                    rm.send_file(run.tapeFile,run.tapeFile)
108 #                except:
109 #                    pass
110 #                try:
111 #                    rm.send_file(run.snapshotFile,run.snapshotFile)
112 #                except:
113 #                    pass
8ab985 114             host['_conn']= rm
SP 115     # we are connected to all hosts...
116     return hosts
117
118
119
120 def getTargetRunIdxList(args):
121     target_runs=list(map(int,args['proc_no']))
122     if len(target_runs)==0:
123         #check if obsolete -n flags have numbers
124         target_runs=args['n']
125         if target_runs==None:
126             return None
127     target_runs=list(set(target_runs))
128     return target_runs
129
130
131
132 def status_processes(args,host):
133     target_runs=getTargetRunIdxList(args)
134     if target_runs==None:
135         target_runs=list(range(1,len(host['runs'])+1))
136     report=[]
f0131d 137 #    print("was here")
8ab985 138     for i in target_runs:
SP 139         line=host['runs'][i-1].getStatistics()
140         line.insert(0,i)
141         report.append(line)
142     if(args['raw']):
143         print(report)
144     else:
145         if(args['html']):
146             tablefmt='html'
147         else:
148             tablefmt='fancy_grid'
149         print(tabulate.tabulate(report,headers=["Run no.", "Run start time", "ETA", "Status", "PID", "Path", "Comment"], tablefmt=tablefmt))
150     return
151
152 def run_processes(args,host):
153     target_runs=getTargetRunIdxList(args)
154     if target_runs==None:
155         target_runs=list(range(1,len(host['runs'])+1))
156     for i in target_runs:
157         host['runs'][i-1].start()
158     return
159
160 def kill_processes(args,host):
161     target_runs=getTargetRunIdxList(args)
162     if target_runs==None:
163         if args['force']==True:
164             target_runs=list(range(1,len(host['runs'])+1))
165         else:
166             print("Not stopping all processes on the host. Run with --force flag if you are really sure to stop all simulations")
167             return
168     for i in target_runs:
169         host['runs'][i-1].stop()
170     return
171
172 def comment_processes(args,host):
173     target_runs=getTargetRunIdxList(args)
174     if target_runs==None:
175         target_runs=list(range(1,len(host['runs'])+1))
176     for i in target_runs:
177         host['runs'][i-1].writeComment(args['comment'][0],'a')
178     print("Comment added")
179     return
180
181 def delete_comments(args,host):
182     target_runs=getTargetRunIdxList(args)
183     if target_runs==None:
184         if args['force']==True:
185             target_runs=list(range(1,len(host['runs'])+1))
186         else:
187             print("Not deleting comments on all posts on the host. Run with --force flag if you are really sure to delete all comments")
188             return
189     for i in target_runs:
190         host['runs'][i-1].writeComment("")
191     print("Comment deleted")
192     return
193
194
195 def start_web_server(args,host):
196     print('Server listening on port {}'.format(args['web_server'][0]))
197     if sys.version_info>=(3,0):
198         WebTrisurf.WebServer(port=args['web_server'][0])
199     else:
200         print("Cannot start WebServer in python 2.7")
201     exit(0)
202
f0131d 203
1c8250 204 def analyze(args,host,a_dict, analysis,hosts):
86c973 205     if len(a_dict)==0:
SP 206         print ('Error: no analyses are specified in the tsmgr.start()!')
207         exit(1)
f0131d 208     target_runs=getTargetRunIdxList(args)
SP 209     if target_runs==None:
210         target_runs=list(range(1,len(host['runs'])+1))
211     for i in target_runs:
212
213         for anal in analysis:
214             if(anal not in a_dict):
215                 print("Analysis '"+anal+"' is not known. Available analyses: "+", ".join(a_dict.keys())+".")
216                 exit(0)
217         for anal in analysis:
1c8250 218             retval=a_dict[anal](host['runs'][i-1],host=host, args=args, hosts=hosts)
8c3c29 219             #try:
SP 220             if(retval):
221                 exit(0)
222             #except:
223             #    pass
f0131d 224
1c8250 225
SP 226     
f0131d 227
SP 228 def perform_action(args,host,**kwargs):
8ab985 229     #find which flags have been used and act upon them. -r -s -k -v -c --delete-comment are mutually exclusive, so only one of them is active
SP 230     if args['run']:
231         run_processes(args,host)
232     elif args['kill']:
233         kill_processes(args,host)
234     elif args['status']:
235         status_processes(args,host)
236     elif args['comment']!= None:
237         comment_processes(args,host)
238     elif args['delete_comment']:
239         delete_comments(args,host)
240     elif args['web_server']!=None:
241         start_web_server(args,host)
242     elif args['preview']:
243         preview_vtu(args,host)
244     elif args['jump_to_ipython']:
245         print('Jumping to shell...')
246         embed()
f0131d 247         exit(0)
SP 248     elif args['analysis']!= None:
1c8250 249         analyze(args,host,kwargs.get('analyses', {}), args['analysis'],kwargs.get('hosts',None))
8ab985 250         exit(0)
SP 251     else: #version requested
252         print(getTrisurfVersion())
253     return
254
255
256
257 def preview_vtu(args,host):
258     #only for localhost at the moment
259     if sys.version_info>=(3,0):
260         print("Preview works only with python 2.7")
261         exit(1)
262     if host['name'] == socket.gethostname():
263         VTKRendering.Renderer(args,host)
264
265 def getListOfHostConfigurationByHostname(hosts,host):
266     rhost=[]
267     for chost in hosts:
268         if chost['name'] in host:
269             rhost.append(chost)
270     return rhost
271
272
273
f0131d 274 def start(hosts,argv=sys.argv[1:], analyses={}):
8ab985 275     args=vars(ParseCLIArguments(argv))
SP 276     #Backward compatibility... If running just on localmode, the host specification is unnecessary. Check if only Runs are specified
277     try:
278         test_host=hosts[0]['name']
279     except:
f0131d 280         print("Old syntax detected.")
SP 281         hosts=({'name':socket.gethostname(),'address':'127.0.0.1', 'runs':hosts},)
8ab985 282
SP 283     #find the host at which the action is attended
284     if args['host']==None:
1c8250 285         #Only status and version commands are automatically executed on all the hosts. stopping or starting  or other actions is not!
8ab985 286         if(args['status']==False and args['version']==False):
SP 287             hosts=getListOfHostConfigurationByHostname(hosts,socket.gethostname())
288     else:
289         hosts=getListOfHostConfigurationByHostname(hosts,args['host'])
290     if len(hosts)==0:
291         print ('Hostname "{}" does not exist in configuration file. Please check the spelling'.format(args['host'][0]))
292         exit(1)
293     if not args['local_only']:
294             hosts=copyConfigAndConnect(hosts)
295     #do local stuff:
296     for host in hosts:
297         if host['name'] == socket.gethostname():
298             if(args['html']):
8c3c29 299                 print("Host <font color='orange'>"+host['name']+"</font> reports:")
8ab985 300             else:
8c3c29 301                 print("Host "+bcolors.WARNING+host['name']+bcolors.ENDC+" reports:")
1c8250 302             perform_action(args,host, analyses=analyses, hosts=hosts)
8ab985 303         elif not args['local_only']:
d7e21a 304             if('remotebasepath' in host):
SP 305                 remote_dir=host['remotebasepath']
306             else:
307                 remote_dir='trisurf_simulations'
4e6b88 308             #output=host['_conn'].execute('cd '+remote_dir)
SP 309             #print(remote_dir)
310             #print(main.__file__)
311             #print('python3 '+main.__file__+' -x '+" ".join(argv))
312             output=host['_conn'].execute('cd '+remote_dir+ '; python3 '+main.__file__+' -x '+" ".join(argv))
8ab985 313             for line in output:
SP 314                 print(line.replace('\n',''))
315
316
317     if not args['local_only']:
318         print("Closing connections to remote hosts")
319         for host in hosts:
320             if(host['name'] !=socket.gethostname()):
321                 host['_conn'].disconnect()
322
323
324