xentaur

view xentaur.py @ 44:04f0c6694d1e

default network module
author igor
date Wed Oct 24 14:53:12 2007 +0300 (2007-10-24)
parents 10444acb35f4
children 85794a582ef5
line source
1 #!/usr/bin/python
4 import sys,os,time
6 xentaur_path=os.environ['HOME']+"/xentaur"
8 sys.path.append('/etc/xen')
9 sys.path.append(xentaur_path)
11 network='snrs_ipsec_rsa_1'
12 domain='qua1'
13 from xendomain import *
15 bridges_turned_down=[]
17 from IPython.Shell import IPShellEmbed
20 screenrc=os.environ['HOME']+"/.screenrc_xentaur"
22 def run(program, *args):
23 pid = os.fork()
24 if not pid:
25 os.execvp(program, (program,) + args)
26 return os.wait()[0]
28 def run_command(line):
29 #cmds=line.split()
30 #run(cmds[0],*cmds[1:])
31 run("/bin/sh", "-c", line)
33 def run_command_return_stdout(line):
34 p = os.popen(line)
35 output = p.read()
36 p.close()
37 return output
39 def create_bridges_script():
40 unbound_bridges=set(bridges)-set(real_bridges)
41 create_unbound_bridges="\n".join(map(lambda x: "sudo brctl show | awk '{print $1}' | grep -qx "+x+" || sudo brctl addbr "+x, unbound_bridges))
42 create_unbound_bridges+="\n"+"\n".join(map(lambda x: "sudo brctl stp "+x+" off", unbound_bridges))
43 create_unbound_bridges+="\n"+"\n".join(map(lambda x: "sudo 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 domain in domains:
53 if not domain in real_nodes:
54 print "sudo xm create "+xentaur_path+"/xendomain.py "+" domain="+domain+" network="+network+" && sleep 1 && sudo xm sched-credit -d $(sudo xm list | grep "+domain+" | awk '{print $2}') -c 10 && sleep 1"
56 def destroy_domains_script():
57 for domain in domains:
58 if not domain in real_nodes:
59 print "sudo xm shutdown "+domain
61 def create_screens_script():
62 N=1
63 screens=[]
64 for domain in domains:
65 screens.append("screen -t "+domain+" "+str(N)+" sh -c 'while true; do sudo xm console "+domain+" ; echo Retrying in 5 seconds...; sleep 5; done'")
66 N+=1
67 screenlist="\n".join(screens)
69 #
70 # Previous terminal acccess commands:
71 # ip="192.168.80."+str(200+N)
72 # screens.append("screen -t "+domain+" "+str(N)+" sh -c 'while true; do ssh root@"+ip+" ; done'")
73 #
75 #hardstatus string "\%{gk}\%c \%{yk}\%M\%d \%{wk}\%?\%-Lw\%?\%{bw}\%n*\%f\%t\%?(\%u)\%?\%{wk}\%?\%+Lw\%?"
77 f=open(screenrc, "w");
78 f.write("""
79 hardstatus on
80 hardstatus alwayslastline
82 screen -t console 0 bash
83 %s
84 """ % (screenlist))
85 f.close()
87 def graph_node(node):
88 i=0
89 domain_type={}
90 for domain in domains:
91 domain_type[domain]=domain_types[i]
92 i+=1
93 return node+" [label=\" "+node+"\",shapefile=\"shapes/all/"+domain_type[node]+".png\",fontcolor=black,fontsize=16]"
95 def graph_bridge(bridge):
96 if bridge in hidden_bridges:
97 return ""
98 if bridge in real_bridges:
99 return "%s [shape=none,shapefile=\"shapes/all/real_switch.png\"]" % (bridge)
100 elif bridge in bridges_turned_down:
101 return "%s [shape=none,shapefile=\"shapes/all/switch_turned_down.png\"]" % (bridge)
102 else:
103 return "%s [shape=none,shapefile=\"shapes/all/switch.png\"]" % (bridge)
106 def graph():
107 nodelist=""
108 bridgelist=""
109 linklist=""
110 physicallist=""
111 networklist=""
113 nodelist=";\n ".join(map(graph_node,nodes))
114 if nodelist: nodelist += ";"
116 bridgelist=";\n ".join(map(graph_bridge,bridges))
117 if bridgelist: bridgelist += ";"
119 links=[]
120 for host, bridges_raw in vbridges_table.iteritems():
121 i=0
122 for this_bridge in bridges_raw:
123 if this_bridge in hidden_bridges or not this_bridge:
124 continue
125 if not [ host, bridges_raw.index(this_bridge), this_bridge ] in temporary_links:
126 links.append(host+" -- "+this_bridge+" [taillabel=\"fa"+str(bridges_raw.index(this_bridge))+"/0\"]")
127 i+=1
129 for link in temporary_links:
130 links.append(link[0]+" -- "+link[2]+" [taillabel=\"fa"+str(link[1])+"/0\",color=blue,len=10,w=5,weight=5]")
132 for link in broken_links:
133 links.append(link[0]+" -- "+link[2]+" [taillabel=\"fa"+str(link[1])+"/0\",style=dashed]")
136 # bridge-bridge links
137 for host, bridges_raw in bridge_bridge_table.iteritems():
138 i=0
139 for this_bridge in bridges_raw:
140 if this_bridge in hidden_bridges or not this_bridge:
141 continue
142 if not [ host, bridges_raw.index(this_bridge), this_bridge ] in temporary_links:
143 links.append(host+" -- "+this_bridge)
144 i+=1
148 linklist=";\n ".join(links)
150 graph_dot = {
151 'nodelist' : nodelist,
152 'bridgelist' : bridgelist,
153 'linklist' : linklist,
154 'physicallist' : physicallist,
155 'networklist' : networklist,
156 }
158 f = open("xenomips.dot", "w");
159 f.write ("""
160 graph G {
161 edge [len=1.25];
162 splines=true;
163 // nodes
165 node [shape=plaintext,color=white,shapefile="shapes/cisco.bmp/router.png"];
166 %(nodelist)s
168 // bridges
170 node [shape=none,shapefile="shapes/all/switch.png"];
171 %(bridgelist)s
173 // physical
175 node [shape=rectangle,color=blue];
176 %(physicallist)s
178 // networks (not bridges, not physical)
179 node [shape=rectangle,color=green];
180 %(networklist)s
182 // links (between nodes and bridges)
183 %(linklist)s
185 };
186 """ % graph_dot)
187 f.close()
188 run_command("neato -Tpng -o xenomips.png xenomips.dot ")
189 run_command("neato -Tsvg -o xenomips.svg xenomips.dot ")
191 def autoredraw():
192 graph()
194 def start_all():
195 create_bridges_script()
196 create_screens_script()
197 create_domains_script()
198 graph()
199 print """
200 cat <<NOTE_FOR_USER
201 # To view virtual network map, run:
202 gqview xenomips.png
203 # To attach to VM consoles, run:
204 screen -c screenrc
205 NOTE_FOR_USER
206 """
208 def shell():
209 autoredraw()
210 ipshell = IPShellEmbed()
211 ipshell()
213 def stop_all():
214 destroy_domains_script()
216 def show_usage():
217 print """Usage:
218 xentaur {start|stop|start-bridges|start-domains|stop-domains|screen|graph}
219 """
221 def save():
222 print "network =", xen_config_name
223 print "domains =", domains
224 print "domain_types =", domain_types
225 print "bridges =", bridges
226 print "vbridges_table =", vbridges_table
227 print "hidden_bridges =", hidden_bridges
228 print "broken_links =", broken_links
229 print "temporary_links =", temporary_links
230 print "bridges_turned_down =", bridges_turned_down
232 #-----------------------------------------------------------------------
233 # CLASSES
235 class Bridge:
236 def __init__ (self,name):
237 self.name=name
238 def up(self):
239 bridge_up(self.name)
240 def down(self):
241 bridge_down(self.name)
242 def show(self):
243 show_bridge(self.name)
244 def dump_start(self,filter=""):
245 dump_start(self.name,filter)
248 class Domain:
249 def __init__ (self,name):
250 self.name=name
251 def start(self):
252 return ""
253 def stop(self):
254 return ""
255 def start_commandline(self):
256 return ""
257 def graphviz(self):
258 return ""
259 def get_domain_id(self):
260 return get_domain_id(self.name)
262 #-----------------------------------------------------------------------
263 # DOMAINS
265 def get_domain_id(domain):
266 return run_command_return_stdout("sudo xm list | awk '{if ($1 == \"'%s'\") print $2}'" % domain).rstrip("\n")
269 #-----------------------------------------------------------------------
270 # BRIDGES and IFACES
272 def bridge_down(bridge):
273 """
274 Turn the bridge <bridge> down
275 """
276 if bridge in real_bridges:
277 print "Bridge %s is a real bridge" % (bridge)
278 return -1
279 if bridge in bridges_turned_down:
280 print "Bridge %s is turned down already" % (bridge)
281 else:
282 bridges_turned_down.append(bridge)
283 run_command("sudo ip link set %s down" % bridge)
284 autoredraw()
286 def bridge_up(bridge):
287 """
288 Turn the bridge <bridge> up
289 """
290 if bridge in real_bridges:
291 print "Bridge %s is a real bridge" % (bridge)
292 return -1
293 if not (bridge in bridges_turned_down):
294 print "Bridge %s is turned up already" % (bridge)
295 else:
296 bridges_turned_down.remove(bridge)
297 run_command("sudo ip link set %s up" % bridge)
298 autoredraw()
300 def show_bridge(bridge):
301 """
302 Show the state of the bridge <bridge>
303 """
304 if bridge in real_bridges:
305 print "Bridge %s is a real bridge" % (bridge)
306 return -1
307 run_command("sudo ip link show %s" % bridge)
310 def int_disconnect(domain, int_number):
311 """
312 Disconnect the interface with the number <int_number>
313 of the domain <domain> from the bridge to which
314 it is connected
315 """
316 dom_id=get_domain_id(domain)
317 bridge=vbridges_table[domain][int_number]
318 if not bridge:
319 print "Interface %s of the %s domain is not connected" % (int_number, domain)
320 return 1
321 run_command("sudo brctl delif %s vif%s.%s" % (bridge, dom_id, int_number))
322 vbridges_table[domain][int_number]=''
323 if [ domain, int_number, bridge ] in temporary_links:
324 temporary_links.remove([ domain, int_number, bridge ])
325 else:
326 broken_links.append([ domain, int_number, bridge ])
327 autoredraw()
329 def int_connect(domain, int_number, bridge):
330 """
331 Connect the interface with the number <int_number>
332 of the domain <domain> to the bridge <bridge>
333 """
334 if bridge in real_bridges:
335 print "Bridge %s is a real bridge" % (bridge)
336 return -1
338 dom_id=get_domain_id(domain)
339 if vbridges_table[domain][int_number]:
340 print "Interface %s of the %s domain is connected already to the %s bridge" % (int_number, domain, vbridges_table[domain][int_number])
341 return 1
342 run_command("sudo brctl addif %s vif%s.%s" % (bridge, dom_id, int_number))
343 vbridges_table[domain][int_number]=bridge
344 if [ domain, int_number, bridge ] in broken_links:
345 broken_links.remove([ domain, int_number, bridge ])
346 else:
347 temporary_links.append([ domain, int_number, bridge ])
348 autoredraw()
350 def int_reconnect(domain, int_number, bridge):
351 """
352 Reconnect the interface with the number <int_number>
353 of the domain <domain> from the bridge to which
354 it is connected to the bridge <bridge>
355 """
356 if bridge in real_bridges:
357 print "Bridge %s is a real bridge" % (bridge)
358 return -1
360 int_disconnect(domain, int_number)
361 int_connect(domain, int_number, bridge)
363 def show_int(domain, int_number):
364 """
365 Show information about the interface <int_nuber>
366 of the domain <domain>
367 """
368 return vbridges_table[domain][int_number]
371 def dump_start(bridge, filter=""):
372 if bridge in real_bridges:
373 print "Bridge %s is a real bridge" % (bridge)
374 return -1
375 try:
376 print "Writing dump... (press Ctrl-C to stop)"
377 run_command("sudo tcpdump -w xentaur.dump -i %s %s > /dev/null 2>&1 " % (bridge,filter))
378 except:
379 print "Done.\n Dump is written to xentaur.dump"
380 return 0
382 def dump_stop():
383 return 0
386 #-----------------------------------------------------------------------
387 # CONFIGURATION TEMPLATES
390 def configure_ip_addresses(doms=domains):
392 cisco_set_ip_on_int="""
393 \n\n\n
394 int fa%s/0
395 no ip address
396 ip address %s 255.255.255.0
397 no shutdown
398 exit
399 """
401 quagga_set_ip_on_int="""
402 int eth%s
403 no ip address
404 ip address %s/24
405 no shutdown
406 exit
407 """
409 for dom in doms:
410 i=domains.index(dom)+1
411 if domain_types[domains.index(dom)] == 'quagga':
412 command = quagga_set_ip_on_int
413 write_to(i,"\nconf t\n")
414 j=0
415 for br in vbridges_table[dom]:
416 write_to(i,command % (j, "192.168.%s.%s"%(bridges.index(br)+1,i)))
417 j+=1
418 write_to(i,"\nend\n")
419 else:
420 command = cisco_set_ip_on_int
421 write_to(i,"\nena\nconf t\n")
422 j=0
423 for br in vbridges_table[dom]:
424 write_to(i,command % (j, "192.168.%s.%s"%(bridges.index(br)+1,i)))
425 j+=1
426 write_to(i,"\nend\n")
427 return 0
429 def configure_no_ip_addresses(doms=domains):
431 cisco_set_ip_on_int="""
432 \n\n\n
433 int fa%s/0
434 no ip address %s 255.255.255.0
435 exit
436 """
438 quagga_set_ip_on_int="""
439 int eth%s
440 no ip address %s/24
441 exit
442 """
444 for dom in doms:
445 i=domains.index(dom)+1
446 if domain_types[domains.index(dom)] == 'quagga':
447 command = quagga_set_ip_on_int
448 write_to(i,"\nconf t\n")
449 j=0
450 for br in vbridges_table[dom]:
451 write_to(i,command % (j, "192.168.%s.%s"%(bridges.index(br)+1,i)))
452 j+=1
453 write_to(i,"\nend\n")
454 else:
455 command = cisco_set_ip_on_int
456 write_to(i,"\nena\nconf t\n")
457 j=0
458 for br in vbridges_table[dom]:
459 write_to(i,command % (j, "192.168.%s.%s"%(bridges.index(br)+1,i)))
460 j+=1
461 write_to(i,"\nend\n")
462 return 0
464 def configure_ospf(doms=domains):
465 for dom in doms:
466 if domain_types[domains.index(dom)] == 'quagga':
467 write_to(dom,"\n\nconf t\nrouter ospf\nnetwork 192.168.0.0/16 area 0\nend\n")
468 else:
469 write_to(dom,"\n\nena\nconf t\nrouter ospf 1\nnetwork 192.168.0.0 0.0.255.255 area 0\nend\n")
470 return 0
472 def configure_save(doms=domains):
473 write_to(doms,"\nwr\n")
475 #-----------------------------------------------------------------------
478 def add_domain(name,type):
479 domains.append(name)
480 domain_types.append(type)
482 def brake_link(domain,bridge):
483 broken_links.append([domain,bridge])
485 wt_timeout=0.5
486 def write_to(screen,string,return_to_screen=""):
487 """
488 write_to(screen,string):
490 Type *string* to the specified screen(s).
491 Screen may be specified with the number *screen*,
492 with array of numbers,
493 with array of names.
495 """
496 screen_numbers=[] # number of the screens to write to
497 if type(screen) == list:
498 screen_numbers=map(lambda x: domains.index(x)+1, screen)
499 elif type(screen) == int:
500 screen_numbers=[screen]
501 else:
502 screen_numbers=[domains.index(screen)+1]
504 for screen_number in screen_numbers:
505 run_command("screen -X select "+str(screen_number))
506 time.sleep(wt_timeout)
507 for line in string.splitlines():
508 f=open('/tmp/xentaurbuf', 'w')
509 f.write(line+"\n")
510 f.close()
511 run_command("screen -X readreg p /tmp/xentaurbuf")
512 time.sleep(wt_timeout)
513 run_command("nohup screen -X paste p >& /dev/null")
514 time.sleep(wt_timeout)
516 if return_to_screen != "":
517 run_command("screen -X select %s" % (return_to_screen))
518 time.sleep(wt_timeout)
520 #-----------------------------------------------------------------------
522 cisco_fa01_up="""
523 ena
524 conf t
525 int fa0/0
526 no shutdown
527 exit
528 int fa1/0
529 no shutdown
530 exit
531 exit
532 exit
533 """
535 cisco_set_ip_on_int="""
536 interface fa%s/0
537 no ip address
538 ip address %s 255.255.255.0
539 exit
540 """
544 nodes=domains
546 if len(sys.argv) > 1:
547 if sys.argv[1] == 'start':
548 start_all()
549 if sys.argv[1] == 'stop':
550 stop_all()
551 if sys.argv[1] == 'start-bridges':
552 create_bridges_script()
553 if sys.argv[1] == 'start-domains':
554 create_domains_script()
555 if sys.argv[1] == 'stop-domains':
556 destroy_domains_script()
557 elif sys.argv[1] == 'screen':
558 create_screens_script()
559 elif sys.argv[1] == 'graph':
560 graph()
561 elif sys.argv[1] == 'shell':
562 shell()
564 else:
565 show_usage()
566 sys.exit(1)
568 sys.exit(0)