Catalli's threaded switch
[sliver-openvswitch.git] / xenserver / opt_xensource_libexec_InterfaceReconfigureVswitch.py
1 # Copyright (c) 2008,2009 Citrix Systems, Inc.
2 # Copyright (c) 2009,2010 Nicira Networks.
3 #
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.
8 #
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.
13 #
14 from InterfaceReconfigure import *
15 import os
16 import re
17
18 #
19 # Bare Network Devices -- network devices without IP configuration
20 #
21
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)
26         return
27     run_command(["/sbin/ifconfig", netdev, 'down'])
28
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)
33
34     if mtu:
35         mtu = ["mtu", mtu]
36     else:
37         mtu = []
38
39     run_command(["/sbin/ifconfig", netdev, 'up'] + mtu)
40
41 #
42 # PIF miscellanea
43 #
44
45 def pif_currently_in_use(pif):
46     """Determine if a PIF is currently in use.
47
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
52     """
53     rec = db().get_pif_record(pif)
54     if rec['currently_attached']:
55         log("configure_datapath: %s is currently attached" % (pif_netdev_name(pif)))
56         return True
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)))
60             return True
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)))
64             return True
65     return False
66
67 #
68 # Datapath Configuration
69 #
70
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.
76 """
77     if pif_is_vlan(pif):
78         return pif_datapath(pif_get_vlan_slave(pif))
79
80     pifrec = db().get_pif_record(pif)
81     nwrec = db().get_network_record(pifrec['network'])
82     if not nwrec['bridge']:
83         return None
84     else:
85         return pif
86
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.
91
92 A VLAN PIF cannot be a datapath PIF.
93 """
94     if pif_is_tunnel(pif):
95         return []
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)
101     else:
102         return [pif]
103
104 def datapath_deconfigure_physical(netdev):
105     return ['--', '--with-iface', '--if-exists', 'del-port', netdev]
106
107 def vsctl_escape(s):
108     if s.isalnum():
109         return s
110
111     def escape(match):
112         c = match.group(0)
113         if c == '\0':
114             raise Error("strings may not contain null bytes")
115         elif c == '\\':
116             return r'\\'
117         elif c == '\n':
118             return r'\n'
119         elif c == '\r':
120             return r'\r'
121         elif c == '\t':
122             return r'\t'
123         elif c == '\b':
124             return r'\b'
125         elif c == '\a':
126             return r'\a'
127         else:
128             return r'\x%02x' % ord(c)
129     return '"' + re.sub(r'["\\\000-\037]', escape, s) + '"'
130
131 def datapath_configure_tunnel(pif):
132     pass
133
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)
138
139     argv = ['--', '--fake-iface', 'add-bond', bridge, interface]
140     for slave in slaves:
141         argv += [pif_netdev_name(slave)]
142
143     # Bonding options.
144     bond_options = {
145         "mode":   "balance-slb",
146         "miimon": "100",
147         "downdelay": "200",
148         "updelay": "31000",
149         "use_carrier": "1",
150         }
151     # override defaults with values from other-config whose keys
152     # being with "bond-"
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)
158
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.
166             try:
167                 value = int(val)
168                 if value < 0:
169                     raise ValueError
170
171                 argv += ['bond_%s=%d' % (name, value)]
172             except ValueError:
173                 log("bridge %s has invalid %s '%s'" % (bridge, name, value))
174         else:
175             # Pass other bond options into other_config.
176             argv += ["other-config:%s=%s" % (vsctl_escape("bond-%s" % name),
177                                              vsctl_escape(val))]
178     return argv
179
180 def datapath_deconfigure_bond(netdev):
181     return ['--', '--with-iface', '--if-exists', 'del-port', netdev]
182
183 def datapath_deconfigure_ipdev(interface):
184     return ['--', '--with-iface', '--if-exists', 'del-port', interface]
185
186 def datapath_modify_config(commands):
187     #log("modifying configuration:")
188     #for c in commands:
189     #    log("  %s" % c)
190             
191     rc = run_command(['/usr/bin/ovs-vsctl'] + ['--timeout=20']
192                      + [c for c in commands if not c.startswith('#')])
193     if not rc:       
194         raise Error("Failed to modify vswitch configuration")
195     return True
196
197 #
198 # Toplevel Datapath Configuration.
199 #
200
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
206       on top of 'pif'.
207
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.
212     """
213
214     vsctl_argv = []
215     extra_up_ports = []
216
217     assert not pif_is_vlan(pif)
218     bridge = pif_bridge_name(pif)
219
220     physical_devices = datapath_get_physical_pifs(pif)
221
222     vsctl_argv += ['## configuring datapath %s' % bridge]
223
224     # Determine additional devices to deconfigure.
225     #
226     # Given all physical devices which are part of this PIF we need to
227     # consider:
228     # - any additional bond which a physical device is part of.
229     # - any additional physical devices which are part of an additional bond.
230     #
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):
237             if bond == pif:
238                 log("configure_datapath: leaving bond %s up" % pif_netdev_name(bond))
239                 continue
240             if bond in extra_down_bonds:
241                 continue
242             if db().get_pif_record(bond)['currently_attached']:
243                 log("configure_datapath: implicitly tearing down currently-attached bond %s" % pif_netdev_name(bond))
244
245             extra_down_bonds += [bond]
246
247             for s in pif_get_bond_slaves(bond):
248                 if s in physical_devices:
249                     continue
250                 if s in extra_down_ports:
251                     continue
252                 if pif_currently_in_use(s):
253                     continue
254                 extra_down_ports += [s]
255
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])
260
261     # Need to fully deconfigure any bridge which any of the:
262     # - physical devices
263     # - bond devices
264     # - sibling devices
265     # refers to
266     for brpif in physical_devices + extra_down_ports + extra_down_bonds:
267         if brpif == pif:
268             continue
269         b = pif_bridge_name(brpif)
270         #ifdown(b)
271         # XXX
272         netdev_down(b)
273         vsctl_argv += ['# remove bridge %s' % b]
274         vsctl_argv += ['--', '--if-exists', 'del-br', b]
275
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)
280         netdev_down(dev)
281
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)
286         netdev_down(dev)
287
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)
292
293     vsctl_argv += ['--', '--may-exist', 'add-br', bridge]
294
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)
307
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'])]
311
312     vsctl_argv += set_br_external_ids(pif)
313     vsctl_argv += ['## done configuring datapath %s' % bridge]
314
315     return vsctl_argv,extra_up_ports
316
317 def deconfigure_bridge(pif):
318     vsctl_argv = []
319
320     bridge = pif_bridge_name(pif)
321
322     log("deconfigure_bridge: bridge           - %s" % bridge)
323
324     vsctl_argv += ['# deconfigure bridge %s' % bridge]
325     vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
326
327     return vsctl_argv
328
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)
333
334     xs_network_uuids = []
335     for nwpif in db().get_pifs_by_device(pifrec['device']):
336         rec = db().get_pif_record(nwpif)
337
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']))
343         #    continue
344         nwrec = db().get_network_record(rec['network'])
345         xs_network_uuids += [nwrec['uuid']]
346
347     vsctl_argv = []
348     vsctl_argv += ['# configure xs-network-uuids']
349     vsctl_argv += ['--', 'br-set-external-id', pif_bridge_name(pif),
350             'xs-network-uuids', ';'.join(xs_network_uuids)]
351
352     return vsctl_argv
353
354 #
355 #
356 #
357
358 class DatapathVswitch(Datapath):
359     def __init__(self, pif):
360         Datapath.__init__(self, pif)
361         self._dp = pif_datapath(pif)
362         self._ipdev = pif_ipdev_name(pif)
363
364         if pif_is_vlan(pif) and not self._dp:
365             raise Error("Unbridged VLAN devices not implemented yet")
366         
367         log("Configured for Vswitch datapath")
368
369     @classmethod
370     def rewrite(cls):
371         if not os.path.exists("/var/run/openvswitch/db.sock"):
372             # ovsdb-server is not running, so we can't update the database.
373             # Probably we are being called as part of system shutdown.  Just
374             # skip the update, since the external-ids will be updated on the
375             # next boot anyhow.
376             return
377
378         vsctl_argv = []
379         for pif in db().get_all_pifs():
380             pifrec = db().get_pif_record(pif)
381             if not pif_is_vlan(pif) and pifrec['currently_attached']:
382                 vsctl_argv += set_br_external_ids(pif)
383
384         if vsctl_argv != []:
385             datapath_modify_config(vsctl_argv)
386
387     def configure_ipdev(self, cfg):
388         cfg.write("TYPE=Ethernet\n")
389
390     def preconfigure(self, parent):
391         vsctl_argv = []
392         extra_ports = []
393
394         pifrec = db().get_pif_record(self._pif)
395         dprec = db().get_pif_record(self._dp)
396
397         ipdev = self._ipdev
398         c,e = configure_datapath(self._dp)
399         bridge = pif_bridge_name(self._pif)
400         vsctl_argv += c
401         extra_ports += e
402
403         dpname = pif_bridge_name(self._dp)
404         
405         if pif_is_vlan(self._pif):
406             # XXX this is only needed on XS5.5, because XAPI misguidedly
407             # creates the fake bridge (via bridge ioctl) before it calls us.
408             vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
409
410             # configure_datapath() set up the underlying datapath bridge.
411             # Stack a VLAN bridge on top of it.
412             vsctl_argv += ['--', '--may-exist', 'add-br',
413                            bridge, dpname, pifrec['VLAN']]
414
415             vsctl_argv += set_br_external_ids(self._pif)
416
417         if ipdev != bridge:
418             vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
419             vsctl_argv += datapath_deconfigure_ipdev(ipdev)
420             vsctl_argv += ["# reconfigure ipdev %s" % ipdev]
421             vsctl_argv += ['--', 'add-port', bridge, ipdev]
422
423         if ipdev != dpname:
424             vsctl_argv += ['# configure Interface MAC']
425             vsctl_argv += ['--', 'set', 'Interface', pif_ipdev_name(self._pif),
426                            'MAC=%s' % vsctl_escape(dprec['MAC'])]
427
428         self._vsctl_argv = vsctl_argv
429         self._extra_ports = extra_ports
430
431     def bring_down_existing(self):
432         # interface-reconfigure is never explicitly called to down a
433         # bond master.  However, when we are called to up a slave it
434         # is implicit that we are destroying the master.  Conversely,
435         # when we are called to up a bond is is implicit that we are
436         # taking down the slaves.
437         #
438         # This is (only) important in the case where the device being
439         # implicitly taken down uses DHCP.  We need to kill the
440         # dhclient process, otherwise performing the inverse operation
441         # later later will fail because ifup will refuse to start a
442         # duplicate dhclient.
443         bond_masters = pif_get_bond_masters(self._pif)
444         for master in bond_masters:
445             log("action_up: bring down bond master %s" % (pif_netdev_name(master)))
446             run_command(["/sbin/ifdown", pif_bridge_name(master)])
447
448         bond_slaves = pif_get_bond_slaves(self._pif)
449         for slave in bond_slaves:
450             log("action_up: bring down bond slave %s" % (pif_netdev_name(slave)))
451             run_command(["/sbin/ifdown", pif_bridge_name(slave)])
452
453     def configure(self):
454         # Bring up physical devices. ovs-vswitchd initially enables or
455         # disables bond slaves based on whether carrier is detected
456         # when they are added, and a network device that is down
457         # always reports "no carrier".
458         physical_devices = datapath_get_physical_pifs(self._dp)
459         
460         for p in physical_devices:
461             prec = db().get_pif_record(p)
462             oc = prec['other_config']
463
464             dev = pif_netdev_name(p)
465
466             mtu = mtu_setting(prec['network'], "PIF", oc)
467
468             netdev_up(dev, mtu)
469
470             settings, offload = ethtool_settings(oc)
471             if len(settings):
472                 run_command(['/sbin/ethtool', '-s', dev] + settings)
473             if len(offload):
474                 run_command(['/sbin/ethtool', '-K', dev] + offload)
475
476         datapath_modify_config(self._vsctl_argv)
477
478     def post(self):
479         for p in self._extra_ports:
480             log("action_up: bring up %s" % p)
481             netdev_up(p)
482
483     def bring_down(self):
484         vsctl_argv = []
485
486         dp = self._dp
487         ipdev = self._ipdev
488         
489         bridge = pif_bridge_name(dp)
490
491         #nw = db().get_pif_record(self._pif)['network']
492         #nwrec = db().get_network_record(nw)
493         #vsctl_argv += ['# deconfigure network-uuids']
494         #vsctl_argv += ['--del-entry=bridge.%s.network-uuids=%s' % (bridge,nwrec['uuid'])]
495
496         log("deconfigure ipdev %s on %s" % (ipdev,bridge))
497         vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
498         vsctl_argv += datapath_deconfigure_ipdev(ipdev)
499
500         if pif_is_vlan(self._pif):
501             # Delete the VLAN bridge.
502             vsctl_argv += deconfigure_bridge(self._pif)
503
504             # If the VLAN's slave is attached, leave datapath setup.
505             slave = pif_get_vlan_slave(self._pif)
506             if db().get_pif_record(slave)['currently_attached']:
507                 log("action_down: vlan slave is currently attached")
508                 dp = None
509
510             # If the VLAN's slave has other VLANs that are attached, leave datapath setup.
511             for master in pif_get_vlan_masters(slave):
512                 if master != self._pif and db().get_pif_record(master)['currently_attached']:
513                     log("action_down: vlan slave has other master: %s" % pif_netdev_name(master))
514                     dp = None
515
516             # Otherwise, take down the datapath too (fall through)
517             if dp:
518                 log("action_down: no more masters, bring down slave %s" % bridge)
519         else:
520             # Stop here if this PIF has attached VLAN masters.
521             masters = [db().get_pif_record(m)['VLAN'] for m in pif_get_vlan_masters(self._pif) if db().get_pif_record(m)['currently_attached']]
522             if len(masters) > 0:
523                 log("Leaving datapath %s up due to currently attached VLAN masters %s" % (bridge, masters))
524                 dp = None
525
526         if dp:
527             vsctl_argv += deconfigure_bridge(dp)
528
529             physical_devices = [pif_netdev_name(p) for p in datapath_get_physical_pifs(dp)]
530
531             log("action_down: bring down physical devices - %s" % physical_devices)
532         
533             for p in physical_devices:
534                 netdev_down(p)
535
536         datapath_modify_config(vsctl_argv)