1
0
mirror of https://github.com/CumulusNetworks/ifupdown2.git synced 2024-05-06 15:54:50 +00:00

addons: batman_adv: cleanup according to PEP8

Signed-off-by: Markus Hauschild <markus@moepman.eu>
This commit is contained in:
Markus Hauschild
2020-11-17 01:00:24 +01:00
parent e40c309ff3
commit 1d9a8d4f6b

View File

@@ -22,10 +22,9 @@ except (ImportError, ModuleNotFoundError):
from ifupdown.exceptions import moduleNotSupported from ifupdown.exceptions import moduleNotSupported
import ifupdown.ifupdownflags as ifupdownflags import ifupdown.ifupdownflags as ifupdownflags
import logging import os
import re import re
import subprocess import subprocess
import os
class batman_adv(Addon, moduleBase): class batman_adv(Addon, moduleBase):
@@ -84,55 +83,55 @@ class batman_adv(Addon, moduleBase):
_batman_attrs = { _batman_attrs = {
} }
def __init__ (self, *args, **kargs): def __init__(self, *args, **kargs):
Addon.__init__(self) Addon.__init__(self)
moduleBase.__init__ (self, *args, **kargs) moduleBase.__init__(self, *args, **kargs)
if not os.path.exists('/usr/sbin/batctl'): if not os.path.exists('/usr/sbin/batctl'):
raise moduleNotSupported('module init failed: no /usr/sbin/batctl found') raise moduleNotSupported('module init failed: no /usr/sbin/batctl found')
for longname, entry in self._modinfo['attrs'].items (): for longname, entry in self._modinfo['attrs'].items():
if entry.get ('batman-attr', False) == False: if entry.get('batman-attr', False) == False:
continue continue
attr = longname.replace ("batman-", "") attr = longname.replace("batman-", "")
self._batman_attrs[attr] = { self._batman_attrs[attr] = {
'filename' : attr.replace ("-", "_"), 'filename': attr.replace("-", "_"),
} }
def _is_batman_device (self, ifaceobj): def _is_batman_device(self, ifaceobj):
if ifaceobj.get_attr_value_first ('batman-ifaces'): if ifaceobj.get_attr_value_first('batman-ifaces'):
return True return True
return False return False
def _get_batman_ifaces (self, ifaceobj ): def _get_batman_ifaces(self, ifaceobj):
batman_ifaces = ifaceobj.get_attr_value_first ('batman-ifaces') batman_ifaces = ifaceobj.get_attr_value_first('batman-ifaces')
if batman_ifaces: if batman_ifaces:
return sorted (batman_ifaces.split ()) return sorted(batman_ifaces.split())
return None return None
def _get_batman_ifaces_ignore_regex (self, ifaceobj): def _get_batman_ifaces_ignore_regex(self, ifaceobj):
ifaces_ignore_regex = ifaceobj.get_attr_value_first ('batman-ifaces-ignore-regex') ifaces_ignore_regex = ifaceobj.get_attr_value_first('batman-ifaces-ignore-regex')
if ifaces_ignore_regex: if ifaces_ignore_regex:
return re.compile (r"%s" % ifaces_ignore_regex) return re.compile(r"%s" % ifaces_ignore_regex)
return None return None
def _get_batman_attr (self, ifaceobj, attr): def _get_batman_attr(self, ifaceobj, attr):
if attr not in self._batman_attrs: if attr not in self._batman_attrs:
raise ValueError ("_get_batman_attr: Invalid or unsupported B.A.T.M.A.N. adv. attribute: %s" % attr) raise ValueError("_get_batman_attr: Invalid or unsupported B.A.T.M.A.N. adv. attribute: %s" % attr)
value = ifaceobj.get_attr_value_first ('batman-%s' % attr) value = ifaceobj.get_attr_value_first('batman-%s' % attr)
if value: if value:
return value return value
return None return None
def _read_current_batman_attr (self, ifaceobj, attr, dont_map = False): def _read_current_batman_attr(self, ifaceobj, attr, dont_map=False):
# 'routing_algo' needs special handling, D'oh. # 'routing_algo' needs special handling, D'oh.
if dont_map: if dont_map:
attr_file_path = "/sys/class/net/%s/mesh/%s" % (ifaceobj.name, attr) attr_file_path = "/sys/class/net/%s/mesh/%s" % (ifaceobj.name, attr)
else: else:
if attr not in self._batman_attrs: if attr not in self._batman_attrs:
raise ValueError ("_read_current_batman_attr: Invalid or unsupported B.A.T.M.A.N. adv. attribute: %s" % attr) raise ValueError("_read_current_batman_attr: Invalid or unsupported B.A.T.M.A.N. adv. attribute: %s" % attr)
attr_file_name = self._batman_attrs[attr]['filename'] attr_file_name = self._batman_attrs[attr]['filename']
attr_file_path = "/sys/class/net/%s/mesh/%s" % (ifaceobj.name, attr_file_name) attr_file_path = "/sys/class/net/%s/mesh/%s" % (ifaceobj.name, attr_file_name)
@@ -140,140 +139,138 @@ class batman_adv(Addon, moduleBase):
try: try:
return self.read_file_oneline(attr_file_path) return self.read_file_oneline(attr_file_path)
except IOError as i: except IOError as i:
raise Exception ("_read_current_batman_attr (%s) %s" % (attr, i)) raise Exception("_read_current_batman_attr (%s) %s" % (attr, i))
except ValueError: except ValueError:
raise Exception ("_read_current_batman_attr: Integer value expected, got: %s" % value) raise Exception("_read_current_batman_attr: Integer value expected, got: %s" % value)
def _set_batman_attr (self, ifaceobj, attr, value): def _set_batman_attr(self, ifaceobj, attr, value):
if attr not in self._batman_attrs: if attr not in self._batman_attrs:
raise ValueError ("_set_batman_attr: Invalid or unsupported B.A.T.M.A.N. adv. attribute: %s" % attr) raise ValueError("_set_batman_attr: Invalid or unsupported B.A.T.M.A.N. adv. attribute: %s" % attr)
attr_file_name = self._batman_attrs[attr]['filename'] attr_file_name = self._batman_attrs[attr]['filename']
attr_file_path = "/sys/class/net/%s/mesh/%s" % (ifaceobj.name, attr_file_name) attr_file_path = "/sys/class/net/%s/mesh/%s" % (ifaceobj.name, attr_file_name)
try: try:
self.write_file(attr_file_path, "%s\n" % value) self.write_file(attr_file_path, "%s\n" % value)
except IOError as i: except IOError as i:
raise Exception ("_set_batman_attr (%s): %s" % (attr, i)) raise Exception("_set_batman_attr (%s): %s" % (attr, i))
def _batctl_if (self, bat_iface, mesh_iface, op): def _batctl_if(self, bat_iface, mesh_iface, op):
if op not in [ 'add', 'del' ]: if op not in ['add', 'del']:
raise Exception ("_batctl_if() called with invalid \"op\" value: %s" % op) raise Exception("_batctl_if() called with invalid \"op\" value: %s" % op)
try: try:
self.logger.debug ("Running batctl -m %s if %s %s" % (bat_iface, op, mesh_iface)) self.logger.debug("Running batctl -m %s if %s %s" % (bat_iface, op, mesh_iface))
utils.exec_commandl(["batctl", "-m", bat_iface, "if", op, mesh_iface]) utils.exec_commandl(["batctl", "-m", bat_iface, "if", op, mesh_iface])
except subprocess.CalledProcessError as c: except subprocess.CalledProcessError as c:
raise Exception ("Command \"batctl -m %s if %s %s\" failed: %s" % (bat_iface, op, mesh_iface, c.output)) raise Exception("Command \"batctl -m %s if %s %s\" failed: %s" % (bat_iface, op, mesh_iface, c.output))
except Exception as e: except Exception as e:
raise Exception ("_batctl_if: %s" % e) raise Exception("_batctl_if: %s" % e)
def _set_routing_algo (self, routing_algo): def _set_routing_algo(self, routing_algo):
if routing_algo not in ['BATMAN_IV', 'BATMAN_V']: if routing_algo not in ['BATMAN_IV', 'BATMAN_V']:
raise Exception ("_set_routing_algo() called with invalid \"routing_algo\" value: %s" % routing_algo) raise Exception("_set_routing_algo() called with invalid \"routing_algo\" value: %s" % routing_algo)
try: try:
self.logger.debug ("Running batctl ra %s" % routing_algo) self.logger.debug("Running batctl ra %s" % routing_algo)
batctl_output = subprocess.check_output (["batctl", "ra", routing_algo], stderr = subprocess.STDOUT) batctl_output = subprocess.check_output(["batctl", "ra", routing_algo], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as c: except subprocess.CalledProcessError as c:
raise Exception ("Command \"batctl ra %s\" failed: %s" % (routing_algo, c.output)) raise Exception("Command \"batctl ra %s\" failed: %s" % (routing_algo, c.output))
except Exception as e: except Exception as e:
raise Exception ("_set_routing_algo: %s" % e) raise Exception("_set_routing_algo: %s" % e)
def _find_member_ifaces (self, ifaceobj, ignore = True): def _find_member_ifaces(self, ifaceobj, ignore=True):
members = [] members = []
iface_ignore_re = self._get_batman_ifaces_ignore_regex (ifaceobj) iface_ignore_re = self._get_batman_ifaces_ignore_regex(ifaceobj)
self.logger.info("batman: executing: %s" % " ".join(["batctl", "-m", ifaceobj.name, "if"])) self.logger.info("batman: executing: %s" % " ".join(["batctl", "-m", ifaceobj.name, "if"]))
batctl_fh = subprocess.Popen (["batctl", "-m", ifaceobj.name, "if"], bufsize = 4194304, stdout = subprocess.PIPE, universal_newlines = True).stdout batctl_fh = subprocess.Popen(["batctl", "-m", ifaceobj.name, "if"], bufsize=4194304, stdout=subprocess.PIPE, universal_newlines=True).stdout
for line in batctl_fh.readlines (): for line in batctl_fh.readlines():
iface = line.split (':')[0] iface = line.split(':')[0]
if iface_ignore_re and iface_ignore_re.match (iface) and ignore: if iface_ignore_re and iface_ignore_re.match(iface) and ignore:
continue continue
members.append (iface) members.append(iface)
return sorted (members) return sorted(members)
def get_dependent_ifacenames (self, ifaceobj, ifaceobjs_all=None): def get_dependent_ifacenames(self, ifaceobj, ifaceobjs_all=None):
if not self._is_batman_device (ifaceobj): if not self._is_batman_device(ifaceobj):
return None return None
ifaceobj.link_kind |= ifaceLinkKind.BATMAN_ADV ifaceobj.link_kind |= ifaceLinkKind.BATMAN_ADV
batman_ifaces = self._get_batman_ifaces (ifaceobj) batman_ifaces = self._get_batman_ifaces(ifaceobj)
if batman_ifaces: if batman_ifaces:
return batman_ifaces return batman_ifaces
return [None] return [None]
def _up (self, ifaceobj): def _up(self, ifaceobj):
if self._get_batman_ifaces (ifaceobj) == None: if self._get_batman_ifaces(ifaceobj) == None:
raise Exception ('could not determine batman interfacaes') raise Exception('could not determine batman interfacaes')
# Verify existance of batman interfaces (should be present already) # Verify existance of batman interfaces (should be present already)
batman_ifaces = [] batman_ifaces = []
for iface in self._get_batman_ifaces (ifaceobj): for iface in self._get_batman_ifaces(ifaceobj):
if not self.cache.link_exists (iface): if not self.cache.link_exists(iface):
self.logger.warn ('batman iface %s not present' % iface) self.logger.warn('batman iface %s not present' % iface)
continue continue
batman_ifaces.append (iface) batman_ifaces.append(iface)
if len (batman_ifaces) == 0: if len(batman_ifaces) == 0:
raise Exception ("None of the configured batman interfaces are available!") raise Exception("None of the configured batman interfaces are available!")
routing_algo = ifaceobj.get_attr_value_first ('batman-routing-algo') routing_algo = ifaceobj.get_attr_value_first('batman-routing-algo')
if routing_algo: if routing_algo:
self._set_routing_algo (routing_algo) self._set_routing_algo(routing_algo)
if_ignore_re = self._get_batman_ifaces_ignore_regex (ifaceobj) if_ignore_re = self._get_batman_ifaces_ignore_regex(ifaceobj)
# Is the batman main interface already present? # Is the batman main interface already present?
if self.cache.link_exists (ifaceobj.name): if self.cache.link_exists(ifaceobj.name):
# Verify which member interfaces are present # Verify which member interfaces are present
members = self._find_member_ifaces (ifaceobj) members = self._find_member_ifaces(ifaceobj)
for iface in members: for iface in members:
if iface not in batman_ifaces: if iface not in batman_ifaces:
self._batctl_if (ifaceobj.name, iface, 'del') self._batctl_if(ifaceobj.name, iface, 'del')
for iface in batman_ifaces: for iface in batman_ifaces:
if iface not in members: if iface not in members:
self._batctl_if (ifaceobj.name, iface, 'add') self._batctl_if(ifaceobj.name, iface, 'add')
# Batman interfaces no present, add member interfaces to create it # Batman interfaces no present, add member interfaces to create it
else: else:
for iface in batman_ifaces: for iface in batman_ifaces:
self._batctl_if (ifaceobj.name, iface, 'add') self._batctl_if(ifaceobj.name, iface, 'add')
# Check/set any B.A.T.M.A.N. adv. set within interface configuration # Check/set any B.A.T.M.A.N. adv. set within interface configuration
for attr in self._batman_attrs: for attr in self._batman_attrs:
value_cfg = self._get_batman_attr (ifaceobj, attr) value_cfg = self._get_batman_attr(ifaceobj, attr)
if value_cfg and value_cfg != self._read_current_batman_attr (ifaceobj, attr): if value_cfg and value_cfg != self._read_current_batman_attr(ifaceobj, attr):
self._set_batman_attr (ifaceobj, attr, value_cfg) self._set_batman_attr(ifaceobj, attr, value_cfg)
if ifaceobj.addr_method == 'manual': if ifaceobj.addr_method == 'manual':
netlink.link_set_updown(ifaceobj.name, "up") netlink.link_set_updown(ifaceobj.name, "up")
def _down(self, ifaceobj):
def _down (self, ifaceobj): if not ifupdownflags.flags.PERFMODE and not self.cache.link_exists(ifaceobj.name):
if not ifupdownflags.flags.PERFMODE and not self.cache.link_exists (ifaceobj.name):
return return
members = self._find_member_ifaces (ifaceobj) members = self._find_member_ifaces(ifaceobj)
for iface in members: for iface in members:
self._batctl_if (ifaceobj.name, iface, 'del') self._batctl_if(ifaceobj.name, iface, 'del')
# The main interface will automagically vanish after the last member # The main interface will automagically vanish after the last member
# interface has been deleted. # interface has been deleted.
def _query_check(self, ifaceobj, ifaceobjcurr):
def _query_check (self, ifaceobj, ifaceobjcurr): if not self.cache.link_exists(ifaceobj.name):
if not self.cache.link_exists (ifaceobj.name):
return return
batman_ifaces_cfg = self._get_batman_ifaces (ifaceobj) batman_ifaces_cfg = self._get_batman_ifaces(ifaceobj)
batman_ifaces_real = self._find_member_ifaces (ifaceobj, False) batman_ifaces_real = self._find_member_ifaces(ifaceobj, False)
# Produce list of all current interfaces, tag interfaces ignored by # Produce list of all current interfaces, tag interfaces ignored by
# regex with () around the iface name. # regex with () around the iface name.
batman_ifaces_real_tagged = [] batman_ifaces_real_tagged = []
iface_ignore_re_str = ifaceobj.get_attr_value_first ('batman-ifaces-ignore-regex') iface_ignore_re_str = ifaceobj.get_attr_value_first('batman-ifaces-ignore-regex')
iface_ignore_re = self._get_batman_ifaces_ignore_regex (ifaceobj) iface_ignore_re = self._get_batman_ifaces_ignore_regex(ifaceobj)
# Assume everything's fine and wait for reality to prove us otherwise # Assume everything's fine and wait for reality to prove us otherwise
ifaces_ok = 0 ifaces_ok = 0
@@ -286,22 +283,22 @@ class batman_adv(Addon, moduleBase):
# Interfaces active but not configured (or ignored)? # Interfaces active but not configured (or ignored)?
for iface in batman_ifaces_real: for iface in batman_ifaces_real:
if iface not in batman_ifaces_cfg: if iface not in batman_ifaces_cfg:
if iface_ignore_re and iface_ignore_re.match (iface): if iface_ignore_re and iface_ignore_re.match(iface):
batman_ifaces_real_tagged.append ("(%s)" % iface) batman_ifaces_real_tagged.append("(%s)" % iface)
continue continue
ifaces_ok = 1 ifaces_ok = 1
else: else:
batman_ifaces_real_tagged.append (iface) batman_ifaces_real_tagged.append(iface)
# Produce sorted list of active and ignored interfaces # Produce sorted list of active and ignored interfaces
ifaces_str = " ".join (batman_ifaces_real_tagged) ifaces_str = " ".join(batman_ifaces_real_tagged)
ifaceobjcurr.update_config_with_status ('batman-ifaces', ifaces_str, ifaces_ok) ifaceobjcurr.update_config_with_status('batman-ifaces', ifaces_str, ifaces_ok)
ifaceobjcurr.update_config_with_status ('batman-ifaces-ignore-regex', iface_ignore_re_str, 0) ifaceobjcurr.update_config_with_status('batman-ifaces-ignore-regex', iface_ignore_re_str, 0)
# Check any B.A.T.M.A.N. adv. set within interface configuration # Check any B.A.T.M.A.N. adv. set within interface configuration
for attr in self._batman_attrs: for attr in self._batman_attrs:
value_cfg = self._get_batman_attr (ifaceobj, attr) value_cfg = self._get_batman_attr(ifaceobj, attr)
value_curr = self._read_current_batman_attr (ifaceobj, attr) value_curr = self._read_current_batman_attr(ifaceobj, attr)
# Ignore this attribute if its'nt configured for this interface # Ignore this attribute if its'nt configured for this interface
if not value_cfg: if not value_cfg:
@@ -311,17 +308,17 @@ class batman_adv(Addon, moduleBase):
if value_cfg != value_curr: if value_cfg != value_curr:
value_ok = 1 value_ok = 1
ifaceobjcurr.update_config_with_status ('batman-%s' % attr, value_curr, value_ok) ifaceobjcurr.update_config_with_status('batman-%s' % attr, value_curr, value_ok)
routing_algo = ifaceobj.get_attr_value_first ('batman-routing-algo') routing_algo = ifaceobj.get_attr_value_first('batman-routing-algo')
if routing_algo: if routing_algo:
value_curr = self._read_current_batman_attr (ifaceobj, "routing_algo", dont_map = True) value_curr = self._read_current_batman_attr(ifaceobj, "routing_algo", dont_map=True)
value_ok = 0 value_ok = 0
if routing_algo != value_curr: if routing_algo != value_curr:
value_ok = 1 value_ok = 1
ifaceobjcurr.update_config_with_status ('batman-routing-algo', value_curr, value_ok) ifaceobjcurr.update_config_with_status('batman-routing-algo', value_curr, value_ok)
_run_ops = { _run_ops = {
'pre-up': _up, 'pre-up': _up,
@@ -329,11 +326,11 @@ class batman_adv(Addon, moduleBase):
'query-checkcurr': _query_check 'query-checkcurr': _query_check
} }
def get_ops (self): def get_ops(self):
""" returns list of ops supported by this module """ """ returns list of ops supported by this module """
return self._run_ops.keys () return self._run_ops.keys()
def run (self, ifaceobj, operation, query_ifaceobj = None, **extra_args): def run(self, ifaceobj, operation, query_ifaceobj=None, **extra_args):
""" run B.A.T.M.A.N. configuration on the interface object passed as argument """ run B.A.T.M.A.N. configuration on the interface object passed as argument
Args: Args:
@@ -349,14 +346,14 @@ class batman_adv(Addon, moduleBase):
of interfaces. status is success if the running state is same of interfaces. status is success if the running state is same
as user required state in ifaceobj. error otherwise. as user required state in ifaceobj. error otherwise.
""" """
op_handler = self._run_ops.get (operation) op_handler = self._run_ops.get(operation)
if not op_handler: if not op_handler:
return return
if (operation != 'query-running' and not self._is_batman_device (ifaceobj)): if (operation != 'query-running' and not self._is_batman_device(ifaceobj)):
return return
if operation == 'query-checkcurr': if operation == 'query-checkcurr':
op_handler (self, ifaceobj, query_ifaceobj) op_handler(self, ifaceobj, query_ifaceobj)
else: else:
op_handler (self, ifaceobj) op_handler(self, ifaceobj)