xentaur

view xentaur.py @ 23:6bb2a29e91be

interfaces connection and disconnection
author igor
date Fri Sep 21 16:01:04 2007 +0300 (2007-09-21)
parents c4a092e32ee1
children fcd08a4f3216
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> the 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 #-----------------------------------------------------------------------
243 def add_domain(name,type):
244 domains.append(name)
245 domain_types.append(type)
247 def brake_link(domain,bridge):
248 broken_links.append([domain,bridge])
250 wt_timeout=0.5
251 def write_to(screen,string,return_to_screen=""):
252 """
253 write_to(screen,string):
255 Type *string* to the specified screen(s).
256 Screen may be specified with the number *screen*,
257 with array of numbers,
258 with array of names.
260 """
261 screen_numbers=[] # number of the screens to write to
262 if type(screen) == list:
263 screen_numbers=map(lambda x: domains.index(x)+1, screen)
264 elif type(screen) == int:
265 screen_numbers=[screen]
266 else:
267 screen_numbers=[domains.index(screen)+1]
269 for screen_number in screen_numbers:
270 run_command("screen -X select "+str(screen_number))
271 time.sleep(wt_timeout)
272 for line in string.splitlines():
273 f=open('/tmp/xentaurbuf', 'w')
274 f.write(line+"\n")
275 f.close()
276 run_command("screen -X readreg p /tmp/xentaurbuf")
277 time.sleep(wt_timeout)
278 run_command("nohup screen -X paste p >& /dev/null")
279 time.sleep(wt_timeout)
281 if return_to_screen != "":
282 run_command("screen -X select %s" % (return_to_screen))
283 time.sleep(wt_timeout)
285 #-----------------------------------------------------------------------
287 cisco_fa01_up="""
288 ena
289 conf t
290 int fa0/0
291 no shutdown
292 exit
293 int fa1/0
294 no shutdown
295 exit
296 exit
297 exit
298 """
300 cisco_set_ip_on_int="""
301 interface fa%s/0
302 no ip address
303 ip address %s 255.255.255.0
304 exit
305 """
307 #-----------------------------------------------------------------------
309 nodes=domains
311 if len(sys.argv) > 1:
312 if sys.argv[1] == 'start':
313 start_all()
314 if sys.argv[1] == 'stop':
315 stop_all()
316 if sys.argv[1] == 'start-bridges':
317 create_bridges_script()
318 if sys.argv[1] == 'start-domains':
319 create_domains_script()
320 if sys.argv[1] == 'stop-domains':
321 destroy_domains_script()
322 elif sys.argv[1] == 'screen':
323 create_screens_script()
324 elif sys.argv[1] == 'graph':
325 graph()
326 elif sys.argv[1] == 'shell':
327 shell()
329 else:
330 show_usage()
331 sys.exit(1)
333 sys.exit(0)