xentaur

view xentaur.py @ 32:bf2d7c5bb340

dump try and catch
author igor
date Sat Sep 22 01:35:51 2007 +0300 (2007-09-22)
parents 532f2ed25f70
children c68d804c3017
line source
1 #!/usr/bin/python
4 import sys,os,time
5 import xenomips_vars
6 xenomips_vars.N='1'
7 sys.path.append('/etc/xen')
9 xen_config_name='fabergeN'
10 try:
11 exec 'from '+xen_config_name+' import bridges,vbridges_table, hidden_bridges, domains, broken_links, temporary_links, domain_types'
12 except:
13 print "Can't find module: %s " % (xen_config_name)
14 sys.exit(0)
16 bridges_turned_down=[]
18 from IPython.Shell import IPShellEmbed
21 screenrc=os.environ['HOME']+"/.screenrc_xentaur"
23 def run(program, *args):
24 pid = os.fork()
25 if not pid:
26 os.execvp(program, (program,) + args)
27 return os.wait()[0]
29 def run_command(line):
30 #cmds=line.split()
31 #run(cmds[0],*cmds[1:])
32 run("/bin/sh", "-c", line)
34 def run_command_return_stdout(line):
35 p = os.popen(line)
36 output = p.read()
37 p.close()
38 return output
40 def create_bridges_script():
41 unbound_bridges=bridges
42 create_unbound_bridges="\n".join(map(lambda x: "sudo /usr/sbin/brctl show | awk '{print $1}' | grep -q "+x+" || sudo /usr/sbin/brctl addbr "+x, unbound_bridges))
43 create_unbound_bridges+="\n"+"\n".join(map(lambda x: "sudo /bin/ip link set "+x+" up", unbound_bridges))
45 print """#!/bin/sh
46 # create unbound bridges
47 %(create_unbound_bridges)s
48 """ % {'create_unbound_bridges' : create_unbound_bridges}
51 def create_domains_script():
52 for N in range(len(domains)):
53 print "sudo /usr/sbin/xm create "+xen_config_name+" N="+str(N)+" && sleep 1 && sudo /usr/sbin/xm sched-credit -d $(sudo /usr/sbin/xm list | grep "+domains[N]+" | awk '{print $2}') -c 10 && sleep 1"
55 def destroy_domains_script():
56 for N in range(len(domains)):
57 print "sudo /usr/sbin/xm shutdown "+domains[N]
59 def create_screens_script():
61 N=1
62 screens=[]
63 for domain in domains:
64 screens.append("screen -t "+domain+" "+str(N)+" sh -c 'while true; do sudo xm console "+domain+" ; echo Retrying in 5 seconds...; sleep 5; done'")
65 N+=1
66 screenlist="\n".join(screens)
68 #
69 # Previous terminal acccess commands:
70 # ip="192.168.80."+str(200+N)
71 # screens.append("screen -t "+domain+" "+str(N)+" sh -c 'while true; do ssh root@"+ip+" ; done'")
72 #
74 #hardstatus string "\%{gk}\%c \%{yk}\%M\%d \%{wk}\%?\%-Lw\%?\%{bw}\%n*\%f\%t\%?(\%u)\%?\%{wk}\%?\%+Lw\%?"
76 f=open(screenrc, "w");
77 f.write("""
78 hardstatus on
79 hardstatus alwayslastline
81 screen -t console 0 bash
82 %s
83 """ % (screenlist))
84 f.close()
86 def graph_node(node):
87 i=0
88 domain_type={}
89 for domain in domains:
90 domain_type[domain]=domain_types[i]
91 i+=1
92 return node+" [label=\" "+node+"\",shapefile=\"shapes/all/"+domain_type[node]+".png\",fontcolor=black,fontsize=16]"
94 def graph_bridge(bridge):
95 if bridge in hidden_bridges:
96 return ""
97 if bridge in bridges_turned_down:
98 return "%s [shape=none,shapefile=\"shapes/all/switch_turned_down.png\"]" % (bridge)
99 else:
100 return "%s [shape=none,shapefile=\"shapes/all/switch.png\"]" % (bridge)
103 def graph():
104 nodelist=""
105 bridgelist=""
106 linklist=""
107 physicallist=""
108 networklist=""
110 nodelist=";\n ".join(map(graph_node,nodes))
111 if nodelist: nodelist += ";"
113 bridgelist=";\n ".join(map(graph_bridge,bridges))
114 if bridgelist: bridgelist += ";"
116 links=[]
117 for host, bridges_raw in vbridges_table.iteritems():
118 i=0
119 for this_bridge in bridges_raw:
120 if this_bridge in hidden_bridges or not this_bridge:
121 continue
122 if not [ host, bridges_raw.index(this_bridge), this_bridge ] in temporary_links:
123 links.append(host+" -- "+this_bridge+" [taillabel=\"fa"+str(bridges_raw.index(this_bridge))+"/0\"]")
124 i+=1
125 # if [ host, this_bridge ] in broken_links:
126 # links.append(host+" -- "+this_bridge+" [taillabel=\"fa"+str(i)+"/0\",style=dashed]")
127 # else:
128 # links.append(host+" -- "+this_bridge+" [taillabel=\"fa"+str(i)+"/0\"]")
130 for link in temporary_links:
131 links.append(link[0]+" -- "+link[2]+" [taillabel=\"fa"+str(link[1])+"/0\",color=blue,len=10,w=5,weight=5]")
133 for link in broken_links:
134 links.append(link[0]+" -- "+link[2]+" [taillabel=\"fa"+str(link[1])+"/0\",style=dashed]")
136 linklist=";\n ".join(links)
138 graph_dot = {
139 'nodelist' : nodelist,
140 'bridgelist' : bridgelist,
141 'linklist' : linklist,
142 'physicallist' : physicallist,
143 'networklist' : networklist,
144 }
146 f = open("xenomips.dot", "w");
147 f.write ("""
148 graph G {
149 edge [len=1.25];
150 splines=true;
151 // nodes
153 node [shape=plaintext,color=white,shapefile="shapes/cisco.bmp/router.png"];
154 %(nodelist)s
156 // bridges
158 node [shape=none,shapefile="shapes/all/switch.png"];
159 %(bridgelist)s
161 // physical
163 node [shape=rectangle,color=blue];
164 %(physicallist)s
166 // networks (not bridges, not physical)
167 node [shape=rectangle,color=green];
168 %(networklist)s
170 // links (between nodes and bridges)
171 %(linklist)s
173 };
174 """ % graph_dot)
175 f.close()
176 run_command("neato -Tpng -o xenomips.png xenomips.dot ")
178 def autoredraw():
179 graph()
181 def start_all():
182 create_bridges_script()
183 create_screens_script()
184 create_domains_script()
185 graph()
186 print """
187 cat <<NOTE_FOR_USER
188 # To view virtual network map, run:
189 gqview xenomips.png
190 # To attach to VM consoles, run:
191 screen -c screenrc
192 NOTE_FOR_USER
193 """
195 def shell():
196 autoredraw()
197 ipshell = IPShellEmbed()
198 ipshell()
200 def stop_all():
201 destroy_domains_script()
203 def show_usage():
204 print """Usage:
205 xentaur {start|stop|start-bridges|start-domains|stop-domains|screen|graph}
206 """
208 #-----------------------------------------------------------------------
209 # DOMAINS
211 def get_domain_id(domain):
212 return run_command_return_stdout("sudo xm list | awk '{if ($1 == \"'%s'\") print $2}'" % domain).rstrip("\n")
215 #-----------------------------------------------------------------------
216 # BRIDGES and IFACES
218 def bridge_down(bridge):
219 """
220 Turn the bridge <bridge> down
221 """
222 if bridge in bridges_turned_down:
223 print "Bridge %s is turned down already" % (bridge)
224 else:
225 bridges_turned_down.append(bridge)
226 run_command("sudo ip link set %s down" % bridge)
227 autoredraw()
229 def bridge_up(bridge):
230 """
231 Turn the bridge <bridge> up
232 """
233 if not (bridge in bridges_turned_down):
234 print "Bridge %s is turned up already" % (bridge)
235 else:
236 bridges_turned_down.remove(bridge)
237 run_command("sudo ip link set %s up" % bridge)
238 autoredraw()
240 def show_bridge(bridge):
241 """
242 Show the state of the bridge <bridge>
243 """
244 run_command("sudo ip link show %s" % bridge)
247 def int_disconnect(domain, int_number):
248 """
249 Disconnect the interface with the number <int_number>
250 of the domain <domain> from the bridge to which
251 it is connected
252 """
253 dom_id=get_domain_id(domain)
254 bridge=vbridges_table[domain][int_number]
255 if not bridge:
256 print "Interface %s of the %s domain is not connected" % (int_number, domain)
257 return 1
258 run_command("sudo brctl delif %s vif%s.%s" % (bridge, dom_id, int_number))
259 vbridges_table[domain][int_number]=''
260 if [ domain, int_number, bridge ] in temporary_links:
261 temporary_links.remove([ domain, int_number, bridge ])
262 else:
263 broken_links.append([ domain, int_number, bridge ])
264 autoredraw()
266 def int_connect(domain, int_number, bridge):
267 """
268 Connect the interface with the number <int_number>
269 of the domain <domain> to the bridge <bridge>
270 """
271 dom_id=get_domain_id(domain)
273 if vbridges_table[domain][int_number]:
274 print "Interface %s of the %s domain is connected already to the %s bridge" % (int_number, domain, vbridges_table[domain][int_number])
275 return 1
276 run_command("sudo brctl addif %s vif%s.%s" % (bridge, dom_id, int_number))
277 vbridges_table[domain][int_number]=bridge
278 if [ domain, int_number, bridge ] in broken_links:
279 broken_links.remove([ domain, int_number, bridge ])
280 else:
281 temporary_links.append([ domain, int_number, bridge ])
282 autoredraw()
284 def int_reconnect(domain, int_number, bridge):
285 """
286 Reconnect the interface with the number <int_number>
287 of the domain <domain> from the bridge to which
288 it is connected to the bridge <bridge>
289 """
290 int_disconnect(domain, int_number)
291 int_connect(domain, int_number, bridge)
293 def show_int(domain, int_number):
294 """
295 Show information about the interface <int_nuber>
296 of the domain <domain>
297 """
298 return vbridges_table[domain][int_number]
301 def dump_start(bridge, filter=""):
302 try:
303 print "Writing dump... (press Ctrl-C to stop)"
304 run_command("sudo tcpdump -w xentaur.dump -i %s %s > /dev/null 2>&1 " % (bridge,filter))
305 except:
306 print "Done.\n Dump is written to xentaur.dump"
307 return 0
309 def dump_stop():
310 return 0
312 #-----------------------------------------------------------------------
315 def add_domain(name,type):
316 domains.append(name)
317 domain_types.append(type)
319 def brake_link(domain,bridge):
320 broken_links.append([domain,bridge])
322 wt_timeout=0.5
323 def write_to(screen,string,return_to_screen=""):
324 """
325 write_to(screen,string):
327 Type *string* to the specified screen(s).
328 Screen may be specified with the number *screen*,
329 with array of numbers,
330 with array of names.
332 """
333 screen_numbers=[] # number of the screens to write to
334 if type(screen) == list:
335 screen_numbers=map(lambda x: domains.index(x)+1, screen)
336 elif type(screen) == int:
337 screen_numbers=[screen]
338 else:
339 screen_numbers=[domains.index(screen)+1]
341 for screen_number in screen_numbers:
342 run_command("screen -X select "+str(screen_number))
343 time.sleep(wt_timeout)
344 for line in string.splitlines():
345 f=open('/tmp/xentaurbuf', 'w')
346 f.write(line+"\n")
347 f.close()
348 run_command("screen -X readreg p /tmp/xentaurbuf")
349 time.sleep(wt_timeout)
350 run_command("nohup screen -X paste p >& /dev/null")
351 time.sleep(wt_timeout)
353 if return_to_screen != "":
354 run_command("screen -X select %s" % (return_to_screen))
355 time.sleep(wt_timeout)
357 #-----------------------------------------------------------------------
359 cisco_fa01_up="""
360 ena
361 conf t
362 int fa0/0
363 no shutdown
364 exit
365 int fa1/0
366 no shutdown
367 exit
368 exit
369 exit
370 """
372 cisco_set_ip_on_int="""
373 interface fa%s/0
374 no ip address
375 ip address %s 255.255.255.0
376 exit
377 """
379 #-----------------------------------------------------------------------
381 nodes=domains
383 if len(sys.argv) > 1:
384 if sys.argv[1] == 'start':
385 start_all()
386 if sys.argv[1] == 'stop':
387 stop_all()
388 if sys.argv[1] == 'start-bridges':
389 create_bridges_script()
390 if sys.argv[1] == 'start-domains':
391 create_domains_script()
392 if sys.argv[1] == 'stop-domains':
393 destroy_domains_script()
394 elif sys.argv[1] == 'screen':
395 create_screens_script()
396 elif sys.argv[1] == 'graph':
397 graph()
398 elif sys.argv[1] == 'shell':
399 shell()
401 else:
402 show_usage()
403 sys.exit(1)
405 sys.exit(0)