Python wrapper for running instances of trisurf-ng
Samo Penic
2017-01-14 f49271578b8fac02db14966e7aab121879f9b736
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 *
8b7022 18     
8ab985 19 #import io
SP 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')
6f912f 58     parser.add_argument('--originating-host',nargs=1,help='specify which host started the remote connections. Useful mainly fo internal functionaly of tsmgr and analyses.')
8ab985 59     args = parser.parse_args(arguments)
SP 60     return args
61
62
63 #gets version of trisurf currently running
64 def getTrisurfVersion():
65     p = subprocess.Popen('trisurf --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
66     lines=p.stdout.readlines()
67     version=re.findall(r'[0-9a-f]{7}(?:-dirty)?', lines[0].decode('ascii'))
68     p.wait()
69     if(len(version)):
70         return version[0]
71     else:
72         return "unknown version"
73
74
75
76 def copyConfigAndConnect(hosts):
77     print("Connecting to remote hosts and copying config files, tapes and snapshots")
d7e21a 78     #create a list of files to be copied across all the remote hosts
SP 79     file_list=[]
80     for h in hosts:
81         for r in h['runs']:
82             if(r.isFromSnapshot):
a5f021 83                 file_list.append(r.snapshotFile)
d7e21a 84             else:
SP 85                 file_list.append(r.tapeFilename)
86     file_list.append(main.__file__)
8ab985 87     for host in hosts:
SP 88         if(host['name'] !=socket.gethostname()): #if I am not the computer named in host name
89             try:
90                 username=host['username']
91             except:
92                 username=os.getusername() #default username is current user user's name
93             try:
94                 port=host['port']
95             except:
96                 port=22 #default ssh port
97             rm=Remote.Connection(hostname=host['address'],username=username, port=port)
98             rm.connect()
f0131d 99 #            print ("Sendind file:"+main.__file__)
d7e21a 100             if('remotebasepath' in host):
SP 101                 remote_dir=host['remotebasepath']
102             else:
103                 remote_dir='trisurf_simulations'
104             rm.send_multiple_files_in_directory(file_list,remote_dir)
105 #            rm.send_file(main.__file__,'remote_control.py')
106 #            for run in host['runs']:
107 #                try:
108 #                    rm.send_file(run.tapeFile,run.tapeFile)
109 #                except:
110 #                    pass
111 #                try:
112 #                    rm.send_file(run.snapshotFile,run.snapshotFile)
113 #                except:
114 #                    pass
8ab985 115             host['_conn']= rm
SP 116     # we are connected to all hosts...
117     return hosts
118
119
120
121 def getTargetRunIdxList(args):
122     target_runs=list(map(int,args['proc_no']))
123     if len(target_runs)==0:
124         #check if obsolete -n flags have numbers
125         target_runs=args['n']
126         if target_runs==None:
127             return None
128     target_runs=list(set(target_runs))
129     return target_runs
130
131
132
133 def status_processes(args,host):
134     target_runs=getTargetRunIdxList(args)
135     if target_runs==None:
136         target_runs=list(range(1,len(host['runs'])+1))
137     report=[]
f0131d 138 #    print("was here")
8ab985 139     for i in target_runs:
SP 140         line=host['runs'][i-1].getStatistics()
141         line.insert(0,i)
142         report.append(line)
143     if(args['raw']):
144         print(report)
145     else:
146         if(args['html']):
147             tablefmt='html'
148         else:
149             tablefmt='fancy_grid'
150         print(tabulate.tabulate(report,headers=["Run no.", "Run start time", "ETA", "Status", "PID", "Path", "Comment"], tablefmt=tablefmt))
151     return
152
153 def run_processes(args,host):
154     target_runs=getTargetRunIdxList(args)
155     if target_runs==None:
156         target_runs=list(range(1,len(host['runs'])+1))
157     for i in target_runs:
158         host['runs'][i-1].start()
159     return
160
161 def kill_processes(args,host):
162     target_runs=getTargetRunIdxList(args)
163     if target_runs==None:
164         if args['force']==True:
165             target_runs=list(range(1,len(host['runs'])+1))
166         else:
167             print("Not stopping all processes on the host. Run with --force flag if you are really sure to stop all simulations")
168             return
169     for i in target_runs:
170         host['runs'][i-1].stop()
171     return
172
173 def comment_processes(args,host):
174     target_runs=getTargetRunIdxList(args)
175     if target_runs==None:
176         target_runs=list(range(1,len(host['runs'])+1))
177     for i in target_runs:
178         host['runs'][i-1].writeComment(args['comment'][0],'a')
179     print("Comment added")
180     return
181
182 def delete_comments(args,host):
183     target_runs=getTargetRunIdxList(args)
184     if target_runs==None:
185         if args['force']==True:
186             target_runs=list(range(1,len(host['runs'])+1))
187         else:
188             print("Not deleting comments on all posts on the host. Run with --force flag if you are really sure to delete all comments")
189             return
190     for i in target_runs:
191         host['runs'][i-1].writeComment("")
192     print("Comment deleted")
193     return
194
195
196 def start_web_server(args,host):
197     print('Server listening on port {}'.format(args['web_server'][0]))
198     if sys.version_info>=(3,0):
199         WebTrisurf.WebServer(port=args['web_server'][0])
200     else:
201         print("Cannot start WebServer in python 2.7")
202     exit(0)
203
f0131d 204
1c8250 205 def analyze(args,host,a_dict, analysis,hosts):
86c973 206     if len(a_dict)==0:
SP 207         print ('Error: no analyses are specified in the tsmgr.start()!')
208         exit(1)
f0131d 209     target_runs=getTargetRunIdxList(args)
SP 210     if target_runs==None:
211         target_runs=list(range(1,len(host['runs'])+1))
212     for i in target_runs:
213
214         for anal in analysis:
215             if(anal not in a_dict):
216                 print("Analysis '"+anal+"' is not known. Available analyses: "+", ".join(a_dict.keys())+".")
217                 exit(0)
218         for anal in analysis:
1c8250 219             retval=a_dict[anal](host['runs'][i-1],host=host, args=args, hosts=hosts)
8c3c29 220             #try:
SP 221             if(retval):
222                 exit(0)
223             #except:
224             #    pass
f0131d 225
1c8250 226
SP 227     
f0131d 228
SP 229 def perform_action(args,host,**kwargs):
8ab985 230     #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 231     if args['run']:
232         run_processes(args,host)
233     elif args['kill']:
234         kill_processes(args,host)
235     elif args['status']:
236         status_processes(args,host)
237     elif args['comment']!= None:
238         comment_processes(args,host)
239     elif args['delete_comment']:
240         delete_comments(args,host)
241     elif args['web_server']!=None:
242         start_web_server(args,host)
243     elif args['preview']:
244         preview_vtu(args,host)
245     elif args['jump_to_ipython']:
246         print('Jumping to shell...')
247         embed()
f0131d 248         exit(0)
SP 249     elif args['analysis']!= None:
1c8250 250         analyze(args,host,kwargs.get('analyses', {}), args['analysis'],kwargs.get('hosts',None))
8ab985 251         exit(0)
SP 252     else: #version requested
253         print(getTrisurfVersion())
254     return
255
256
257
258 def preview_vtu(args,host):
d00e25 259     from . import VTKRendering
f49271 260     target_runs=getTargetRunIdxList(args)
SP 261     if target_runs==None:
262         target_runs=list(range(1,len(host['runs'])+1))
8ab985 263     if host['name'] == socket.gethostname():
f49271 264         for i in target_runs:
SP 265             VTKRendering.Renderer(args,host,host['runs'][i-1])
266     else:
267         print("VTK rendering currently works on localhost only!")
268         
8ab985 269
SP 270 def getListOfHostConfigurationByHostname(hosts,host):
271     rhost=[]
272     for chost in hosts:
273         if chost['name'] in host:
274             rhost.append(chost)
275     return rhost
276
277
278
f0131d 279 def start(hosts,argv=sys.argv[1:], analyses={}):
8ab985 280     args=vars(ParseCLIArguments(argv))
SP 281     #Backward compatibility... If running just on localmode, the host specification is unnecessary. Check if only Runs are specified
282     try:
283         test_host=hosts[0]['name']
284     except:
f0131d 285         print("Old syntax detected.")
SP 286         hosts=({'name':socket.gethostname(),'address':'127.0.0.1', 'runs':hosts},)
8ab985 287
SP 288     #find the host at which the action is attended
289     if args['host']==None:
1c8250 290         #Only status and version commands are automatically executed on all the hosts. stopping or starting  or other actions is not!
8ab985 291         if(args['status']==False and args['version']==False):
SP 292             hosts=getListOfHostConfigurationByHostname(hosts,socket.gethostname())
293     else:
294         hosts=getListOfHostConfigurationByHostname(hosts,args['host'])
295     if len(hosts)==0:
296         print ('Hostname "{}" does not exist in configuration file. Please check the spelling'.format(args['host'][0]))
297         exit(1)
298     if not args['local_only']:
299             hosts=copyConfigAndConnect(hosts)
300     #do local stuff:
301     for host in hosts:
302         if host['name'] == socket.gethostname():
303             if(args['html']):
8c3c29 304                 print("Host <font color='orange'>"+host['name']+"</font> reports:")
8ab985 305             else:
8c3c29 306                 print("Host "+bcolors.WARNING+host['name']+bcolors.ENDC+" reports:")
1c8250 307             perform_action(args,host, analyses=analyses, hosts=hosts)
8ab985 308         elif not args['local_only']:
d7e21a 309             if('remotebasepath' in host):
SP 310                 remote_dir=host['remotebasepath']
311             else:
312                 remote_dir='trisurf_simulations'
4e6b88 313             #output=host['_conn'].execute('cd '+remote_dir)
SP 314             #print(remote_dir)
315             #print(main.__file__)
316             #print('python3 '+main.__file__+' -x '+" ".join(argv))
a5f021 317             output=host['_conn'].execute('cd '+remote_dir+ '; python3 '+main.__file__+' -x --originating-host ' +socket.gethostname()+" "+" ".join(argv))
8ab985 318             for line in output:
SP 319                 print(line.replace('\n',''))
320
321
322     if not args['local_only']:
323         print("Closing connections to remote hosts")
324         for host in hosts:
325             if(host['name'] !=socket.gethostname()):
326                 host['_conn'].disconnect()
327
328
329