xentaur

view xentaur.py @ 37:3245e12b66d5

+example1
author igor
date Tue Sep 25 23:31:23 2007 +0300 (2007-09-25)
parents 244f1602496a
children f71b298798c2
line source
1 #!/usr/bin/python
4 import sys,os,time
5 import xenomips_vars
6 xenomips_vars.N='1'
8 xentaur_path=os.environ['HOME']+"/xentaur"
10 sys.path.append('/etc/xen')
11 sys.path.append(xentaur_path)
13 network='netw'
14 domain='dyn3'
15 from xendomain import *
17 bridges_turned_down=[]
19 from IPython.Shell import IPShellEmbed
22 screenrc=os.environ['HOME']+"/.screenrc_xentaur"
24 def run(program, *args):
25 pid = os.fork()
26 if not pid:
27 os.execvp(program, (program,) + args)
28 return os.wait()[0]
30 def run_command(line):
31 #cmds=line.split()
32 #run(cmds[0],*cmds[1:])
33 run("/bin/sh", "-c", line)
35 def run_command_return_stdout(line):
36 p = os.popen(line)
37 output = p.read()
38 p.close()
39 return output
41 def create_bridges_script():
42 unbound_bridges=bridges
43 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))
44 create_unbound_bridges+="\n"+"\n".join(map(lambda x: "sudo /bin/ip link set "+x+" up", unbound_bridges))
46 print """#!/bin/sh
47 # create unbound bridges
48 %(create_unbound_bridges)s
49 """ % {'create_unbound_bridges' : create_unbound_bridges}
52 def create_domains_script():
53 for domain in domains:
54 print "sudo /usr/sbin/xm create "+xentaur_path+"/xendomain.py "+" domain="+domain+" network="+network+" && sleep 1 && sudo /usr/sbin/xm sched-credit -d $(sudo /usr/sbin/xm list | grep "+domain+" | awk '{print $2}') -c 10 && sleep 1"
56 def destroy_domains_script():
57 for domain in domains:
58 print "sudo /usr/sbin/xm shutdown "+domain
60 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 def save():
209 print "network =", xen_config_name
210 print "domains =", domains
211 print "domain_types =", domain_types
212 print "bridges =", bridges
213 print "vbridges_table =", vbridges_table
214 print "hidden_bridges =", hidden_bridges
215 print "broken_links =", broken_links
216 print "temporary_links =", temporary_links
217 print "bridges_turned_down =", bridges_turned_down
219 #-----------------------------------------------------------------------
220 # CLASSES
222 class Bridge:
223 def __init__ (self,name):
224 self.name=name
225 def up(self):
226 bridge_up(self.name)
227 def down(self):
228 bridge_down(self.name)
229 def show(self):
230 show_bridge(self.name)
231 def dump_start(self,filter=""):
232 dump_start(self.name,filter)
235 #-----------------------------------------------------------------------
236 # DOMAINS
238 def get_domain_id(domain):
239 return run_command_return_stdout("sudo xm list | awk '{if ($1 == \"'%s'\") print $2}'" % domain).rstrip("\n")
242 #-----------------------------------------------------------------------
243 # BRIDGES and IFACES
245 def bridge_down(bridge):
246 """
247 Turn the bridge <bridge> down
248 """
249 if bridge in bridges_turned_down:
250 print "Bridge %s is turned down already" % (bridge)
251 else:
252 bridges_turned_down.append(bridge)
253 run_command("sudo ip link set %s down" % bridge)
254 autoredraw()
256 def bridge_up(bridge):
257 """
258 Turn the bridge <bridge> up
259 """
260 if not (bridge in bridges_turned_down):
261 print "Bridge %s is turned up already" % (bridge)
262 else:
263 bridges_turned_down.remove(bridge)
264 run_command("sudo ip link set %s up" % bridge)
265 autoredraw()
267 def show_bridge(bridge):
268 """
269 Show the state of the bridge <bridge>
270 """
271 run_command("sudo ip link show %s" % bridge)
274 def int_disconnect(domain, int_number):
275 """
276 Disconnect the interface with the number <int_number>
277 of the domain <domain> from the bridge to which
278 it is connected
279 """
280 dom_id=get_domain_id(domain)
281 bridge=vbridges_table[domain][int_number]
282 if not bridge:
283 print "Interface %s of the %s domain is not connected" % (int_number, domain)
284 return 1
285 run_command("sudo brctl delif %s vif%s.%s" % (bridge, dom_id, int_number))
286 vbridges_table[domain][int_number]=''
287 if [ domain, int_number, bridge ] in temporary_links:
288 temporary_links.remove([ domain, int_number, bridge ])
289 else:
290 broken_links.append([ domain, int_number, bridge ])
291 autoredraw()
293 def int_connect(domain, int_number, bridge):
294 """
295 Connect the interface with the number <int_number>
296 of the domain <domain> to the bridge <bridge>
297 """
298 dom_id=get_domain_id(domain)
300 if vbridges_table[domain][int_number]:
301 print "Interface %s of the %s domain is connected already to the %s bridge" % (int_number, domain, vbridges_table[domain][int_number])
302 return 1
303 run_command("sudo brctl addif %s vif%s.%s" % (bridge, dom_id, int_number))
304 vbridges_table[domain][int_number]=bridge
305 if [ domain, int_number, bridge ] in broken_links:
306 broken_links.remove([ domain, int_number, bridge ])
307 else:
308 temporary_links.append([ domain, int_number, bridge ])
309 autoredraw()
311 def int_reconnect(domain, int_number, bridge):
312 """
313 Reconnect the interface with the number <int_number>
314 of the domain <domain> from the bridge to which
315 it is connected to the bridge <bridge>
316 """
317 int_disconnect(domain, int_number)
318 int_connect(domain, int_number, bridge)
320 def show_int(domain, int_number):
321 """
322 Show information about the interface <int_nuber>
323 of the domain <domain>
324 """
325 return vbridges_table[domain][int_number]
328 def dump_start(bridge, filter=""):
329 try:
330 print "Writing dump... (press Ctrl-C to stop)"
331 run_command("sudo tcpdump -w xentaur.dump -i %s %s > /dev/null 2>&1 " % (bridge,filter))
332 except:
333 print "Done.\n Dump is written to xentaur.dump"
334 return 0
336 def dump_stop():
337 return 0
340 #-----------------------------------------------------------------------
341 # CONFIGURATION TEMPLATES
344 def configure_ip_addresses(doms=domains):
345 return 0
347 def configure_ospf(doms=domains):
348 return 0
350 def configure_save(doms=domains):
351 write_to(doms,"\nwr\n")
353 #-----------------------------------------------------------------------
356 def add_domain(name,type):
357 domains.append(name)
358 domain_types.append(type)
360 def brake_link(domain,bridge):
361 broken_links.append([domain,bridge])
363 wt_timeout=0.5
364 def write_to(screen,string,return_to_screen=""):
365 """
366 write_to(screen,string):
368 Type *string* to the specified screen(s).
369 Screen may be specified with the number *screen*,
370 with array of numbers,
371 with array of names.
373 """
374 screen_numbers=[] # number of the screens to write to
375 if type(screen) == list:
376 screen_numbers=map(lambda x: domains.index(x)+1, screen)
377 elif type(screen) == int:
378 screen_numbers=[screen]
379 else:
380 screen_numbers=[domains.index(screen)+1]
382 for screen_number in screen_numbers:
383 run_command("screen -X select "+str(screen_number))
384 time.sleep(wt_timeout)
385 for line in string.splitlines():
386 f=open('/tmp/xentaurbuf', 'w')
387 f.write(line+"\n")
388 f.close()
389 run_command("screen -X readreg p /tmp/xentaurbuf")
390 time.sleep(wt_timeout)
391 run_command("nohup screen -X paste p >& /dev/null")
392 time.sleep(wt_timeout)
394 if return_to_screen != "":
395 run_command("screen -X select %s" % (return_to_screen))
396 time.sleep(wt_timeout)
398 #-----------------------------------------------------------------------
400 cisco_fa01_up="""
401 ena
402 conf t
403 int fa0/0
404 no shutdown
405 exit
406 int fa1/0
407 no shutdown
408 exit
409 exit
410 exit
411 """
413 cisco_set_ip_on_int="""
414 interface fa%s/0
415 no ip address
416 ip address %s 255.255.255.0
417 exit
418 """
422 nodes=domains
424 if len(sys.argv) > 1:
425 if sys.argv[1] == 'start':
426 start_all()
427 if sys.argv[1] == 'stop':
428 stop_all()
429 if sys.argv[1] == 'start-bridges':
430 create_bridges_script()
431 if sys.argv[1] == 'start-domains':
432 create_domains_script()
433 if sys.argv[1] == 'stop-domains':
434 destroy_domains_script()
435 elif sys.argv[1] == 'screen':
436 create_screens_script()
437 elif sys.argv[1] == 'graph':
438 graph()
439 elif sys.argv[1] == 'shell':
440 shell()
442 else:
443 show_usage()
444 sys.exit(1)
446 sys.exit(0)