xenserver: Support fail_mode override at network level.
[cascardo/ovs.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         elif name in ['miimon', 'use_carrier']:
175             try:
176                 value = int(val)
177                 if value < 0:
178                     raise ValueError
179
180                 if name == 'use_carrier':
181                     if value:
182                         value = "carrier"
183                     else:
184                         value = "miimon"
185                     argv += ["other-config:bond-detect-mode=%s" % value]
186                 else:
187                     argv += ["other-config:bond-miimon-interval=%d" % value]
188             except ValueError:
189                 log("bridge %s has invalid %s '%s'" % (bridge, name, value))
190         elif name == "mode":
191
192             if val in ['balance-slb', 'active-backup']:
193                 argv += ['bond_%s=%s' % (name, val)]
194             else:
195                 log("bridge %s has invalid %s '%s'" % (bridge, name, val))
196         else:
197             # Pass other bond options into other_config.
198             argv += ["other-config:%s=%s" % (vsctl_escape("bond-%s" % name),
199                                              vsctl_escape(val))]
200     return argv
201
202 def datapath_deconfigure_bond(netdev):
203     return ['--', '--with-iface', '--if-exists', 'del-port', netdev]
204
205 def datapath_deconfigure_ipdev(interface):
206     return ['--', '--with-iface', '--if-exists', 'del-port', interface]
207
208 def datapath_modify_config(commands):
209     #log("modifying configuration:")
210     #for c in commands:
211     #    log("  %s" % c)
212             
213     rc = run_command(['/usr/bin/ovs-vsctl'] + ['--timeout=20']
214                      + [c for c in commands if not c.startswith('#')])
215     if not rc:       
216         raise Error("Failed to modify vswitch configuration")
217     return True
218
219 #
220 # Toplevel Datapath Configuration.
221 #
222
223 def configure_datapath(pif):
224     """Bring up the configuration for 'pif', which must not be a VLAN PIF, by:
225     - Tearing down other PIFs that use the same physical devices as 'pif'.
226     - Ensuring that 'pif' itself is set up.
227     - *Not* tearing down any PIFs that are stacked on top of 'pif' (i.e. VLANs
228       on top of 'pif'.
229
230     Returns a tuple containing
231     - A list containing the necessary vsctl command line arguments
232     - A list of additional devices which should be brought up after
233       the configuration is applied.
234     """
235
236     vsctl_argv = []
237     extra_up_ports = []
238
239     assert not pif_is_vlan(pif)
240     bridge = pif_bridge_name(pif)
241
242     physical_devices = datapath_get_physical_pifs(pif)
243
244     vsctl_argv += ['## configuring datapath %s' % bridge]
245
246     # Determine additional devices to deconfigure.
247     #
248     # Given all physical devices which are part of this PIF we need to
249     # consider:
250     # - any additional bond which a physical device is part of.
251     # - any additional physical devices which are part of an additional bond.
252     #
253     # Any of these which are not currently in use should be brought
254     # down and deconfigured.
255     extra_down_bonds = []
256     extra_down_ports = []
257     for p in physical_devices:
258         for bond in pif_get_bond_masters(p):
259             if bond == pif:
260                 log("configure_datapath: leaving bond %s up" % pif_netdev_name(bond))
261                 continue
262             if bond in extra_down_bonds:
263                 continue
264             if db().get_pif_record(bond)['currently_attached']:
265                 log("configure_datapath: implicitly tearing down currently-attached bond %s" % pif_netdev_name(bond))
266
267             extra_down_bonds += [bond]
268
269             for s in pif_get_bond_slaves(bond):
270                 if s in physical_devices:
271                     continue
272                 if s in extra_down_ports:
273                     continue
274                 if pif_currently_in_use(s):
275                     continue
276                 extra_down_ports += [s]
277
278     log("configure_datapath: bridge      - %s" % bridge)
279     log("configure_datapath: physical    - %s" % [pif_netdev_name(p) for p in physical_devices])
280     log("configure_datapath: extra ports - %s" % [pif_netdev_name(p) for p in extra_down_ports])
281     log("configure_datapath: extra bonds - %s" % [pif_netdev_name(p) for p in extra_down_bonds])
282
283     # Need to fully deconfigure any bridge which any of the:
284     # - physical devices
285     # - bond devices
286     # - sibling devices
287     # refers to
288     for brpif in physical_devices + extra_down_ports + extra_down_bonds:
289         if brpif == pif:
290             continue
291         b = pif_bridge_name(brpif)
292         #ifdown(b)
293         # XXX
294         netdev_down(b)
295         vsctl_argv += ['# remove bridge %s' % b]
296         vsctl_argv += ['--', '--if-exists', 'del-br', b]
297
298     for n in extra_down_ports:
299         dev = pif_netdev_name(n)
300         vsctl_argv += ['# deconfigure sibling physical device %s' % dev]
301         vsctl_argv += datapath_deconfigure_physical(dev)
302         netdev_down(dev)
303
304     for n in extra_down_bonds:
305         dev = pif_netdev_name(n)
306         vsctl_argv += ['# deconfigure bond device %s' % dev]
307         vsctl_argv += datapath_deconfigure_bond(dev)
308         netdev_down(dev)
309
310     for p in physical_devices:
311         dev = pif_netdev_name(p)
312         vsctl_argv += ['# deconfigure physical port %s' % dev]
313         vsctl_argv += datapath_deconfigure_physical(dev)
314
315     vsctl_argv += ['--', '--may-exist', 'add-br', bridge]
316
317     if len(physical_devices) > 1:
318         vsctl_argv += ['# deconfigure bond %s' % pif_netdev_name(pif)]
319         vsctl_argv += datapath_deconfigure_bond(pif_netdev_name(pif))
320         vsctl_argv += ['# configure bond %s' % pif_netdev_name(pif)]
321         vsctl_argv += datapath_configure_bond(pif, physical_devices)
322         extra_up_ports += [pif_netdev_name(pif)]
323     elif len(physical_devices) == 1:
324         iface = pif_netdev_name(physical_devices[0])
325         vsctl_argv += ['# add physical device %s' % iface]
326         vsctl_argv += ['--', '--may-exist', 'add-port', bridge, iface]
327     elif pif_is_tunnel(pif):
328         datapath_configure_tunnel(pif)
329
330     vsctl_argv += ['# configure Bridge MAC']
331     vsctl_argv += ['--', 'set', 'Bridge', bridge,
332                    'other-config:hwaddr=%s' % vsctl_escape(db().get_pif_record(pif)['MAC'])]
333
334     pool = db().get_pool_record()
335     network = db().get_network_by_bridge(bridge)
336     fail_mode = None
337     valid_fail_modes = ['standalone', 'secure']
338
339     if network:
340         network_rec = db().get_network_record(network)
341         fail_mode = network_rec['other_config'].get('vswitch-controller-fail-mode')
342
343     if (fail_mode not in valid_fail_modes) and pool:
344         fail_mode = pool['other_config'].get('vswitch-controller-fail-mode')
345
346     if fail_mode not in valid_fail_modes:
347         fail_mode = 'standalone'
348
349     vsctl_argv += ['--', 'set', 'Bridge', bridge, 'fail_mode=%s' % fail_mode]
350
351     vsctl_argv += set_br_external_ids(pif)
352     vsctl_argv += ['## done configuring datapath %s' % bridge]
353
354     return vsctl_argv,extra_up_ports
355
356 def deconfigure_bridge(pif):
357     vsctl_argv = []
358
359     bridge = pif_bridge_name(pif)
360
361     log("deconfigure_bridge: bridge           - %s" % bridge)
362
363     vsctl_argv += ['# deconfigure bridge %s' % bridge]
364     vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
365
366     return vsctl_argv
367
368 def set_br_external_ids(pif):
369     pifrec = db().get_pif_record(pif)
370     dp = pif_datapath(pif)
371     dprec = db().get_pif_record(dp)
372
373     xs_network_uuids = []
374     for nwpif in db().get_pifs_by_device(pifrec['device']):
375         rec = db().get_pif_record(nwpif)
376
377         # When state is read from dbcache PIF.currently_attached
378         # is always assumed to be false... Err on the side of
379         # listing even detached networks for the time being.
380         #if nwpif != pif and not rec['currently_attached']:
381         #    log("Network PIF %s not currently attached (%s)" % (rec['uuid'],pifrec['uuid']))
382         #    continue
383         nwrec = db().get_network_record(rec['network'])
384
385         uuid = nwrec['uuid']
386         if pif_is_vlan(nwpif):
387             xs_network_uuids.append(uuid)
388         else:
389             xs_network_uuids.insert(0, uuid)
390
391     vsctl_argv = []
392     vsctl_argv += ['# configure xs-network-uuids']
393     vsctl_argv += ['--', 'br-set-external-id', pif_bridge_name(pif),
394             'xs-network-uuids', ';'.join(xs_network_uuids)]
395
396     return vsctl_argv
397
398 #
399 #
400 #
401
402 class DatapathVswitch(Datapath):
403     def __init__(self, pif):
404         Datapath.__init__(self, pif)
405         self._dp = pif_datapath(pif)
406         self._ipdev = pif_ipdev_name(pif)
407
408         if pif_is_vlan(pif) and not self._dp:
409             raise Error("Unbridged VLAN devices not implemented yet")
410         
411         log("Configured for Vswitch datapath")
412
413     @classmethod
414     def rewrite(cls):
415         if not os.path.exists("/var/run/openvswitch/db.sock"):
416             # ovsdb-server is not running, so we can't update the database.
417             # Probably we are being called as part of system shutdown.  Just
418             # skip the update, since the external-ids will be updated on the
419             # next boot anyhow.
420             return
421
422         vsctl_argv = []
423         for pif in db().get_all_pifs():
424             pifrec = db().get_pif_record(pif)
425             if not pif_is_vlan(pif) and pifrec['currently_attached']:
426                 vsctl_argv += set_br_external_ids(pif)
427
428         if vsctl_argv != []:
429             datapath_modify_config(vsctl_argv)
430
431     def configure_ipdev(self, cfg):
432         cfg.write("TYPE=Ethernet\n")
433
434     def preconfigure(self, parent):
435         vsctl_argv = []
436         extra_ports = []
437
438         pifrec = db().get_pif_record(self._pif)
439         dprec = db().get_pif_record(self._dp)
440
441         ipdev = self._ipdev
442         c,e = configure_datapath(self._dp)
443         bridge = pif_bridge_name(self._pif)
444         vsctl_argv += c
445         extra_ports += e
446
447         dpname = pif_bridge_name(self._dp)
448         
449         if pif_is_vlan(self._pif):
450             # XXX this is only needed on XS5.5, because XAPI misguidedly
451             # creates the fake bridge (via bridge ioctl) before it calls us.
452             vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
453
454             # configure_datapath() set up the underlying datapath bridge.
455             # Stack a VLAN bridge on top of it.
456             vsctl_argv += ['--', '--may-exist', 'add-br',
457                            bridge, dpname, pifrec['VLAN']]
458
459             vsctl_argv += set_br_external_ids(self._pif)
460
461         if ipdev != bridge:
462             vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
463             vsctl_argv += datapath_deconfigure_ipdev(ipdev)
464             vsctl_argv += ["# reconfigure ipdev %s" % ipdev]
465             vsctl_argv += ['--', 'add-port', bridge, ipdev]
466
467         if ipdev != dpname:
468             vsctl_argv += ['# configure Interface MAC']
469             vsctl_argv += ['--', 'set', 'Interface', pif_ipdev_name(self._pif),
470                            'MAC=%s' % vsctl_escape(dprec['MAC'])]
471
472         self._vsctl_argv = vsctl_argv
473         self._extra_ports = extra_ports
474
475     def bring_down_existing(self):
476         # interface-reconfigure is never explicitly called to down a
477         # bond master.  However, when we are called to up a slave it
478         # is implicit that we are destroying the master.  Conversely,
479         # when we are called to up a bond is is implicit that we are
480         # taking down the slaves.
481         #
482         # This is (only) important in the case where the device being
483         # implicitly taken down uses DHCP.  We need to kill the
484         # dhclient process, otherwise performing the inverse operation
485         # later later will fail because ifup will refuse to start a
486         # duplicate dhclient.
487         bond_masters = pif_get_bond_masters(self._pif)
488         for master in bond_masters:
489             log("action_up: bring down bond master %s" % (pif_netdev_name(master)))
490             run_command(["/sbin/ifdown", pif_bridge_name(master)])
491
492         bond_slaves = pif_get_bond_slaves(self._pif)
493         for slave in bond_slaves:
494             log("action_up: bring down bond slave %s" % (pif_netdev_name(slave)))
495             run_command(["/sbin/ifdown", pif_bridge_name(slave)])
496
497     def configure(self):
498         # Bring up physical devices. ovs-vswitchd initially enables or
499         # disables bond slaves based on whether carrier is detected
500         # when they are added, and a network device that is down
501         # always reports "no carrier".
502         physical_devices = datapath_get_physical_pifs(self._dp)
503         
504         for p in physical_devices:
505             prec = db().get_pif_record(p)
506             oc = prec['other_config']
507
508             dev = pif_netdev_name(p)
509
510             mtu = mtu_setting(prec['network'], "PIF", oc)
511
512             netdev_up(dev, mtu)
513
514             settings, offload = ethtool_settings(oc)
515             if len(settings):
516                 run_command(['/sbin/ethtool', '-s', dev] + settings)
517             if len(offload):
518                 run_command(['/sbin/ethtool', '-K', dev] + offload)
519
520         datapath_modify_config(self._vsctl_argv)
521
522     def post(self):
523         for p in self._extra_ports:
524             log("action_up: bring up %s" % p)
525             netdev_up(p)
526
527     def bring_down(self):
528         vsctl_argv = []
529
530         dp = self._dp
531         ipdev = self._ipdev
532         
533         bridge = pif_bridge_name(dp)
534
535         #nw = db().get_pif_record(self._pif)['network']
536         #nwrec = db().get_network_record(nw)
537         #vsctl_argv += ['# deconfigure network-uuids']
538         #vsctl_argv += ['--del-entry=bridge.%s.network-uuids=%s' % (bridge,nwrec['uuid'])]
539
540         log("deconfigure ipdev %s on %s" % (ipdev,bridge))
541         vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
542         vsctl_argv += datapath_deconfigure_ipdev(ipdev)
543
544         if pif_is_vlan(self._pif):
545             # Delete the VLAN bridge.
546             vsctl_argv += deconfigure_bridge(self._pif)
547
548             # If the VLAN's slave is attached, leave datapath setup.
549             slave = pif_get_vlan_slave(self._pif)
550             if db().get_pif_record(slave)['currently_attached']:
551                 log("action_down: vlan slave is currently attached")
552                 dp = None
553
554             # If the VLAN's slave has other VLANs that are attached, leave datapath setup.
555             for master in pif_get_vlan_masters(slave):
556                 if master != self._pif and db().get_pif_record(master)['currently_attached']:
557                     log("action_down: vlan slave has other master: %s" % pif_netdev_name(master))
558                     dp = None
559
560             # Otherwise, take down the datapath too (fall through)
561             if dp:
562                 log("action_down: no more masters, bring down slave %s" % bridge)
563         else:
564             # Stop here if this PIF has attached VLAN masters.
565             masters = [db().get_pif_record(m)['VLAN'] for m in pif_get_vlan_masters(self._pif) if db().get_pif_record(m)['currently_attached']]
566             if len(masters) > 0:
567                 log("Leaving datapath %s up due to currently attached VLAN masters %s" % (bridge, masters))
568                 dp = None
569
570         if dp:
571             vsctl_argv += deconfigure_bridge(dp)
572
573             physical_devices = [pif_netdev_name(p) for p in datapath_get_physical_pifs(dp)]
574
575             log("action_down: bring down physical devices - %s" % physical_devices)
576         
577             for p in physical_devices:
578                 netdev_down(p)
579
580         datapath_modify_config(vsctl_argv)