xentaur

view xentaur.py @ 24:fcd08a4f3216

reconnect and show
author igor
date Fri Sep 21 16:19:12 2007 +0300 (2007-09-21)
parents 6bb2a29e91be
children a268a7754150
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 exec 'from '+xen_config_name+' import bridges,vbridges_table, hidden_bridges, domains, broken_links, temporary_links, domain_types'
12 from IPython.Shell import IPShellEmbed
15 screenrc=os.environ['HOME']+"/.screenrc_xentaur"
17 def run(program, *args):
18 pid = os.fork()
19 if not pid:
20 os.execvp(program, (program,) + args)
21 return os.wait()[0]
23 def run_command(line):
24 #cmds=line.split()
25 #run(cmds[0],*cmds[1:])
26 run("/bin/sh", "-c", line)
28 def run_command_return_stdout(line):
29 p = os.popen(line)
30 output = p.read()
31 p.close()
32 return output
34 def create_bridges_script():
35 unbound_bridges=bridges
36 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))
37 create_unbound_bridges+="\n"+"\n".join(map(lambda x: "sudo /bin/ip link set "+x+" up", unbound_bridges))
39 print """#!/bin/sh
40 # create unbound bridges
41 %(create_unbound_bridges)s
42 """ % {'create_unbound_bridges' : create_unbound_bridges}
45 def create_domains_script():
46 for N in range(len(domains)):
47 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"
49 def destroy_domains_script():
50 for N in range(len(domains)):
51 print "sudo /usr/sbin/xm shutdown "+domains[N]
53 def create_screens_script():
55 N=1
56 screens=[]
57 for domain in domains:
58 screens.append("screen -t "+domain+" "+str(N)+" sh -c 'while true; do sudo xm console "+domain+" ; echo Retrying in 5 seconds...; sleep 5; done'")
59 N+=1
60 screenlist="\n".join(screens)
62 #
63 # Previous terminal acccess commands:
64 # ip="192.168.80."+str(200+N)
65 # screens.append("screen -t "+domain+" "+str(N)+" sh -c 'while true; do ssh root@"+ip+" ; done'")
66 #
68 #hardstatus string "\%{gk}\%c \%{yk}\%M\%d \%{wk}\%?\%-Lw\%?\%{bw}\%n*\%f\%t\%?(\%u)\%?\%{wk}\%?\%+Lw\%?"
70 f=open(screenrc, "w");
71 f.write("""
72 hardstatus on
73 hardstatus alwayslastline
75 screen -t console 0 bash
76 %s
77 """ % (screenlist))
78 f.close()
80 def graph_node(node):
81 i=0
82 domain_type={}
83 for domain in domains:
84 domain_type[domain]=domain_types[i]
85 i+=1
86 return node+" [label=\" "+node+"\",shapefile=\"shapes/all/"+domain_type[node]+".png\",fontcolor=navy,fontsize=14]"
88 def graph():
89 nodelist=""
90 bridgelist=""
91 linklist=""
92 physicallist=""
93 networklist=""
95 nodelist=";\n ".join(map(graph_node,nodes))
96 if nodelist: nodelist += ";"
98 bridgelist=";\n ".join(set(bridges)-set(hidden_bridges))
99 if bridgelist: bridgelist += ";"
101 links=[]
102 for host, bridges_raw in vbridges_table.iteritems():
103 i=0
104 for this_bridge in bridges_raw:
105 if this_bridge in hidden_bridges:
106 continue
107 if [ host, this_bridge ] in broken_links:
108 links.append(host+" -- "+this_bridge+" [taillabel=\"fa"+str(i)+"/0\",style=dashed]")
109 else:
110 links.append(host+" -- "+this_bridge+" [taillabel=\"fa"+str(i)+"/0\"]")
111 i+=1
113 for link in temporary_links:
114 links.append(link[0]+" -- "+link[1]+" [color=blue,len=10,w=5,weight=5]")
116 linklist=";\n ".join(links)
118 graph_dot = {
119 'nodelist' : nodelist,
120 'bridgelist' : bridgelist,
121 'linklist' : linklist,
122 'physicallist' : physicallist,
123 'networklist' : networklist,
124 }
126 f = open("xenomips.dot", "w");
127 f.write ("""
128 graph G {
129 edge [len=1.25];
130 splines=true;
131 // nodes
133 node [shape=plaintext,color=white,shapefile="shapes/cisco.bmp/router.png"];
134 %(nodelist)s
136 // bridges
138 node [shape=none,shapefile="shapes/all/switch.png"];
139 %(bridgelist)s
141 // physical
143 node [shape=rectangle,color=blue];
144 %(physicallist)s
146 // networks (not bridges, not physical)
147 node [shape=rectangle,color=green];
148 %(networklist)s
150 // links (between nodes and bridges)
151 %(linklist)s
153 };
154 """ % graph_dot)
155 f.close()
156 run_command("neato -Tpng -o xenomips.png xenomips.dot ")
158 def start_all():
159 create_bridges_script()
160 create_screens_script()
161 create_domains_script()
162 graph()
163 print """
164 cat <<NOTE_FOR_USER
165 # To view virtual network map, run:
166 gqview xenomips.png
167 # To attach to VM consoles, run:
168 screen -c screenrc
169 NOTE_FOR_USER
170 """
172 def shell():
173 ipshell = IPShellEmbed()
174 ipshell()
176 def stop_all():
177 destroy_domains_script()
179 def show_usage():
180 print """Usage:
181 xentaur {start|stop|start-bridges|start-domains|stop-domains|screen|graph}
182 """
184 #-----------------------------------------------------------------------
185 # DOMAINS
187 def get_domain_id(domain):
188 return run_command_return_stdout("sudo xm list | awk '{if ($1 == \"'%s'\") print $2}'" % domain).rstrip("\n")
191 #-----------------------------------------------------------------------
192 # BRIDGES and IFACES
194 def bridge_down(bridge):
195 """
196 Turn the bridge <bridge> down
197 """
198 run_command("sudo ip link set %s down" % bridge)
200 def bridge_up(bridge):
201 """
202 Turn the bridge <bridge> up
203 """
204 run_command("sudo ip link set %s up" % bridge)
206 def show_bridge(bridge):
207 """
208 Show the state of the bridge <bridge>
209 """
210 run_command("sudo ip link show %s" % bridge)
213 def int_disconnect(domain, int_number):
214 """
215 Disconnect the interface with the number <int_number>
216 of the domain <domain> from the bridge to which
217 it is connected
218 """
219 dom_id=get_domain_id(domain)
220 bridge=vbridges_table[domain][int_number]
221 if not bridge:
222 print "Interface %s of the %s domain is not connected" % (int_number, domain)
223 return 1
224 run_command("sudo brctl delif %s vif%s.%s" % (bridge, dom_id, int_number))
225 vbridges_table[domain][int_number]=''
227 def int_connect(domain, int_number, bridge):
228 """
229 Connect the interface with the number <int_number>
230 of the domain <domain> to the bridge <bridge>
231 """
232 dom_id=get_domain_id(domain)
234 if vbridges_table[domain][int_number]:
235 print "Interface %s of the %s domain is connected already to the %s bridge" % (int_number, domain, vbridges_table[domain][int_number])
236 return 1
237 run_command("sudo brctl addif %s vif%s.%s" % (bridge, dom_id, int_number))
238 vbridges_table[domain][int_number]=bridge
240 def int_reconnect(domain, int_number, bridge):
241 """
242 Reconnect the interface with the number <int_number>
243 of the domain <domain> from the bridge to which
244 it is connected to the bridge <bridge>
245 """
246 int_disconnect(domain, int_number)
247 int_connect(domain, int_number, bridge)
249 def show_int(domain, int_number):
250 vbridges_table[domain][int_number]
252 #-----------------------------------------------------------------------
255 def add_domain(name,type):
256 domains.append(name)
257 domain_types.append(type)
259 def brake_link(domain,bridge):
260 broken_links.append([domain,bridge])
262 wt_timeout=0.5
263 def write_to(screen,string,return_to_screen=""):
264 """
265 write_to(screen,string):
267 Type *string* to the specified screen(s).
268 Screen may be specified with the number *screen*,
269 with array of numbers,
270 with array of names.
272 """
273 screen_numbers=[] # number of the screens to write to
274 if type(screen) == list:
275 screen_numbers=map(lambda x: domains.index(x)+1, screen)
276 elif type(screen) == int:
277 screen_numbers=[screen]
278 else:
279 screen_numbers=[domains.index(screen)+1]
281 for screen_number in screen_numbers:
282 run_command("screen -X select "+str(screen_number))
283 time.sleep(wt_timeout)
284 for line in string.splitlines():
285 f=open('/tmp/xentaurbuf', 'w')
286 f.write(line+"\n")
287 f.close()
288 run_command("screen -X readreg p /tmp/xentaurbuf")
289 time.sleep(wt_timeout)
290 run_command("nohup screen -X paste p >& /dev/null")
291 time.sleep(wt_timeout)
293 if return_to_screen != "":
294 run_command("screen -X select %s" % (return_to_screen))
295 time.sleep(wt_timeout)
297 #-----------------------------------------------------------------------
299 cisco_fa01_up="""
300 ena
301 conf t
302 int fa0/0
303 no shutdown
304 exit
305 int fa1/0
306 no shutdown
307 exit
308 exit
309 exit
310 """
312 cisco_set_ip_on_int="""
313 interface fa%s/0
314 no ip address
315 ip address %s 255.255.255.0
316 exit
317 """
319 #-----------------------------------------------------------------------
321 nodes=domains
323 if len(sys.argv) > 1:
324 if sys.argv[1] == 'start':
325 start_all()
326 if sys.argv[1] == 'stop':
327 stop_all()
328 if sys.argv[1] == 'start-bridges':
329 create_bridges_script()
330 if sys.argv[1] == 'start-domains':
331 create_domains_script()
332 if sys.argv[1] == 'stop-domains':
333 destroy_domains_script()
334 elif sys.argv[1] == 'screen':
335 create_screens_script()
336 elif sys.argv[1] == 'graph':
337 graph()
338 elif sys.argv[1] == 'shell':
339 shell()
341 else:
342 show_usage()
343 sys.exit(1)
345 sys.exit(0)