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))
176 if val in ['balance-slb', 'active-backup']:
177 argv += ['bond_%s=%s' % (name, val)]
179 log("bridge %s has invalid %s '%s'" % (bridge, name, val))
181 # Pass other bond options into other_config.
182 argv += ["other-config:%s=%s" % (vsctl_escape("bond-%s" % name),
186 def datapath_deconfigure_bond(netdev):
187 return ['--', '--with-iface', '--if-exists', 'del-port', netdev]
189 def datapath_deconfigure_ipdev(interface):
190 return ['--', '--with-iface', '--if-exists', 'del-port', interface]
192 def datapath_modify_config(commands):
193 #log("modifying configuration:")
197 rc = run_command(['/usr/bin/ovs-vsctl'] + ['--timeout=20']
198 + [c for c in commands if not c.startswith('#')])
200 raise Error("Failed to modify vswitch configuration")
204 # Toplevel Datapath Configuration.
207 def configure_datapath(pif):
208 """Bring up the configuration for 'pif', which must not be a VLAN PIF, by:
209 - Tearing down other PIFs that use the same physical devices as 'pif'.
210 - Ensuring that 'pif' itself is set up.
211 - *Not* tearing down any PIFs that are stacked on top of 'pif' (i.e. VLANs
214 Returns a tuple containing
215 - A list containing the necessary vsctl command line arguments
216 - A list of additional devices which should be brought up after
217 the configuration is applied.
223 assert not pif_is_vlan(pif)
224 bridge = pif_bridge_name(pif)
226 physical_devices = datapath_get_physical_pifs(pif)
228 vsctl_argv += ['## configuring datapath %s' % bridge]
230 # Determine additional devices to deconfigure.
232 # Given all physical devices which are part of this PIF we need to
234 # - any additional bond which a physical device is part of.
235 # - any additional physical devices which are part of an additional bond.
237 # Any of these which are not currently in use should be brought
238 # down and deconfigured.
239 extra_down_bonds = []
240 extra_down_ports = []
241 for p in physical_devices:
242 for bond in pif_get_bond_masters(p):
244 log("configure_datapath: leaving bond %s up" % pif_netdev_name(bond))
246 if bond in extra_down_bonds:
248 if db().get_pif_record(bond)['currently_attached']:
249 log("configure_datapath: implicitly tearing down currently-attached bond %s" % pif_netdev_name(bond))
251 extra_down_bonds += [bond]
253 for s in pif_get_bond_slaves(bond):
254 if s in physical_devices:
256 if s in extra_down_ports:
258 if pif_currently_in_use(s):
260 extra_down_ports += [s]
262 log("configure_datapath: bridge - %s" % bridge)
263 log("configure_datapath: physical - %s" % [pif_netdev_name(p) for p in physical_devices])
264 log("configure_datapath: extra ports - %s" % [pif_netdev_name(p) for p in extra_down_ports])
265 log("configure_datapath: extra bonds - %s" % [pif_netdev_name(p) for p in extra_down_bonds])
267 # Need to fully deconfigure any bridge which any of the:
272 for brpif in physical_devices + extra_down_ports + extra_down_bonds:
275 b = pif_bridge_name(brpif)
279 vsctl_argv += ['# remove bridge %s' % b]
280 vsctl_argv += ['--', '--if-exists', 'del-br', b]
282 for n in extra_down_ports:
283 dev = pif_netdev_name(n)
284 vsctl_argv += ['# deconfigure sibling physical device %s' % dev]
285 vsctl_argv += datapath_deconfigure_physical(dev)
288 for n in extra_down_bonds:
289 dev = pif_netdev_name(n)
290 vsctl_argv += ['# deconfigure bond device %s' % dev]
291 vsctl_argv += datapath_deconfigure_bond(dev)
294 for p in physical_devices:
295 dev = pif_netdev_name(p)
296 vsctl_argv += ['# deconfigure physical port %s' % dev]
297 vsctl_argv += datapath_deconfigure_physical(dev)
299 vsctl_argv += ['--', '--may-exist', 'add-br', bridge]
301 if len(physical_devices) > 1:
302 vsctl_argv += ['# deconfigure bond %s' % pif_netdev_name(pif)]
303 vsctl_argv += datapath_deconfigure_bond(pif_netdev_name(pif))
304 vsctl_argv += ['# configure bond %s' % pif_netdev_name(pif)]
305 vsctl_argv += datapath_configure_bond(pif, physical_devices)
306 extra_up_ports += [pif_netdev_name(pif)]
307 elif len(physical_devices) == 1:
308 iface = pif_netdev_name(physical_devices[0])
309 vsctl_argv += ['# add physical device %s' % iface]
310 vsctl_argv += ['--', '--may-exist', 'add-port', bridge, iface]
311 elif pif_is_tunnel(pif):
312 datapath_configure_tunnel(pif)
314 vsctl_argv += ['# configure Bridge MAC']
315 vsctl_argv += ['--', 'set', 'Bridge', bridge,
316 'other-config:hwaddr=%s' % vsctl_escape(db().get_pif_record(pif)['MAC'])]
318 vsctl_argv += set_br_external_ids(pif)
319 vsctl_argv += ['## done configuring datapath %s' % bridge]
321 return vsctl_argv,extra_up_ports
323 def deconfigure_bridge(pif):
326 bridge = pif_bridge_name(pif)
328 log("deconfigure_bridge: bridge - %s" % bridge)
330 vsctl_argv += ['# deconfigure bridge %s' % bridge]
331 vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
335 def set_br_external_ids(pif):
336 pifrec = db().get_pif_record(pif)
337 dp = pif_datapath(pif)
338 dprec = db().get_pif_record(dp)
340 xs_network_uuids = []
341 for nwpif in db().get_pifs_by_device(pifrec['device']):
342 rec = db().get_pif_record(nwpif)
344 # When state is read from dbcache PIF.currently_attached
345 # is always assumed to be false... Err on the side of
346 # listing even detached networks for the time being.
347 #if nwpif != pif and not rec['currently_attached']:
348 # log("Network PIF %s not currently attached (%s)" % (rec['uuid'],pifrec['uuid']))
350 nwrec = db().get_network_record(rec['network'])
353 if pif_is_vlan(nwpif):
354 xs_network_uuids.append(uuid)
356 xs_network_uuids.insert(0, uuid)
359 vsctl_argv += ['# configure xs-network-uuids']
360 vsctl_argv += ['--', 'br-set-external-id', pif_bridge_name(pif),
361 'xs-network-uuids', ';'.join(xs_network_uuids)]
369 class DatapathVswitch(Datapath):
370 def __init__(self, pif):
371 Datapath.__init__(self, pif)
372 self._dp = pif_datapath(pif)
373 self._ipdev = pif_ipdev_name(pif)
375 if pif_is_vlan(pif) and not self._dp:
376 raise Error("Unbridged VLAN devices not implemented yet")
378 log("Configured for Vswitch datapath")
382 if not os.path.exists("/var/run/openvswitch/db.sock"):
383 # ovsdb-server is not running, so we can't update the database.
384 # Probably we are being called as part of system shutdown. Just
385 # skip the update, since the external-ids will be updated on the
390 for pif in db().get_all_pifs():
391 pifrec = db().get_pif_record(pif)
392 if not pif_is_vlan(pif) and pifrec['currently_attached']:
393 vsctl_argv += set_br_external_ids(pif)
396 datapath_modify_config(vsctl_argv)
398 def configure_ipdev(self, cfg):
399 cfg.write("TYPE=Ethernet\n")
401 def preconfigure(self, parent):
405 pifrec = db().get_pif_record(self._pif)
406 dprec = db().get_pif_record(self._dp)
409 c,e = configure_datapath(self._dp)
410 bridge = pif_bridge_name(self._pif)
414 dpname = pif_bridge_name(self._dp)
416 if pif_is_vlan(self._pif):
417 # XXX this is only needed on XS5.5, because XAPI misguidedly
418 # creates the fake bridge (via bridge ioctl) before it calls us.
419 vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
421 # configure_datapath() set up the underlying datapath bridge.
422 # Stack a VLAN bridge on top of it.
423 vsctl_argv += ['--', '--may-exist', 'add-br',
424 bridge, dpname, pifrec['VLAN']]
426 vsctl_argv += set_br_external_ids(self._pif)
429 vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
430 vsctl_argv += datapath_deconfigure_ipdev(ipdev)
431 vsctl_argv += ["# reconfigure ipdev %s" % ipdev]
432 vsctl_argv += ['--', 'add-port', bridge, ipdev]
435 vsctl_argv += ['# configure Interface MAC']
436 vsctl_argv += ['--', 'set', 'Interface', pif_ipdev_name(self._pif),
437 'MAC=%s' % vsctl_escape(dprec['MAC'])]
439 self._vsctl_argv = vsctl_argv
440 self._extra_ports = extra_ports
442 def bring_down_existing(self):
443 # interface-reconfigure is never explicitly called to down a
444 # bond master. However, when we are called to up a slave it
445 # is implicit that we are destroying the master. Conversely,
446 # when we are called to up a bond is is implicit that we are
447 # taking down the slaves.
449 # This is (only) important in the case where the device being
450 # implicitly taken down uses DHCP. We need to kill the
451 # dhclient process, otherwise performing the inverse operation
452 # later later will fail because ifup will refuse to start a
453 # duplicate dhclient.
454 bond_masters = pif_get_bond_masters(self._pif)
455 for master in bond_masters:
456 log("action_up: bring down bond master %s" % (pif_netdev_name(master)))
457 run_command(["/sbin/ifdown", pif_bridge_name(master)])
459 bond_slaves = pif_get_bond_slaves(self._pif)
460 for slave in bond_slaves:
461 log("action_up: bring down bond slave %s" % (pif_netdev_name(slave)))
462 run_command(["/sbin/ifdown", pif_bridge_name(slave)])
465 # Bring up physical devices. ovs-vswitchd initially enables or
466 # disables bond slaves based on whether carrier is detected
467 # when they are added, and a network device that is down
468 # always reports "no carrier".
469 physical_devices = datapath_get_physical_pifs(self._dp)
471 for p in physical_devices:
472 prec = db().get_pif_record(p)
473 oc = prec['other_config']
475 dev = pif_netdev_name(p)
477 mtu = mtu_setting(prec['network'], "PIF", oc)
481 settings, offload = ethtool_settings(oc)
483 run_command(['/sbin/ethtool', '-s', dev] + settings)
485 run_command(['/sbin/ethtool', '-K', dev] + offload)
487 datapath_modify_config(self._vsctl_argv)
490 for p in self._extra_ports:
491 log("action_up: bring up %s" % p)
494 def bring_down(self):
500 bridge = pif_bridge_name(dp)
502 #nw = db().get_pif_record(self._pif)['network']
503 #nwrec = db().get_network_record(nw)
504 #vsctl_argv += ['# deconfigure network-uuids']
505 #vsctl_argv += ['--del-entry=bridge.%s.network-uuids=%s' % (bridge,nwrec['uuid'])]
507 log("deconfigure ipdev %s on %s" % (ipdev,bridge))
508 vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
509 vsctl_argv += datapath_deconfigure_ipdev(ipdev)
511 if pif_is_vlan(self._pif):
512 # Delete the VLAN bridge.
513 vsctl_argv += deconfigure_bridge(self._pif)
515 # If the VLAN's slave is attached, leave datapath setup.
516 slave = pif_get_vlan_slave(self._pif)
517 if db().get_pif_record(slave)['currently_attached']:
518 log("action_down: vlan slave is currently attached")
521 # If the VLAN's slave has other VLANs that are attached, leave datapath setup.
522 for master in pif_get_vlan_masters(slave):
523 if master != self._pif and db().get_pif_record(master)['currently_attached']:
524 log("action_down: vlan slave has other master: %s" % pif_netdev_name(master))
527 # Otherwise, take down the datapath too (fall through)
529 log("action_down: no more masters, bring down slave %s" % bridge)
531 # Stop here if this PIF has attached VLAN masters.
532 masters = [db().get_pif_record(m)['VLAN'] for m in pif_get_vlan_masters(self._pif) if db().get_pif_record(m)['currently_attached']]
534 log("Leaving datapath %s up due to currently attached VLAN masters %s" % (bridge, masters))
538 vsctl_argv += deconfigure_bridge(dp)
540 physical_devices = [pif_netdev_name(p) for p in datapath_get_physical_pifs(dp)]
542 log("action_down: bring down physical devices - %s" % physical_devices)
544 for p in physical_devices:
547 datapath_modify_config(vsctl_argv)