Python wrapper for running instances of trisurf-ng
Samo Penic
2017-01-06 f0131dcc3b40089ad3129535aa9c3f4965452c39
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')
f0131d 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")
53     parser.add_argument('-H', '--host', nargs=1, 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.')
54     parser.add_argument('--html', help='Generate HTML output', action="store_true")
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")
77     for host in hosts:
78         if(host['name'] !=socket.gethostname()): #if I am not the computer named in host name
79             try:
80                 username=host['username']
81             except:
82                 username=os.getusername() #default username is current user user's name
83             try:
84                 port=host['port']
85             except:
86                 port=22 #default ssh port
87             rm=Remote.Connection(hostname=host['address'],username=username, port=port)
88             rm.connect()
f0131d 89 #            print ("Sendind file:"+main.__file__)
SP 90             rm.send_file(main.__file__,'remote_control.py')
8ab985 91             for run in host['runs']:
SP 92                 try:
93                     rm.send_file(run.tapeFile,run.tapeFile)
94                 except:
95                     pass
96                 try:
97                     rm.send_file(run.snapshotFile,run.snapshotFile)
98                 except:
99                     pass
100             host['_conn']= rm
101     # we are connected to all hosts...
102     return hosts
103
104
105
106 def getTargetRunIdxList(args):
107     target_runs=list(map(int,args['proc_no']))
108     if len(target_runs)==0:
109         #check if obsolete -n flags have numbers
110         target_runs=args['n']
111         if target_runs==None:
112             return None
113     target_runs=list(set(target_runs))
114     return target_runs
115
116
117
118 def status_processes(args,host):
119     target_runs=getTargetRunIdxList(args)
120     if target_runs==None:
121         target_runs=list(range(1,len(host['runs'])+1))
122     report=[]
f0131d 123 #    print("was here")
8ab985 124     for i in target_runs:
SP 125         line=host['runs'][i-1].getStatistics()
126         line.insert(0,i)
127         report.append(line)
128     if(args['raw']):
129         print(report)
130     else:
131         if(args['html']):
132             tablefmt='html'
133         else:
134             tablefmt='fancy_grid'
135         print(tabulate.tabulate(report,headers=["Run no.", "Run start time", "ETA", "Status", "PID", "Path", "Comment"], tablefmt=tablefmt))
136     return
137
138 def run_processes(args,host):
139     target_runs=getTargetRunIdxList(args)
140     if target_runs==None:
141         target_runs=list(range(1,len(host['runs'])+1))
142     for i in target_runs:
143         host['runs'][i-1].start()
144     return
145
146 def kill_processes(args,host):
147     target_runs=getTargetRunIdxList(args)
148     if target_runs==None:
149         if args['force']==True:
150             target_runs=list(range(1,len(host['runs'])+1))
151         else:
152             print("Not stopping all processes on the host. Run with --force flag if you are really sure to stop all simulations")
153             return
154     for i in target_runs:
155         host['runs'][i-1].stop()
156     return
157
158 def comment_processes(args,host):
159     target_runs=getTargetRunIdxList(args)
160     if target_runs==None:
161         target_runs=list(range(1,len(host['runs'])+1))
162     for i in target_runs:
163         host['runs'][i-1].writeComment(args['comment'][0],'a')
164     print("Comment added")
165     return
166
167 def delete_comments(args,host):
168     target_runs=getTargetRunIdxList(args)
169     if target_runs==None:
170         if args['force']==True:
171             target_runs=list(range(1,len(host['runs'])+1))
172         else:
173             print("Not deleting comments on all posts on the host. Run with --force flag if you are really sure to delete all comments")
174             return
175     for i in target_runs:
176         host['runs'][i-1].writeComment("")
177     print("Comment deleted")
178     return
179
180
181 def start_web_server(args,host):
182     print('Server listening on port {}'.format(args['web_server'][0]))
183     if sys.version_info>=(3,0):
184         WebTrisurf.WebServer(port=args['web_server'][0])
185     else:
186         print("Cannot start WebServer in python 2.7")
187     exit(0)
188
f0131d 189
SP 190 def analyze(args,host,a_dict, analysis):
191     target_runs=getTargetRunIdxList(args)
192     if target_runs==None:
193         target_runs=list(range(1,len(host['runs'])+1))
194     for i in target_runs:
195
196         for anal in analysis:
197             if(anal not in a_dict):
198                 print("Analysis '"+anal+"' is not known. Available analyses: "+", ".join(a_dict.keys())+".")
199                 exit(0)
200         for anal in analysis:
201             a_dict[anal](host['runs'][i-1],host=host)
202
203
204 def perform_action(args,host,**kwargs):
8ab985 205     #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 206     if args['run']:
207         run_processes(args,host)
208     elif args['kill']:
209         kill_processes(args,host)
210     elif args['status']:
211         status_processes(args,host)
212     elif args['comment']!= None:
213         comment_processes(args,host)
214     elif args['delete_comment']:
215         delete_comments(args,host)
216     elif args['web_server']!=None:
217         start_web_server(args,host)
218     elif args['preview']:
219         preview_vtu(args,host)
220     elif args['jump_to_ipython']:
221         print('Jumping to shell...')
222         embed()
f0131d 223         exit(0)
SP 224     elif args['analysis']!= None:
225         analyze(args,host,kwargs.get('analyses', {}), args['analysis'])
8ab985 226         exit(0)
SP 227     else: #version requested
228         print(getTrisurfVersion())
229     return
230
231
232
233 def preview_vtu(args,host):
234     #only for localhost at the moment
235     if sys.version_info>=(3,0):
236         print("Preview works only with python 2.7")
237         exit(1)
238     if host['name'] == socket.gethostname():
239         VTKRendering.Renderer(args,host)
240
241 def getListOfHostConfigurationByHostname(hosts,host):
242     rhost=[]
243     for chost in hosts:
244         if chost['name'] in host:
245             rhost.append(chost)
246     return rhost
247
248
249
f0131d 250 def start(hosts,argv=sys.argv[1:], analyses={}):
8ab985 251     args=vars(ParseCLIArguments(argv))
SP 252     #print(vars(args))
253
254     #Backward compatibility... If running just on localmode, the host specification is unnecessary. Check if only Runs are specified
255     try:
256         test_host=hosts[0]['name']
257     except:
f0131d 258         print("Old syntax detected.")
SP 259         hosts=({'name':socket.gethostname(),'address':'127.0.0.1', 'runs':hosts},)
8ab985 260
SP 261
262     #find the host at which the action is attended
263     if args['host']==None:
264         if(args['status']==False and args['version']==False):
265             hosts=getListOfHostConfigurationByHostname(hosts,socket.gethostname())
266     else:
267         hosts=getListOfHostConfigurationByHostname(hosts,args['host'])
268     if len(hosts)==0:
269         print ('Hostname "{}" does not exist in configuration file. Please check the spelling'.format(args['host'][0]))
270         exit(1)
271
272     if not args['local_only']:
273             hosts=copyConfigAndConnect(hosts)
274
275     #do local stuff:
276     for host in hosts:
277         if host['name'] == socket.gethostname():
278             if(args['html']):
279                 print("Host <font color='orange'>"+host['name']+"</font> reports the following:")
280             else:
281                 print("Host "+bcolors.WARNING+host['name']+bcolors.ENDC+" reports the following:")
f0131d 282             perform_action(args,host, analyses=analyses)
8ab985 283         elif not args['local_only']:
SP 284             output=host['_conn'].execute('python3 ./remote_control.py -x '+" ".join(argv))
285             for line in output:
286                 print(line.replace('\n',''))
287
288
289     if not args['local_only']:
290         print("Closing connections to remote hosts")
291         for host in hosts:
292             if(host['name'] !=socket.gethostname()):
293                 host['_conn'].disconnect()
294
295
296