ia64/xen-unstable

view tools/python/xen/util/Brctl.py @ 13200:069d1364af53

Added Brctl.get_state, to support upcoming PIF implementation.

Signed-off-by: Ewan Mellor <ewan@xensource.com>
author Ewan Mellor <ewan@xensource.com>
date Wed Dec 27 15:39:32 2006 +0000 (2006-12-27)
parents 903d88857972
children
line source
1 """Bridge control utilities.
2 """
3 import os
4 import os.path
5 import re
6 import sys
8 CMD_IFCONFIG = 'ifconfig'
9 CMD_ROUTE = 'route'
10 CMD_BRCTL = 'brctl'
11 CMD_IPTABLES = "iptables"
13 opts = None
15 class Opts:
17 def __init__(self, defaults):
18 for (k, v) in defaults.items():
19 setattr(self, k, v)
20 pass
22 def cmd(p, s):
23 """Print and execute command 'p' with args 's'.
24 """
25 global opts
26 c = p + ' ' + s
27 if opts.verbose: print c
28 if not opts.dryrun:
29 os.system(c)
31 bridgeRE = re.compile(r'([^\t]*)\t*[^\t]*\t*[^\t]*\t*([^\t]*)')
32 def get_state():
33 fin = os.popen(CMD_BRCTL + ' show', 'r')
34 try:
35 bridges = {}
36 brlist = None
37 brname = None
38 first = True
39 for line in fin:
40 if first:
41 first = False
42 elif line[0] == '\t':
43 brlist.append(line.strip())
44 else:
45 if brname:
46 bridges[brname] = brlist
47 m = bridgeRE.match(line)
48 brname = m.group(1)
49 brlist = [m.group(2).strip()]
50 if brname:
51 bridges[brname] = brlist
52 return bridges
53 finally:
54 fin.close()
56 def vif_bridge_add(params):
57 """Add the network interface for vif on dom to a bridge.
58 """
59 cmd(CMD_BRCTL, 'addif %(bridge)s %(vif)s' % params)
61 def vif_bridge_rem(params):
62 """Remove the network interface for vif on dom from a bridge.
63 """
64 cmd(CMD_BRCTL, 'delif %(bridge)s %(vif)s' % params)
66 def vif_restrict_addr(vif, addr, delete=0):
67 d = { 'vif': vif, 'addr': addr}
68 if delete:
69 d['flag'] = '-D'
70 else:
71 d['flag'] = '-A'
72 cmd(CMD_IPTABLES, '-P FORWARD DROP')
73 cmd(CMD_IPTABLES, '%(flag)s FORWARD -m physdev --physdev-in %(vif)s -s %(addr)s -j ACCEPT' % d)
74 cmd(CMD_IPTABLES, '%(flag)s FORWARD -m physdev --physdev-out %(vif)s -d %(addr)s -j ACCEPT' % d)
76 def bridge_create(bridge, **kwd):
77 """Create a bridge.
78 Defaults hello time to 0, forward delay to 0 and stp off.
79 """
80 cmd(CMD_BRCTL, 'addbr %s' % bridge)
81 if kwd.get('hello', None) is None:
82 kwd['hello'] = 0
83 if kwd.get('fd', None) is None:
84 kwd['fd'] = 0
85 if kwd.get('stp', None) is None:
86 kwd['stp'] = 'off'
87 bridge_set(bridge, **kwd)
88 cmd(CMD_IFCONFIG, "%s up" % bridge)
90 def bridge_set(bridge, hello=None, fd=None, stp=None):
91 """Set bridge parameters.
92 """
93 if hello is not None:
94 cmd(CMD_BRCTL, 'sethello %s %d' % (bridge, hello))
95 if fd is not None:
96 cmd(CMD_BRCTL, 'setfd %s %d' % (bridge, fd))
97 if stp is not None:
98 cmd(CMD_BRCTL, 'stp %s %s' % (bridge, stp))
100 def bridge_del(bridge):
101 """Delete a bridge.
102 """
103 cmd(CMD_IFCONFIG, '%s down' % bridge)
104 cmd(CMD_BRCTL, 'delbr %s' % bridge)
106 def routes():
107 """Return a list of the routes.
108 """
109 fin = os.popen(CMD_ROUTE + ' -n', 'r')
110 routes = []
111 for x in fin:
112 if x.startswith('Kernel'): continue
113 if x.startswith('Destination'): continue
114 x = x.strip()
115 y = x.split()
116 z = { 'destination': y[0],
117 'gateway' : y[1],
118 'mask' : y[2],
119 'flags' : y[3],
120 'metric' : y[4],
121 'ref' : y[5],
122 'use' : y[6],
123 'interface' : y[7] }
124 routes.append(z)
125 return routes
127 def ifconfig(interface):
128 """Return the ip config for an interface,
129 """
130 fin = os.popen(CMD_IFCONFIG + ' %s' % interface, 'r')
131 inetre = re.compile('\s*inet\s*addr:(?P<address>\S*)\s*Bcast:(?P<broadcast>\S*)\s*Mask:(?P<mask>\S*)')
132 info = None
133 for x in fin:
134 m = inetre.match(x)
135 if not m: continue
136 info = m.groupdict()
137 info['interface'] = interface
138 break
139 return info
141 def reconfigure(interface, bridge):
142 """Reconfigure an interface to be attached to a bridge, and give the bridge
143 the IP address etc. from interface. Move the default route to the interface
144 to the bridge.
146 """
147 global opts
148 intf_info = ifconfig(interface)
149 if not intf_info:
150 print >>sys.stderr, 'Interface not found:', interface
151 return
152 #bridge_info = ifconfig(bridge)
153 #if not bridge_info:
154 # print >>sys.stderr, 'Bridge not found:', bridge
155 # return
156 route_info = routes()
157 intf_info['bridge'] = bridge
158 intf_info['gateway'] = None
159 for r in route_info:
160 if (r['destination'] == '0.0.0.0' and
161 'G' in r['flags'] and
162 r['interface'] == interface):
163 intf_info['gateway'] = r['gateway']
164 if not intf_info['gateway']:
165 print >>sys.stderr, 'Gateway not found: ', interface
166 return
167 cmd(CMD_IFCONFIG,
168 '%(bridge)s %(address)s netmask %(mask)s broadcast %(broadcast)s up'
169 % intf_info)
170 cmd(CMD_ROUTE,
171 'add default gateway %(gateway)s dev %(bridge)s'
172 % intf_info)
173 cmd(CMD_BRCTL, 'addif %(bridge)s %(interface)s' % intf_info)
174 cmd(CMD_IFCONFIG, '%(interface)s 0.0.0.0' % intf_info)
176 defaults = {
177 'verbose' : 1,
178 'dryrun' : 0,
179 }
181 opts = Opts(defaults)
183 def set_opts(val):
184 global opts
185 opts = val
186 return opts