1 # Copyright (c) 2008,2009 Citrix Systems, Inc.
2 # Copyright (c) 2009,2010 Nicira Networks.
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU Lesser General Public License as published
6 # by the Free Software Foundation; version 2.1 only. with the special
7 # exception on linking described in file LICENSE.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Lesser General Public License for more details.
14 from InterfaceReconfigure import *
19 # Bare Network Devices -- network devices without IP configuration
22 def netdev_down(netdev):
23 """Bring down a bare network device"""
24 if not netdev_exists(netdev):
25 log("netdev: down: device %s does not exist, ignoring" % netdev)
27 run_command(["/sbin/ifconfig", netdev, 'down'])
29 def netdev_up(netdev, mtu=None):
30 """Bring up a bare network device"""
31 if not netdev_exists(netdev):
32 raise Error("netdev: up: device %s does not exist" % netdev)
39 run_command(["/sbin/ifconfig", netdev, 'up'] + mtu)
45 def pif_currently_in_use(pif):
46 """Determine if a PIF is currently in use.
48 A PIF is determined to be currently in use if
49 - PIF.currently-attached is true
50 - Any bond master is currently attached
51 - Any VLAN master is currently attached
53 rec = db().get_pif_record(pif)
54 if rec['currently_attached']:
55 log("configure_datapath: %s is currently attached" % (pif_netdev_name(pif)))
57 for b in pif_get_bond_masters(pif):
58 if pif_currently_in_use(b):
59 log("configure_datapath: %s is in use by BOND master %s" % (pif_netdev_name(pif),pif_netdev_name(b)))
61 for v in pif_get_vlan_masters(pif):
62 if pif_currently_in_use(v):
63 log("configure_datapath: %s is in use by VLAN master %s" % (pif_netdev_name(pif),pif_netdev_name(v)))
68 # Datapath Configuration
71 def pif_datapath(pif):
72 """Return the datapath PIF associated with PIF.
73 A non-VLAN PIF is its own datapath PIF, except that a bridgeless PIF has
74 no datapath PIF at all.
75 A VLAN PIF's datapath PIF is its VLAN slave's datapath PIF.
78 return pif_datapath(pif_get_vlan_slave(pif))
80 pifrec = db().get_pif_record(pif)
81 nwrec = db().get_network_record(pifrec['network'])
82 if not nwrec['bridge']:
87 def datapath_get_physical_pifs(pif):
88 """Return the PIFs for the physical network device(s) associated with a datapath PIF.
89 For a bond master PIF, these are the bond slave PIFs.
90 For a non-VLAN, non-bond master PIF, the PIF is its own physical device PIF.
92 A VLAN PIF cannot be a datapath PIF.
94 if pif_is_tunnel(pif):
96 elif pif_is_vlan(pif):
97 # Seems like overkill...
98 raise Error("get-physical-pifs should not get passed a VLAN")
99 elif pif_is_bond(pif):
100 return pif_get_bond_slaves(pif)
104 def datapath_deconfigure_physical(netdev):
105 return ['--', '--with-iface', '--if-exists', 'del-port', netdev]
114 raise Error("strings may not contain null bytes")
128 return r'\x%02x' % ord(c)
129 return '"' + re.sub(r'["\\\000-\037]', escape, s) + '"'
131 def datapath_configure_tunnel(pif):
134 def datapath_configure_bond(pif,slaves):
135 bridge = pif_bridge_name(pif)
136 pifrec = db().get_pif_record(pif)
137 interface = pif_netdev_name(pif)
139 argv = ['--', '--fake-iface', 'add-bond', bridge, interface]
141 argv += [pif_netdev_name(slave)]
145 "mode": "balance-slb",
151 # override defaults with values from other-config whose keys
153 oc = pifrec['other_config']
154 overrides = filter(lambda (key,val):
155 key.startswith("bond-"), oc.items())
156 overrides = map(lambda (key,val): (key[5:], val), overrides)
157 bond_options.update(overrides)
159 argv += ['--', 'set', 'Port', interface]
160 if pifrec['MAC'] != "":
161 argv += ['MAC=%s' % vsctl_escape(pifrec['MAC'])]
162 for (name,val) in bond_options.items():
163 if name in ['updelay', 'downdelay']:
164 # updelay and downdelay have dedicated schema columns.
165 # The value must be a nonnegative integer.
171 argv += ['bond_%s=%d' % (name, value)]
173 log("bridge %s has invalid %s '%s'" % (bridge, name, value))
175 # Pass other bond options into other_config.
176 argv += ["other-config:%s=%s" % (vsctl_escape("bond-%s" % name),
180 def datapath_deconfigure_bond(netdev):
181 return ['--', '--with-iface', '--if-exists', 'del-port', netdev]
183 def datapath_deconfigure_ipdev(interface):
184 return ['--', '--with-iface', '--if-exists', 'del-port', interface]
186 def datapath_modify_config(commands):
187 #log("modifying configuration:")
191 rc = run_command(['/usr/bin/ovs-vsctl'] + ['--timeout=20']
192 + [c for c in commands if not c.startswith('#')])
194 raise Error("Failed to modify vswitch configuration")
198 # Toplevel Datapath Configuration.
201 def configure_datapath(pif):
202 """Bring up the configuration for 'pif', which must not be a VLAN PIF, by:
203 - Tearing down other PIFs that use the same physical devices as 'pif'.
204 - Ensuring that 'pif' itself is set up.
205 - *Not* tearing down any PIFs that are stacked on top of 'pif' (i.e. VLANs
208 Returns a tuple containing
209 - A list containing the necessary vsctl command line arguments
210 - A list of additional devices which should be brought up after
211 the configuration is applied.
217 assert not pif_is_vlan(pif)
218 bridge = pif_bridge_name(pif)
220 physical_devices = datapath_get_physical_pifs(pif)
222 vsctl_argv += ['## configuring datapath %s' % bridge]
224 # Determine additional devices to deconfigure.
226 # Given all physical devices which are part of this PIF we need to
228 # - any additional bond which a physical device is part of.
229 # - any additional physical devices which are part of an additional bond.
231 # Any of these which are not currently in use should be brought
232 # down and deconfigured.
233 extra_down_bonds = []
234 extra_down_ports = []
235 for p in physical_devices:
236 for bond in pif_get_bond_masters(p):
238 log("configure_datapath: leaving bond %s up" % pif_netdev_name(bond))
240 if bond in extra_down_bonds:
242 if db().get_pif_record(bond)['currently_attached']:
243 log("configure_datapath: implicitly tearing down currently-attached bond %s" % pif_netdev_name(bond))
245 extra_down_bonds += [bond]
247 for s in pif_get_bond_slaves(bond):
248 if s in physical_devices:
250 if s in extra_down_ports:
252 if pif_currently_in_use(s):
254 extra_down_ports += [s]
256 log("configure_datapath: bridge - %s" % bridge)
257 log("configure_datapath: physical - %s" % [pif_netdev_name(p) for p in physical_devices])
258 log("configure_datapath: extra ports - %s" % [pif_netdev_name(p) for p in extra_down_ports])
259 log("configure_datapath: extra bonds - %s" % [pif_netdev_name(p) for p in extra_down_bonds])
261 # Need to fully deconfigure any bridge which any of the:
266 for brpif in physical_devices + extra_down_ports + extra_down_bonds:
269 b = pif_bridge_name(brpif)
273 vsctl_argv += ['# remove bridge %s' % b]
274 vsctl_argv += ['--', '--if-exists', 'del-br', b]
276 for n in extra_down_ports:
277 dev = pif_netdev_name(n)
278 vsctl_argv += ['# deconfigure sibling physical device %s' % dev]
279 vsctl_argv += datapath_deconfigure_physical(dev)
282 for n in extra_down_bonds:
283 dev = pif_netdev_name(n)
284 vsctl_argv += ['# deconfigure bond device %s' % dev]
285 vsctl_argv += datapath_deconfigure_bond(dev)
288 for p in physical_devices:
289 dev = pif_netdev_name(p)
290 vsctl_argv += ['# deconfigure physical port %s' % dev]
291 vsctl_argv += datapath_deconfigure_physical(dev)
293 vsctl_argv += ['--', '--may-exist', 'add-br', bridge]
295 if len(physical_devices) > 1:
296 vsctl_argv += ['# deconfigure bond %s' % pif_netdev_name(pif)]
297 vsctl_argv += datapath_deconfigure_bond(pif_netdev_name(pif))
298 vsctl_argv += ['# configure bond %s' % pif_netdev_name(pif)]
299 vsctl_argv += datapath_configure_bond(pif, physical_devices)
300 extra_up_ports += [pif_netdev_name(pif)]
301 elif len(physical_devices) == 1:
302 iface = pif_netdev_name(physical_devices[0])
303 vsctl_argv += ['# add physical device %s' % iface]
304 vsctl_argv += ['--', '--may-exist', 'add-port', bridge, iface]
305 elif pif_is_tunnel(pif):
306 datapath_configure_tunnel(pif)
308 vsctl_argv += ['# configure Bridge MAC']
309 vsctl_argv += ['--', 'set', 'Bridge', bridge,
310 'other-config:hwaddr=%s' % vsctl_escape(db().get_pif_record(pif)['MAC'])]
312 vsctl_argv += set_br_external_ids(pif)
313 vsctl_argv += ['## done configuring datapath %s' % bridge]
315 return vsctl_argv,extra_up_ports
317 def deconfigure_bridge(pif):
320 bridge = pif_bridge_name(pif)
322 log("deconfigure_bridge: bridge - %s" % bridge)
324 vsctl_argv += ['# deconfigure bridge %s' % bridge]
325 vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
329 def set_br_external_ids(pif):
330 pifrec = db().get_pif_record(pif)
331 dp = pif_datapath(pif)
332 dprec = db().get_pif_record(dp)
334 xs_network_uuids = []
335 for nwpif in db().get_pifs_by_device(pifrec['device']):
336 rec = db().get_pif_record(nwpif)
338 # When state is read from dbcache PIF.currently_attached
339 # is always assumed to be false... Err on the side of
340 # listing even detached networks for the time being.
341 #if nwpif != pif and not rec['currently_attached']:
342 # log("Network PIF %s not currently attached (%s)" % (rec['uuid'],pifrec['uuid']))
344 nwrec = db().get_network_record(rec['network'])
347 if pif_is_vlan(nwpif):
348 xs_network_uuids.append(uuid)
350 xs_network_uuids.insert(0, uuid)
353 vsctl_argv += ['# configure xs-network-uuids']
354 vsctl_argv += ['--', 'br-set-external-id', pif_bridge_name(pif),
355 'xs-network-uuids', ';'.join(xs_network_uuids)]
363 class DatapathVswitch(Datapath):
364 def __init__(self, pif):
365 Datapath.__init__(self, pif)
366 self._dp = pif_datapath(pif)
367 self._ipdev = pif_ipdev_name(pif)
369 if pif_is_vlan(pif) and not self._dp:
370 raise Error("Unbridged VLAN devices not implemented yet")
372 log("Configured for Vswitch datapath")
376 if not os.path.exists("/var/run/openvswitch/db.sock"):
377 # ovsdb-server is not running, so we can't update the database.
378 # Probably we are being called as part of system shutdown. Just
379 # skip the update, since the external-ids will be updated on the
384 for pif in db().get_all_pifs():
385 pifrec = db().get_pif_record(pif)
386 if not pif_is_vlan(pif) and pifrec['currently_attached']:
387 vsctl_argv += set_br_external_ids(pif)
390 datapath_modify_config(vsctl_argv)
392 def configure_ipdev(self, cfg):
393 cfg.write("TYPE=Ethernet\n")
395 def preconfigure(self, parent):
399 pifrec = db().get_pif_record(self._pif)
400 dprec = db().get_pif_record(self._dp)
403 c,e = configure_datapath(self._dp)
404 bridge = pif_bridge_name(self._pif)
408 dpname = pif_bridge_name(self._dp)
410 if pif_is_vlan(self._pif):
411 # XXX this is only needed on XS5.5, because XAPI misguidedly
412 # creates the fake bridge (via bridge ioctl) before it calls us.
413 vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
415 # configure_datapath() set up the underlying datapath bridge.
416 # Stack a VLAN bridge on top of it.
417 vsctl_argv += ['--', '--may-exist', 'add-br',
418 bridge, dpname, pifrec['VLAN']]
420 vsctl_argv += set_br_external_ids(self._pif)
423 vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
424 vsctl_argv += datapath_deconfigure_ipdev(ipdev)
425 vsctl_argv += ["# reconfigure ipdev %s" % ipdev]
426 vsctl_argv += ['--', 'add-port', bridge, ipdev]
429 vsctl_argv += ['# configure Interface MAC']
430 vsctl_argv += ['--', 'set', 'Interface', pif_ipdev_name(self._pif),
431 'MAC=%s' % vsctl_escape(dprec['MAC'])]
433 self._vsctl_argv = vsctl_argv
434 self._extra_ports = extra_ports
436 def bring_down_existing(self):
437 # interface-reconfigure is never explicitly called to down a
438 # bond master. However, when we are called to up a slave it
439 # is implicit that we are destroying the master. Conversely,
440 # when we are called to up a bond is is implicit that we are
441 # taking down the slaves.
443 # This is (only) important in the case where the device being
444 # implicitly taken down uses DHCP. We need to kill the
445 # dhclient process, otherwise performing the inverse operation
446 # later later will fail because ifup will refuse to start a
447 # duplicate dhclient.
448 bond_masters = pif_get_bond_masters(self._pif)
449 for master in bond_masters:
450 log("action_up: bring down bond master %s" % (pif_netdev_name(master)))
451 run_command(["/sbin/ifdown", pif_bridge_name(master)])
453 bond_slaves = pif_get_bond_slaves(self._pif)
454 for slave in bond_slaves:
455 log("action_up: bring down bond slave %s" % (pif_netdev_name(slave)))
456 run_command(["/sbin/ifdown", pif_bridge_name(slave)])
459 # Bring up physical devices. ovs-vswitchd initially enables or
460 # disables bond slaves based on whether carrier is detected
461 # when they are added, and a network device that is down
462 # always reports "no carrier".
463 physical_devices = datapath_get_physical_pifs(self._dp)
465 for p in physical_devices:
466 prec = db().get_pif_record(p)
467 oc = prec['other_config']
469 dev = pif_netdev_name(p)
471 mtu = mtu_setting(prec['network'], "PIF", oc)
475 settings, offload = ethtool_settings(oc)
477 run_command(['/sbin/ethtool', '-s', dev] + settings)
479 run_command(['/sbin/ethtool', '-K', dev] + offload)
481 datapath_modify_config(self._vsctl_argv)
484 for p in self._extra_ports:
485 log("action_up: bring up %s" % p)
488 def bring_down(self):
494 bridge = pif_bridge_name(dp)
496 #nw = db().get_pif_record(self._pif)['network']
497 #nwrec = db().get_network_record(nw)
498 #vsctl_argv += ['# deconfigure network-uuids']
499 #vsctl_argv += ['--del-entry=bridge.%s.network-uuids=%s' % (bridge,nwrec['uuid'])]
501 log("deconfigure ipdev %s on %s" % (ipdev,bridge))
502 vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
503 vsctl_argv += datapath_deconfigure_ipdev(ipdev)
505 if pif_is_vlan(self._pif):
506 # Delete the VLAN bridge.
507 vsctl_argv += deconfigure_bridge(self._pif)
509 # If the VLAN's slave is attached, leave datapath setup.
510 slave = pif_get_vlan_slave(self._pif)
511 if db().get_pif_record(slave)['currently_attached']:
512 log("action_down: vlan slave is currently attached")
515 # If the VLAN's slave has other VLANs that are attached, leave datapath setup.
516 for master in pif_get_vlan_masters(slave):
517 if master != self._pif and db().get_pif_record(master)['currently_attached']:
518 log("action_down: vlan slave has other master: %s" % pif_netdev_name(master))
521 # Otherwise, take down the datapath too (fall through)
523 log("action_down: no more masters, bring down slave %s" % bridge)
525 # Stop here if this PIF has attached VLAN masters.
526 masters = [db().get_pif_record(m)['VLAN'] for m in pif_get_vlan_masters(self._pif) if db().get_pif_record(m)['currently_attached']]
528 log("Leaving datapath %s up due to currently attached VLAN masters %s" % (bridge, masters))
532 vsctl_argv += deconfigure_bridge(dp)
534 physical_devices = [pif_netdev_name(p) for p in datapath_get_physical_pifs(dp)]
536 log("action_down: bring down physical devices - %s" % physical_devices)
538 for p in physical_devices:
541 datapath_modify_config(vsctl_argv)