xenserver: Allow fail_mode to be set from xapi.
[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     fail_mode = pool['other_config']['vswitch-controller-fail-mode']
336
337     if fail_mode in ['standalone', 'secure']:
338         vsctl_argv += ['--', 'set', 'Bridge', bridge, 'fail_mode=%s' % fail_mode]
339
340     vsctl_argv += set_br_external_ids(pif)
341     vsctl_argv += ['## done configuring datapath %s' % bridge]
342
343     return vsctl_argv,extra_up_ports
344
345 def deconfigure_bridge(pif):
346     vsctl_argv = []
347
348     bridge = pif_bridge_name(pif)
349
350     log("deconfigure_bridge: bridge           - %s" % bridge)
351
352     vsctl_argv += ['# deconfigure bridge %s' % bridge]
353     vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
354
355     return vsctl_argv
356
357 def set_br_external_ids(pif):
358     pifrec = db().get_pif_record(pif)
359     dp = pif_datapath(pif)
360     dprec = db().get_pif_record(dp)
361
362     xs_network_uuids = []
363     for nwpif in db().get_pifs_by_device(pifrec['device']):
364         rec = db().get_pif_record(nwpif)
365
366         # When state is read from dbcache PIF.currently_attached
367         # is always assumed to be false... Err on the side of
368         # listing even detached networks for the time being.
369         #if nwpif != pif and not rec['currently_attached']:
370         #    log("Network PIF %s not currently attached (%s)" % (rec['uuid'],pifrec['uuid']))
371         #    continue
372         nwrec = db().get_network_record(rec['network'])
373
374         uuid = nwrec['uuid']
375         if pif_is_vlan(nwpif):
376             xs_network_uuids.append(uuid)
377         else:
378             xs_network_uuids.insert(0, uuid)
379
380     vsctl_argv = []
381     vsctl_argv += ['# configure xs-network-uuids']
382     vsctl_argv += ['--', 'br-set-external-id', pif_bridge_name(pif),
383             'xs-network-uuids', ';'.join(xs_network_uuids)]
384
385     return vsctl_argv
386
387 #
388 #
389 #
390
391 class DatapathVswitch(Datapath):
392     def __init__(self, pif):
393         Datapath.__init__(self, pif)
394         self._dp = pif_datapath(pif)
395         self._ipdev = pif_ipdev_name(pif)
396
397         if pif_is_vlan(pif) and not self._dp:
398             raise Error("Unbridged VLAN devices not implemented yet")
399         
400         log("Configured for Vswitch datapath")
401
402     @classmethod
403     def rewrite(cls):
404         if not os.path.exists("/var/run/openvswitch/db.sock"):
405             # ovsdb-server is not running, so we can't update the database.
406             # Probably we are being called as part of system shutdown.  Just
407             # skip the update, since the external-ids will be updated on the
408             # next boot anyhow.
409             return
410
411         vsctl_argv = []
412         for pif in db().get_all_pifs():
413             pifrec = db().get_pif_record(pif)
414             if not pif_is_vlan(pif) and pifrec['currently_attached']:
415                 vsctl_argv += set_br_external_ids(pif)
416
417         if vsctl_argv != []:
418             datapath_modify_config(vsctl_argv)
419
420     def configure_ipdev(self, cfg):
421         cfg.write("TYPE=Ethernet\n")
422
423     def preconfigure(self, parent):
424         vsctl_argv = []
425         extra_ports = []
426
427         pifrec = db().get_pif_record(self._pif)
428         dprec = db().get_pif_record(self._dp)
429
430         ipdev = self._ipdev
431         c,e = configure_datapath(self._dp)
432         bridge = pif_bridge_name(self._pif)
433         vsctl_argv += c
434         extra_ports += e
435
436         dpname = pif_bridge_name(self._dp)
437         
438         if pif_is_vlan(self._pif):
439             # XXX this is only needed on XS5.5, because XAPI misguidedly
440             # creates the fake bridge (via bridge ioctl) before it calls us.
441             vsctl_argv += ['--', '--if-exists', 'del-br', bridge]
442
443             # configure_datapath() set up the underlying datapath bridge.
444             # Stack a VLAN bridge on top of it.
445             vsctl_argv += ['--', '--may-exist', 'add-br',
446                            bridge, dpname, pifrec['VLAN']]
447
448             vsctl_argv += set_br_external_ids(self._pif)
449
450         if ipdev != bridge:
451             vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
452             vsctl_argv += datapath_deconfigure_ipdev(ipdev)
453             vsctl_argv += ["# reconfigure ipdev %s" % ipdev]
454             vsctl_argv += ['--', 'add-port', bridge, ipdev]
455
456         if ipdev != dpname:
457             vsctl_argv += ['# configure Interface MAC']
458             vsctl_argv += ['--', 'set', 'Interface', pif_ipdev_name(self._pif),
459                            'MAC=%s' % vsctl_escape(dprec['MAC'])]
460
461         self._vsctl_argv = vsctl_argv
462         self._extra_ports = extra_ports
463
464     def bring_down_existing(self):
465         # interface-reconfigure is never explicitly called to down a
466         # bond master.  However, when we are called to up a slave it
467         # is implicit that we are destroying the master.  Conversely,
468         # when we are called to up a bond is is implicit that we are
469         # taking down the slaves.
470         #
471         # This is (only) important in the case where the device being
472         # implicitly taken down uses DHCP.  We need to kill the
473         # dhclient process, otherwise performing the inverse operation
474         # later later will fail because ifup will refuse to start a
475         # duplicate dhclient.
476         bond_masters = pif_get_bond_masters(self._pif)
477         for master in bond_masters:
478             log("action_up: bring down bond master %s" % (pif_netdev_name(master)))
479             run_command(["/sbin/ifdown", pif_bridge_name(master)])
480
481         bond_slaves = pif_get_bond_slaves(self._pif)
482         for slave in bond_slaves:
483             log("action_up: bring down bond slave %s" % (pif_netdev_name(slave)))
484             run_command(["/sbin/ifdown", pif_bridge_name(slave)])
485
486     def configure(self):
487         # Bring up physical devices. ovs-vswitchd initially enables or
488         # disables bond slaves based on whether carrier is detected
489         # when they are added, and a network device that is down
490         # always reports "no carrier".
491         physical_devices = datapath_get_physical_pifs(self._dp)
492         
493         for p in physical_devices:
494             prec = db().get_pif_record(p)
495             oc = prec['other_config']
496
497             dev = pif_netdev_name(p)
498
499             mtu = mtu_setting(prec['network'], "PIF", oc)
500
501             netdev_up(dev, mtu)
502
503             settings, offload = ethtool_settings(oc)
504             if len(settings):
505                 run_command(['/sbin/ethtool', '-s', dev] + settings)
506             if len(offload):
507                 run_command(['/sbin/ethtool', '-K', dev] + offload)
508
509         datapath_modify_config(self._vsctl_argv)
510
511     def post(self):
512         for p in self._extra_ports:
513             log("action_up: bring up %s" % p)
514             netdev_up(p)
515
516     def bring_down(self):
517         vsctl_argv = []
518
519         dp = self._dp
520         ipdev = self._ipdev
521         
522         bridge = pif_bridge_name(dp)
523
524         #nw = db().get_pif_record(self._pif)['network']
525         #nwrec = db().get_network_record(nw)
526         #vsctl_argv += ['# deconfigure network-uuids']
527         #vsctl_argv += ['--del-entry=bridge.%s.network-uuids=%s' % (bridge,nwrec['uuid'])]
528
529         log("deconfigure ipdev %s on %s" % (ipdev,bridge))
530         vsctl_argv += ["# deconfigure ipdev %s" % ipdev]
531         vsctl_argv += datapath_deconfigure_ipdev(ipdev)
532
533         if pif_is_vlan(self._pif):
534             # Delete the VLAN bridge.
535             vsctl_argv += deconfigure_bridge(self._pif)
536
537             # If the VLAN's slave is attached, leave datapath setup.
538             slave = pif_get_vlan_slave(self._pif)
539             if db().get_pif_record(slave)['currently_attached']:
540                 log("action_down: vlan slave is currently attached")
541                 dp = None
542
543             # If the VLAN's slave has other VLANs that are attached, leave datapath setup.
544             for master in pif_get_vlan_masters(slave):
545                 if master != self._pif and db().get_pif_record(master)['currently_attached']:
546                     log("action_down: vlan slave has other master: %s" % pif_netdev_name(master))
547                     dp = None
548
549             # Otherwise, take down the datapath too (fall through)
550             if dp:
551                 log("action_down: no more masters, bring down slave %s" % bridge)
552         else:
553             # Stop here if this PIF has attached VLAN masters.
554             masters = [db().get_pif_record(m)['VLAN'] for m in pif_get_vlan_masters(self._pif) if db().get_pif_record(m)['currently_attached']]
555             if len(masters) > 0:
556                 log("Leaving datapath %s up due to currently attached VLAN masters %s" % (bridge, masters))
557                 dp = None
558
559         if dp:
560             vsctl_argv += deconfigure_bridge(dp)
561
562             physical_devices = [pif_netdev_name(p) for p in datapath_get_physical_pifs(dp)]
563
564             log("action_down: bring down physical devices - %s" % physical_devices)
565         
566             for p in physical_devices:
567                 netdev_down(p)
568
569         datapath_modify_config(vsctl_argv)