def is_process_running(self, procName): try: utils.exec_command('%s -x %s' % (utils.pidof_cmd, procName)) except: return False else: return True
def _rule_cache_fill(self): ip_rules = utils.exec_command('%s rule show' %utils.ip_cmd).splitlines() self.ip_rule_cache = [' '.join(r.split()) for r in ip_rules] self.l3mdev4_rule = self._l3mdev_rule(self.ip_rule_cache) ip_rules = utils.exec_command('%s -6 rule show' %utils.ip_cmd).splitlines() self.ip6_rule_cache = [' '.join(r.split()) for r in ip_rules] self.l3mdev6_rule = self._l3mdev_rule(self.ip6_rule_cache)
def _down_vrf_helper(self, ifaceobj, vrf_table): mode = "" if ifupdownflags.flags.PERFMODE: mode = "boot" if self.vrf_helper: utils.exec_command('%s delete %s %s %s' % (self.vrf_helper, ifaceobj.name, vrf_table, mode))
def __init__(self, *args, **kargs): moduleBase.__init__(self, *args, **kargs) self.ipcmd = None self.bondcmd = None if not os.path.exists('/sys/class/net/bonding_masters'): try: utils.exec_command('modprobe -q bonding') except Exception as e: self.logger.info("bond: error while loading bonding module: %s" % str(e))
def _close_sockets(self, ifaceobj, ifindex): if not self.vrf_close_socks_on_down: return try: utils.exec_command('%s -aK \"dev == %s\"' %(utils.ss_cmd, ifindex)) except Exception, e: self.logger.info('%s: closing socks using ss' ' failed (%s)\n' %(ifaceobj.name, str(e))) pass
def _down(self, ifaceobj): """ down ifplugd -k -i $IFACE down kill $(cat /var/run/vrrpd_$IFACE_*.pid) """ attrval = ifaceobj.get_attr_value_first('vrrp-id') if not attrval: return try: utils.exec_command('%s -k -i %s' % (utils.ifplugd_cmd, ifaceobj.name)) except Exception, e: self.logger.debug('%s: ifplugd down error (%s)' %(ifaceobj.name, str(e))) pass
def _del_vrf_rules(self, vrf_dev_name, vrf_table): pref = 200 ip_rule_out_format = '%s: from all %s %s lookup %s' ip_rule_cmd = '%s %s rule del pref %s %s %s table %s' rule = ip_rule_out_format %(pref, 'oif', vrf_dev_name, vrf_dev_name) if rule in self.ip_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '', pref, 'oif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd) rule = ip_rule_out_format %(pref, 'iif', vrf_dev_name, vrf_dev_name) if rule in self.ip_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '', pref, 'iif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd) rule = ip_rule_out_format %(pref, 'oif', vrf_dev_name, vrf_dev_name) if rule in self.ip6_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '-6', pref, 'oif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd) rule = ip_rule_out_format %(pref, 'iif', vrf_dev_name, vrf_dev_name) if rule in self.ip6_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '-6', pref, 'iif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd)
def _add_vrf_rules(self, vrf_dev_name, vrf_table): pref = 200 ip_rule_out_format = '%s: from all %s %s lookup %s' ip_rule_cmd = '%s %s rule add pref %s %s %s table %s' if self.vrf_fix_local_table: self.vrf_fix_local_table = False rule = '0: from all lookup local' if rule in self.ip_rule_cache: try: utils.exec_command('%s rule del pref 0' %utils.ip_cmd) utils.exec_command('%s rule add pref 32765 table local' %utils.ip_cmd) except Exception, e: self.logger.info('%s: %s' % (vrf_dev_name, str(e))) pass if rule in self.ip6_rule_cache: try: utils.exec_command('%s -6 rule del pref 0' %utils.ip_cmd) utils.exec_command('%s -6 rule add pref 32765 table local' %utils.ip_cmd) except Exception, e: self.logger.info('%s: %s' % (vrf_dev_name, str(e))) pass
def sysctl_get(self, variable): """ get value of sysctl variable """ output = utils.exec_command('%s %s' % (utils.sysctl_cmd, variable)) split = output.split('=') if len(split) > 1: return split[1].strip() return None
def _query_check_vrf_dev(self, ifaceobj, ifaceobjcurr, vrf_table): try: if not self.ipcmd.link_exists(ifaceobj.name): self.logger.info('%s: vrf: does not exist' %(ifaceobj.name)) return if vrf_table == 'auto': config_table = self._get_iproute2_vrf_table(ifaceobj.name) else: config_table = vrf_table vrfdev_attrs = self.ipcmd.link_get_linkinfo_attrs(ifaceobj.name) if not vrfdev_attrs: ifaceobjcurr.update_config_with_status('vrf-table', 'None', 1) return running_table = vrfdev_attrs.get('table') if not running_table: ifaceobjcurr.update_config_with_status('vrf-table', 'None', 1) return if config_table != running_table: ifaceobjcurr.update_config_with_status('vrf-table', running_table, 1) else: ifaceobjcurr.update_config_with_status('vrf-table', running_table, 0) if not ifupdownflags.flags.WITHDEFAULTS: return if self.vrf_helper: try: utils.exec_command('%s verify %s %s' %(self.vrf_helper, ifaceobj.name, config_table)) ifaceobjcurr.update_config_with_status('vrf-helper', '%s create %s %s' %(self.vrf_helper, ifaceobj.name, config_table), 0) except Exception, e: ifaceobjcurr.update_config_with_status('vrf-helper', '%s create %s %s' %(self.vrf_helper, ifaceobj.name, config_table), 1) pass except Exception, e: self.log_warn(str(e))
def is_service_running(cls, procname=None, pidfile=None): utilsobj = utilsBase() if pidfile: if os.path.exists(pidfile): pid = utilsobj.read_file_oneline(pidfile) if not os.path.exists('/proc/%s' %pid): return False else: return False return True if procname: try: utils.exec_command('%s %s' % (utils.pidof_cmd, procname)) except: return False else: return True return False
def _get_reserved_vlan_range(self): start = end = 0 get_resvvlan = '/var/lib/ifupdown2/hooks/get_reserved_vlan_range.sh' if not os.path.exists(get_resvvlan): return (start, end) try: (s, e) = utils.exec_command(get_resvvlan).strip('\n').split('-') start = int(s) end = int(e) except Exception, e: self.logger.debug('%s failed (%s)' %(get_resvvlan, str(e))) # ignore errors pass
def _up(self, ifaceobj): """ up vrrpd -n -D -i $IFACE -v 1 -p 20 10.0.1.254 up ifplugd -i $IFACE -b -f -u0 -d1 -I -p -q """ if (not ifupdownflags.flags.DRYRUN and not os.path.exists('/sys/class/net/%s' %ifaceobj.name)): return cmd = '' attrval = ifaceobj.get_attr_value_first('vrrp-id') if attrval: cmd += ' -v %s' %attrval else: return attrval = ifaceobj.get_attr_value_first('vrrp-priority') if attrval: cmd += ' -p %s' %attrval else: self.logger.warn('%s: incomplete vrrp parameters ' %ifaceobj.name, '(priority not found)') attrval = ifaceobj.get_attr_value_first('vrrp-virtual-ip') if attrval: cmd += ' %s' %attrval else: self.logger.warn('%s: incomplete vrrp arguments ' %ifaceobj.name, '(virtual ip not found)') return cmd = ('%s -n -D -i %s %s' % (utils.vrrpd_cmd, ifaceobj.name, cmd)) utils.exec_command(cmd) cmd = ('%s -i %s -b -f -u0 -d1 -I -p -q' % (utils.ifplugd_cmd, ifaceobj.name)) if self._check_if_process_is_running(utils.ifplugd_cmd, cmd): self.logger.info('%s: ifplugd already running' %ifaceobj.name) return utils.exec_command(cmd)
def __execute_or_batch(self, prefix, cmd): if self.__batch_mode: self.__add_to_batch(prefix, cmd) else: utils.exec_command("%s %s" % (prefix, cmd))
def sysctl_set(self, variable, value): """ set sysctl variable to value passed as argument """ utils.exec_command('%s %s=%s' % (utils.sysctl_cmd, variable, value))
def run_iface_op(cls, ifupdownobj, ifaceobj, op, cenv=None): """ Runs sub operation on an interface """ ifacename = ifaceobj.name if ifupdownobj.type and ifupdownobj.type != ifaceobj.type: return if not ifupdownobj.flags.ADDONS_ENABLE: return if op == 'query-checkcurr': query_ifaceobj=ifupdownobj.create_n_save_ifaceobjcurr(ifaceobj) # If not type bridge vlan and the object does not exist, # mark not found and return if (not ifupdownobj.link_exists(ifaceobj.name) and ifaceobj.type != ifaceType.BRIDGE_VLAN): query_ifaceobj.set_state_n_status(ifaceState.from_str(op), ifaceStatus.NOTFOUND) return for mname in ifupdownobj.module_ops.get(op): m = ifupdownobj.modules.get(mname) err = 0 try: if hasattr(m, 'run'): msg = ('%s: %s : running module %s' %(ifacename, op, mname)) if op == 'query-checkcurr': # Dont check curr if the interface object was # auto generated if (ifaceobj.priv_flags and ifaceobj.priv_flags.NOCONFIG): continue ifupdownobj.logger.debug(msg) m.run(ifaceobj, op, query_ifaceobj, ifaceobj_getfunc=ifupdownobj.get_ifaceobjs) else: ifupdownobj.logger.debug(msg) m.run(ifaceobj, op, ifaceobj_getfunc=ifupdownobj.get_ifaceobjs) except Exception as e: if not ifupdownobj.ignore_error(str(e)): err = 1 #import traceback #traceback.print_exc() ifupdownobj.logger.error(str(e)) # Continue with rest of the modules pass finally: if err or ifaceobj.status == ifaceStatus.ERROR: ifaceobj.set_state_n_status(ifaceState.from_str(op), ifaceStatus.ERROR) if 'up' in op or 'down' in op or 'query-checkcurr' in op: cls.set_sched_status(False) else: # Mark success only if the interface was not already # marked with error status = (ifaceobj.status if ifaceobj.status == ifaceStatus.ERROR else ifaceStatus.SUCCESS) ifaceobj.set_state_n_status(ifaceState.from_str(op), status) if ifupdownobj.config.get('addon_scripts_support', '0') == '1': # execute /etc/network/ scripts os.environ['IFACE'] = ifaceobj.name if ifaceobj.name else '' os.environ['LOGICAL'] = ifaceobj.name if ifaceobj.name else '' os.environ['METHOD'] = ifaceobj.addr_method if ifaceobj.addr_method else '' os.environ['ADDRFAM'] = ','.join(ifaceobj.addr_family) if ifaceobj.addr_family else '' for mname in ifupdownobj.script_ops.get(op, []): ifupdownobj.logger.debug('%s: %s : running script %s' %(ifacename, op, mname)) try: utils.exec_command(mname, env=cenv) except Exception as e: if "permission denied" in str(e).lower(): ifupdownobj.logger.warning('%s: %s %s' % (ifacename, op, str(e))) else: ifupdownobj.log_error('%s: %s %s' % (ifacename, op, str(e)))
def _up(self, ifaceobj): # if dhclient is already running do not stop and start it dhclient4_running = self.dhclientcmd.is_running(ifaceobj.name) dhclient6_running = self.dhclientcmd.is_running6(ifaceobj.name) # today if we have an interface with both inet and inet6, if we # remove the inet or inet6 or both then execute ifreload, we need # to release/kill the appropriate dhclient(4/6) if they are running self._down_stale_dhcp_config(ifaceobj, 'inet', dhclient4_running) self._down_stale_dhcp_config(ifaceobj, 'inet6', dhclient6_running) if ifaceobj.link_privflags & ifaceLinkPrivFlags.KEEP_LINK_DOWN: self.logger.info("%s: skipping dhcp configuration: link-down yes" % ifaceobj.name) return try: dhclient_cmd_prefix = None dhcp_wait = policymanager.policymanager_api.get_attr_default( module_name=self.__class__.__name__, attr='dhcp-wait') wait = not str(dhcp_wait).lower() == "no" dhcp6_ll_wait = policymanager.policymanager_api.get_iface_default(module_name=self.__class__.__name__, \ ifname=ifaceobj.name, attr='dhcp6-ll-wait') try: timeout = int(dhcp6_ll_wait) + 1 except Exception: timeout = 10 pass dhcp6_duid = policymanager.policymanager_api.get_iface_default(module_name=self.__class__.__name__, \ ifname=ifaceobj.name, attr='dhcp6-duid') vrf = ifaceobj.get_attr_value_first('vrf') if (vrf and self.vrf_exec_cmd_prefix and self.cache.link_exists(vrf)): dhclient_cmd_prefix = '%s %s' % (self.vrf_exec_cmd_prefix, vrf) elif self.mgmt_vrf_context: dhclient_cmd_prefix = '%s %s' % (self.vrf_exec_cmd_prefix, 'default') self.logger.info( 'detected mgmt vrf context starting dhclient in default vrf context' ) if 'inet' in ifaceobj.addr_family: if dhclient4_running: self.logger.info('dhclient4 already running on %s. ' 'Not restarting.' % ifaceobj.name) else: # First release any existing dhclient processes try: if not ifupdownflags.flags.PERFMODE: self.dhclientcmd.stop(ifaceobj.name) except Exception: pass self.dhclient_start_and_check( ifaceobj.name, "inet", self.dhclientcmd.start, wait=wait, cmd_prefix=dhclient_cmd_prefix) if 'inet6' in ifaceobj.addr_family: if dhclient6_running: self.logger.info('dhclient6 already running on %s. ' 'Not restarting.' % ifaceobj.name) else: accept_ra = ifaceobj.get_attr_value_first('accept_ra') if accept_ra: # XXX: Validate value self.sysctl_set( 'net.ipv6.conf.%s' % ifaceobj.name + '.accept_ra', accept_ra) autoconf = ifaceobj.get_attr_value_first('autoconf') if autoconf: # XXX: Validate value self.sysctl_set( 'net.ipv6.conf.%s' % ifaceobj.name + '.autoconf', autoconf) try: self.dhclientcmd.stop6(ifaceobj.name, duid=dhcp6_duid) except Exception: pass #add delay before starting IPv6 dhclient to #make sure the configured interface/link is up. if timeout > 1: time.sleep(1) while timeout: addr_output = utils.exec_command( '%s -6 addr show %s' % (utils.ip_cmd, ifaceobj.name)) r = re.search('inet6 .* scope link', addr_output) if r: self.dhclientcmd.start6( ifaceobj.name, wait=wait, cmd_prefix=dhclient_cmd_prefix, duid=dhcp6_duid) return timeout -= 1 if timeout: time.sleep(1) except Exception as e: self.logger.error("%s: %s" % (ifaceobj.name, str(e))) ifaceobj.set_status(ifaceStatus.ERROR)
def __init__(self, *args, **kargs): Addon.__init__(self) moduleBase.__init__(self, *args, **kargs) self.dhclientcmd = None self.name = self.__class__.__name__ self.vrf_mgmt_devname = policymanager.policymanager_api.get_module_globals( module_name=self.__class__.__name__, attr="vrf-mgmt-devname") self.at_exit = False self.user_reserved_vrf_table = [] if (ifupdownflags.flags.PERFMODE and not (self.vrf_mgmt_devname and os.path.exists( '/sys/class/net/%s' % self.vrf_mgmt_devname))): # if perf mode is set (PERFMODE is set at boot), and this is the first # time we are calling ifup at boot (check for mgmt vrf existance at # boot, make sure this is really the first invocation at boot. # ifup is called with PERFMODE at boot multiple times (once for mgmt vrf # and the second time with all auto interfaces). We want to delete # the map file only the first time. This is to avoid accidently # deleting map file with a valid mgmt vrf entry if os.path.exists(self.iproute2_vrf_filename): try: self.logger.info('vrf: removing file %s' % self.iproute2_vrf_filename) os.remove(self.iproute2_vrf_filename) except Exception as e: self.logger.debug('vrf: removing file failed (%s)' % str(e)) try: ip_rules = utils.exec_command('%s rule show' % utils.ip_cmd).splitlines() self.ip_rule_cache = [' '.join(r.split()) for r in ip_rules] except Exception as e: self.ip_rule_cache = [] self.logger.warning('vrf: cache v4: %s' % str(e)) try: ip_rules = utils.exec_command('%s -6 rule show' % utils.ip_cmd).splitlines() self.ip6_rule_cache = [' '.join(r.split()) for r in ip_rules] except Exception as e: self.ip6_rule_cache = [] self.logger.warning('vrf: cache v6: %s' % str(e)) #self.logger.debug("vrf: ip rule cache") #self.logger.info(self.ip_rule_cache) #self.logger.info("vrf: ip -6 rule cache") #self.logger.info(self.ip6_rule_cache) self.l3mdev_checked = False self.l3mdev4_rule = False if self._l3mdev_rule(self.ip_rule_cache): self.l3mdev4_rule = True self.l3mdev_checked = True self.l3mdev6_rule = False if self._l3mdev_rule(self.ip6_rule_cache): self.l3mdev6_rule = True self.l3mdev_checked = True self._iproute2_vrf_map_initialized = False self.iproute2_vrf_map = {} self.iproute2_vrf_map_sync_to_disk = False self.vrf_table_id_start = policymanager.policymanager_api.get_module_globals( module_name=self.__class__.__name__, attr='vrf-table-id-start') if not self.vrf_table_id_start: self.vrf_table_id_start = self.VRF_TABLE_START self.vrf_table_id_end = policymanager.policymanager_api.get_module_globals( module_name=self.__class__.__name__, attr='vrf-table-id-end') if not self.vrf_table_id_end: self.vrf_table_id_end = self.VRF_TABLE_END self._modinfo['attrs']['vrf-table']['validrange'] = [ str(self.vrf_table_id_start), str(self.vrf_table_id_end) ] self.vrf_max_count = policymanager.policymanager_api.get_module_globals( module_name=self.__class__.__name__, attr='vrf-max-count') self.vrf_fix_local_table = True self.vrf_count = 0 self.vrf_helper = policymanager.policymanager_api.get_module_globals( module_name=self.__class__.__name__, attr='vrf-helper') self.vrf_close_socks_on_down = policymanager.policymanager_api.get_module_globals( module_name=self.__class__.__name__, attr='vrf-close-socks-on-down') self.warn_on_vrf_map_write_err = True
def showbridge(self, bridgename=None): if bridgename: return utils.exec_command('%s showbridge %s' % (utils.mstpctl_cmd, bridgename)) else: return utils.exec_command('%s showbridge' % utils.mstpctl_cmd)
def _up(self, ifaceobj): vlanid = self._get_vlan_id(ifaceobj) if vlanid == -1: raise Exception('could not determine vlanid') vlanrawdevice = self._get_vlan_raw_device(ifaceobj) if not vlanrawdevice: raise Exception('could not determine vlan raw device') ifname = ifaceobj.name if ifupdownflags.flags.PERFMODE: cached_vlan_ifla_info_data = {} else: cached_vlan_ifla_info_data = self.cache.get_link_info_data(ifname) vlan_bridge_binding = ifaceobj.get_attr_value_first("vlan-bridge-binding") if not vlan_bridge_binding: vlan_bridge_binding = policymanager.policymanager_api.get_attr_default( self.__class__.__name__, "vlan-bridge-binding" ) or self.get_attr_default_value("vlan-bridge-binding") bool_vlan_bridge_binding = utils.get_boolean_from_string(vlan_bridge_binding) vlan_protocol = ifaceobj.get_attr_value_first('vlan-protocol') cached_vlan_protocol = cached_vlan_ifla_info_data.get(Link.IFLA_VLAN_PROTOCOL) if not vlan_protocol: vlan_protocol = self.get_attr_default_value('vlan-protocol') if cached_vlan_protocol and vlan_protocol.lower() != cached_vlan_protocol.lower(): raise Exception('%s: cannot change vlan-protocol to %s: operation not supported. ' 'Please delete the device with \'ifdown %s\' and recreate it to ' 'apply the change.' % (ifaceobj.name, vlan_protocol, ifaceobj.name)) cached_vlan_id = cached_vlan_ifla_info_data.get(Link.IFLA_VLAN_ID) if cached_vlan_id is not None and vlanid != cached_vlan_id: raise Exception('%s: cannot change vlan-id to %s: operation not supported. ' 'Please delete the device with \'ifdown %s\' and recreate it to ' 'apply the change.' % (ifaceobj.name, vlanid, ifaceobj.name)) if not ifupdownflags.flags.PERFMODE: vlan_exists = self.cache.link_exists(ifaceobj.name) if vlan_exists: user_vlan_raw_device = ifaceobj.get_attr_value_first('vlan-raw-device') cached_vlan_raw_device = self.cache.get_lower_device_ifname(ifname) if cached_vlan_raw_device and user_vlan_raw_device and cached_vlan_raw_device != user_vlan_raw_device: raise Exception('%s: cannot change vlan-raw-device from %s to %s: operation not supported. ' 'Please delete the device with \'ifdown %s\' and recreate it to apply the change.' % (ifaceobj.name, cached_vlan_raw_device, user_vlan_raw_device, ifaceobj.name)) if not self.cache.link_exists(vlanrawdevice): if ifupdownflags.flags.DRYRUN: return else: raise Exception('rawdevice %s not present' % vlanrawdevice) if vlan_exists: # vlan-bridge-binding has changed we need to update it if vlan_bridge_binding is not None and bool_vlan_bridge_binding != cached_vlan_ifla_info_data.get(Link.IFLA_VLAN_FLAGS, {}).get(Link.VLAN_FLAG_BRIDGE_BINDING, False): self.logger.info("%s: mismatch detected: resetting: vlan-bridge-binding %s" % (ifname, vlan_bridge_binding)) self.netlink.link_add_vlan(vlanrawdevice, ifaceobj.name, vlanid, vlan_protocol, bool_vlan_bridge_binding) self._bridge_vid_add_del(vlanrawdevice, vlanid) return try: self.netlink.link_add_vlan(vlanrawdevice, ifaceobj.name, vlanid, vlan_protocol, bool_vlan_bridge_binding if vlan_bridge_binding is not None else None) except RetryCMD as e: self.logger.info("%s: attempting to create vlan without bridge_binding (capability not detected on the system)" % ifaceobj.name) utils.exec_command(e.cmd) self._bridge_vid_add_del(vlanrawdevice, vlanid)
def bridge_vlan_del_vid_list(ifname, vids): if not vids: return for v in vids: utils.exec_command("%s vlan del vid %s dev %s" % (utils.bridge_cmd, v, ifname))
def bridge_set_stp(bridge, stp_state): utils.exec_command("%s stp %s %s" % (utils.brctl_cmd, bridge, stp_state))
def link_add_veth(self, ifname, peer_name): utils.exec_command("%s link add %s type veth peer name %s" % (utils.ip_cmd, ifname, peer_name))
def link_add_macvlan(self, ifname, macvlan_ifname, macvlan_mode): utils.exec_command( "%s link add link %s name %s type macvlan mode %s" % (utils.ip_cmd, ifname, macvlan_ifname, macvlan_mode))
def link_add(self, ifname, link_type): utils.exec_command("%s link add %s type %s" % (utils.ip_cmd, ifname, link_type))
def _up(self, ifaceobj): vxlan_id_str = ifaceobj.get_attr_value_first("vxlan-id") if not ifaceobj.link_privflags & ifaceLinkPrivFlags.SINGLE_VXLAN and not vxlan_id_str: self.logger.warning("%s: missing vxlan-id attribute on vxlan device" % ifaceobj.name) return ifname = ifaceobj.name link_exists = self.cache.link_exists(ifname) if link_exists: # if link already exists make sure this is a vxlan device_link_kind = self.cache.get_link_kind(ifname) if device_link_kind != "vxlan": self.logger.error( "%s: device already exists and is not a vxlan (type %s)" % (ifname, device_link_kind) ) ifaceobj.set_status(ifaceStatus.ERROR) return # get vxlan running attributes cached_vxlan_ifla_info_data = self.cache.get_link_info_data(ifname) else: cached_vxlan_ifla_info_data = {} user_request_vxlan_info_data = {} if vxlan_id_str: # for single vxlan device we don't have a vxlan-id self.__config_vxlan_id(ifname, ifaceobj, vxlan_id_str, user_request_vxlan_info_data, cached_vxlan_ifla_info_data) self.__config_vxlan_learning(ifaceobj, link_exists, user_request_vxlan_info_data, cached_vxlan_ifla_info_data) self.__config_vxlan_ageing(ifname, ifaceobj, link_exists, user_request_vxlan_info_data, cached_vxlan_ifla_info_data) self.__config_vxlan_port(ifname, ifaceobj, link_exists, user_request_vxlan_info_data, cached_vxlan_ifla_info_data) self.__config_vxlan_ttl(ifname, ifaceobj, user_request_vxlan_info_data, cached_vxlan_ifla_info_data) local = self.__config_vxlan_local_tunnelip(ifname, ifaceobj, link_exists, user_request_vxlan_info_data, cached_vxlan_ifla_info_data) vxlan_mcast_grp = self.__get_vxlan_attribute(ifaceobj, "vxlan-mcastgrp") vxlan_svcnodeip = self.__get_vxlan_attribute(ifaceobj, "vxlan-svcnodeip") vxlan_mcast_grp6 = self.__get_vxlan_attribute(ifaceobj, "vxlan-mcastgrp6") vxlan_svcnodeip6 = self.__get_vxlan_attribute(ifaceobj, "vxlan-svcnodeip6") vxlan_physdev = self.__get_vxlan_physdev(ifaceobj, vxlan_mcast_grp) vxlan_physdev_changed = self.__config_vxlan_physdev( link_exists, ifaceobj, vxlan_physdev, user_request_vxlan_info_data, cached_vxlan_ifla_info_data ) group, multicast_group_changed = self.__config_vxlan_group( ifname, ifaceobj, link_exists, vxlan_mcast_grp, vxlan_svcnodeip, vxlan_physdev, user_request_vxlan_info_data, cached_vxlan_ifla_info_data ) group6, multicast_group_changed6 = self.__config_vxlan_group6( ifname, ifaceobj, link_exists, vxlan_mcast_grp6, vxlan_svcnodeip6, vxlan_physdev, user_request_vxlan_info_data, cached_vxlan_ifla_info_data ) flap_vxlan_device = link_exists and (multicast_group_changed or multicast_group_changed6 or vxlan_physdev_changed) if user_request_vxlan_info_data: if link_exists and not len(user_request_vxlan_info_data) > 1: # if the vxlan already exists it's already cached # user_request_vxlan_info_data always contains at least one # element: vxlan-id self.logger.info('%s: vxlan already exists - no change detected' % ifname) else: if ifaceobj.link_privflags & ifaceLinkPrivFlags.SINGLE_VXLAN: if link_exists: self.logger.warning("%s: updating existing single vxlan device is not support yet" % ifname) else: self.iproute2.link_add_single_vxlan( ifname, local.ip if local else None, group.ip if group else None, vxlan_physdev, user_request_vxlan_info_data.get(Link.IFLA_VXLAN_PORT) ) else: try: if flap_vxlan_device: self.netlink.link_down_force(ifname) self.netlink.link_add_vxlan_with_info_data(ifname, user_request_vxlan_info_data) if flap_vxlan_device: self.netlink.link_up_force(ifname) except Exception as e: if link_exists: self.log_error("%s: applying vxlan change failed: %s" % (ifname, str(e)), ifaceobj) else: self.log_error("%s: vxlan creation failed: %s" % (ifname, str(e)), ifaceobj) return if ifaceobj.link_privflags & ifaceLinkPrivFlags.SINGLE_VXLAN: # check current fdb entries vxlan_fdb_data = utils.exec_command("bridge fdb show dev %s" % ifname) current_fdb = [] if vxlan_fdb_data: # each entry should look like the following: # 00:00:00:00:00:00 dst 239.1.1.100 src_vni 1000 self permanent for entry in [line for line in vxlan_fdb_data.strip().split("\n") if "src_vni" in line]: mac, _, dst, _, src_vni = entry.split()[0:5] current_fdb.append((mac, src_vni, dst)) user_config_fdb = self.get_vxlan_fdb_src_vni(ifaceobj.get_attr_value("vxlan-mcastgrp-map")) fdb_to_remove = set(current_fdb) - set(user_config_fdb) for mac, vni, _ in fdb_to_remove: self.iproute2.bridge_fdb_del_src_vni(ifname, mac, vni) for mac, src_vni, dst_ip in user_config_fdb: if (mac, src_vni, dst_ip) not in current_fdb: try: self.iproute2.bridge_fdb_add_src_vni(ifname, src_vni, dst_ip) except Exception as e: ifaceobj.set_status(ifaceStatus.ERROR) self.log_error("%s: vxlan-mcastgrp-map: %s=%s: %s" % (ifname, src_vni, dst_ip, str(e)), raise_error=False) vxlan_purge_remotes = self.__get_vlxan_purge_remotes(ifaceobj) remoteips = ifaceobj.get_attr_value('vxlan-remoteip') if remoteips: try: for remoteip in remoteips: ipnetwork.IPv4Address(remoteip) except Exception as e: self.log_error('%s: vxlan-remoteip: %s' % (ifaceobj.name, str(e))) if vxlan_purge_remotes or remoteips: # figure out the diff for remotes and do the bridge fdb updates # only if provisioned by user and not by an vxlan external # controller. local_str = str(local) if local_str and remoteips and local_str in remoteips: remoteips.remove(local_str) peers = self.iproute2.get_vxlan_peers(ifaceobj.name, str(group.ip) if group else None) cur_peers = set(peers) if remoteips: new_peers = set(remoteips) del_list = cur_peers.difference(new_peers) add_list = new_peers.difference(cur_peers) else: del_list = cur_peers add_list = [] for addr in del_list: try: self.iproute2.bridge_fdb_del( ifaceobj.name, "00:00:00:00:00:00", None, True, addr ) except Exception: pass for addr in add_list: try: self.iproute2.bridge_fdb_append( ifaceobj.name, "00:00:00:00:00:00", None, True, addr ) except Exception: pass
def showportdetail(self, bridgename): return utils.exec_command('%s showportdetail %s' % (utils.mstpctl_cmd, bridgename))
self.logger.info('vrf: removing file %s' % self.iproute2_vrf_filename) os.remove(self.iproute2_vrf_filename) except Exception, e: self.logger.debug('vrf: removing file failed (%s)' % str(e)) try: ip_rules = utils.exec_command('%s rule show' % utils.ip_cmd).splitlines() self.ip_rule_cache = [' '.join(r.split()) for r in ip_rules] except Exception, e: self.ip_rule_cache = [] self.logger.warn('vrf: cache v4: %s' % str(e)) try: ip_rules = utils.exec_command('%s -6 rule show' % utils.ip_cmd).splitlines() self.ip6_rule_cache = [' '.join(r.split()) for r in ip_rules] except Exception, e: self.ip6_rule_cache = [] self.logger.warn('vrf: cache v6: %s' % str(e)) #self.logger.debug("vrf: ip rule cache") #self.logger.info(self.ip_rule_cache) #self.logger.info("vrf: ip -6 rule cache") #self.logger.info(self.ip6_rule_cache) self.l3mdev_checked = False self.l3mdev4_rule = False if self._l3mdev_rule(self.ip_rule_cache): self.l3mdev4_rule = True
self.logger.info('vrf: removing file %s' %self.iproute2_vrf_filename) os.remove(self.iproute2_vrf_filename) except Exception, e: self.logger.debug('vrf: removing file failed (%s)' %str(e)) try: ip_rules = utils.exec_command('%s rule show' %utils.ip_cmd).splitlines() self.ip_rule_cache = [' '.join(r.split()) for r in ip_rules] except Exception, e: self.ip_rule_cache = [] self.logger.warn('vrf: cache v4: %s' % str(e)) try: ip_rules = utils.exec_command('%s -6 rule show' %utils.ip_cmd).splitlines() self.ip6_rule_cache = [' '.join(r.split()) for r in ip_rules] except Exception, e: self.ip6_rule_cache = [] self.logger.warn('vrf: cache v6: %s' % str(e)) #self.logger.debug("vrf: ip rule cache") #self.logger.info(self.ip_rule_cache) #self.logger.info("vrf: ip -6 rule cache") #self.logger.info(self.ip6_rule_cache) self.l3mdev_checked = False self.l3mdev4_rule = False if self._l3mdev_rule(self.ip_rule_cache): self.l3mdev4_rule = True
def bridge_vlan_add_vid_list(ifname, vids): for v in vids: utils.exec_command("%s vlan add vid %s dev %s" % (utils.bridge_cmd, v, ifname))
def _kill_ssh_connections(self, ifacename, ifaceobj): try: iplist = [ str(ip.ip) for ip in self.cache.get_managed_ip_addresses( ifname=ifacename, ifaceobj_list=[ifaceobj], ) ] if not iplist: return proc = [] #Example output: #ESTAB 0 0 10.0.1.84:ssh 10.0.1.228:45186 #users:(("sshd",pid=2528,fd=3)) cmdl = [utils.ss_cmd, '-t', '-p'] for line in utils.exec_commandl(cmdl).splitlines(): citems = line.split() addr = None if '%' in citems[3]: addr = citems[3].split('%')[0] elif ':ssh' in citems[3]: addr = citems[3].split(':')[0] if not addr: continue if addr in iplist: if len(citems) == 6: proc.append(citems[5].split(',')[1].split('=')[1]) if not proc: return pid = None # outpt of '/usr/bin/pstree -Aps <pid>': # 'systemd(1)---sshd(990)---sshd(16112)---sshd(16126)---bash(16127)---sudo(16756)---ifreload(16761)---pstree(16842)\n' # get the above output to following format # ['systemd(1)', 'sshd(990)', 'sshd(16112)', 'sshd(16126)', 'bash(16127)', 'sudo(16756)', 'ifreload(16761)', 'pstree(16850)'] pstree = list( reversed( utils.exec_command( '%s -Aps %s' % (utils.pstree_cmd, os.getpid())).strip().split('---'))) for index, process in enumerate(pstree): # check the parent of SSH process to make sure # we don't kill SSH server or systemd process if 'sshd' in process and 'sshd' in pstree[index + 1]: pid = [x for x in process if x.isdigit()] break self.logger.info("%s: killing active ssh sessions: %s" % (ifacename, str(proc))) if ifupdownflags.flags.DRYRUN: return for id in proc: if id != pid: try: os.kill(int(id), signal.SIGINT) except OSError as e: continue # Kill current SSH client if pid in proc: try: forkret = os.fork() except OSError as e: self.logger.info("fork error : %s [%d]" % (e.strerror, e.errno)) if (forkret == 0): # The first child. try: os.setsid() self.logger.info( "%s: ifreload continuing in the background" % ifacename) except OSError as xxx_todo_changeme: (err_no, err_message) = xxx_todo_changeme.args self.logger.info("os.setsid failed: errno=%d: %s" % (err_no, err_message)) self.logger.info("pid=%d pgid=%d" % (os.getpid(), os.getpgid(0))) try: self.logger.info("%s: killing our session: %s" % (ifacename, str(proc))) os.kill(int(pid), signal.SIGINT) return except OSError as e: return except Exception as e: self.logger.info('%s: %s' % (ifacename, str(e)))
def sysctl_set(self, variable, value): utils.exec_command('%s %s=%s' % (utils.sysctl_cmd, variable, value))
ifaceobj.set_state_n_status(ifaceState.from_str(op), status) if ifupdownobj.config.get('addon_scripts_support', '0') == '1': # execute /etc/network/ scripts os.environ['IFACE'] = ifaceobj.name if ifaceobj.name else '' os.environ['LOGICAL'] = ifaceobj.name if ifaceobj.name else '' os.environ[ 'METHOD'] = ifaceobj.addr_method if ifaceobj.addr_method else '' os.environ['ADDRFAM'] = ','.join( ifaceobj.addr_family) if ifaceobj.addr_family else '' for mname in ifupdownobj.script_ops.get(op, []): ifupdownobj.logger.debug('%s: %s : running script %s' % (ifacename, op, mname)) try: utils.exec_command(mname, env=cenv) except Exception, e: ifupdownobj.log_error('%s: %s %s' % (ifacename, op, str(e))) @classmethod def run_iface_list_ops(cls, ifupdownobj, ifaceobjs, ops): """ Runs all operations on a list of interface configurations for the same interface """ # minor optimization. If operation is 'down', proceed only # if interface exists in the system ifacename = ifaceobjs[0].name ifupdownobj.logger.info('%s: running ops ...' % ifacename)
def do_speed_settings(self, ifaceobj, operation='post_up'): cmd = '' autoneg_to_configure = None speed_to_configure = None duplex_to_configure = None config_speed = ifaceobj.get_attr_value_first('link-speed') config_duplex = ifaceobj.get_attr_value_first('link-duplex') config_autoneg = ifaceobj.get_attr_value_first('link-autoneg') default_speed = policymanager.policymanager_api.get_iface_default( module_name='ethtool', ifname=ifaceobj.name, attr='link-speed') default_duplex = policymanager.policymanager_api.get_iface_default( module_name='ethtool', ifname=ifaceobj.name, attr='link-duplex') default_autoneg = policymanager.policymanager_api.get_iface_default( module_name='ethtool', ifname=ifaceobj.name, attr='link-autoneg') # autoneg wins if provided by user and is on if config_autoneg and utils.get_boolean_from_string(config_autoneg): autoneg_to_configure = config_autoneg speed_to_configure = None duplex_to_configure = None elif config_speed: # Any speed settings configured by the user wins autoneg_to_configure = None speed_to_configure = config_speed duplex_to_configure = config_duplex if not config_duplex: duplex_to_configure = default_duplex else: # if user given autoneg config is off, we must respect that and # override any default autoneg config if config_autoneg and not utils.get_boolean_from_string( config_autoneg): default_autoneg = 'off' if default_autoneg and utils.get_boolean_from_string( default_autoneg): autoneg_to_configure = utils.get_onoff_bool(default_autoneg) speed_to_configure = None duplex_to_configure = None else: autoneg_to_configure = None speed_to_configure = default_speed duplex_to_configure = default_duplex if autoneg_to_configure: autoneg_to_configure = utils.get_onoff_bool(autoneg_to_configure) # check running values running_val = self.get_running_attr('autoneg', ifaceobj) if autoneg_to_configure != running_val: # if the configured value is not set, set it cmd += ' autoneg %s' % autoneg_to_configure else: force_set = False if speed_to_configure: # check running values if utils.get_boolean_from_string( self.get_running_attr('autoneg', ifaceobj) or 'off'): cmd = 'autoneg off' # if we are transitioning from autoneg 'on' to 'off' # don't check running speed force_set = True running_val = self.get_running_attr('speed', ifaceobj) if force_set or (speed_to_configure != running_val): # if the configured value is not set, set it cmd += ' speed %s' % speed_to_configure if duplex_to_configure: # check running values running_val = self.get_running_attr('duplex', ifaceobj) if force_set or (duplex_to_configure != running_val): # if the configured value is not set, set it cmd += ' duplex %s' % duplex_to_configure if cmd: try: cmd = ('%s -s %s %s' % (utils.ethtool_cmd, ifaceobj.name, cmd)) utils.exec_command(cmd) except Exception as e: if not self.ethtool_ignore_errors: self.log_error('%s: %s' % (ifaceobj.name, str(e)), ifaceobj)
def __execute_or_batch(self, cmd): if self.__batch_mode: self.__add_to_batch(cmd) else: utils.exec_command("%s %s" % (utils.mstpctl_cmd, cmd))
def bridge_fdb_del_src_vni(dev, mac, src_vni): utils.exec_command("%s fdb del %s dev %s src_vni %s" % (utils.bridge_cmd, mac, dev, src_vni))
def bridge_fdb_del_raw(dev, args): utils.exec_command("%s fdb del dev %s %s" % (utils.bridge_cmd, dev, args))
def sysctl_get(self, variable): return utils.exec_command('%s %s' % (utils.sysctl_cmd, variable)).split('=')[1].strip()
if ifaceobj.status == ifaceStatus.ERROR else ifaceStatus.SUCCESS) ifaceobj.set_state_n_status(ifaceState.from_str(op), status) if ifupdownobj.config.get('addon_scripts_support', '0') == '1': # execute /etc/network/ scripts os.environ['IFACE'] = ifaceobj.name if ifaceobj.name else '' os.environ['LOGICAL'] = ifaceobj.name if ifaceobj.name else '' os.environ['METHOD'] = ifaceobj.addr_method if ifaceobj.addr_method else '' os.environ['ADDRFAM'] = ','.join(ifaceobj.addr_family) if ifaceobj.addr_family else '' for mname in ifupdownobj.script_ops.get(op, []): ifupdownobj.logger.debug('%s: %s : running script %s' %(ifacename, op, mname)) try: utils.exec_command(mname, env=cenv) except Exception, e: ifupdownobj.log_error('%s: %s %s' % (ifacename, op, str(e))) @classmethod def run_iface_list_ops(cls, ifupdownobj, ifaceobjs, ops): """ Runs all operations on a list of interface configurations for the same interface """ # minor optimization. If operation is 'down', proceed only # if interface exists in the system ifacename = ifaceobjs[0].name ifupdownobj.logger.info('%s: running ops ...' %ifacename) if ('down' in ops[0] and
def get_running_attr(self, attr='', ifaceobj=None): if not ifaceobj or not attr: return running_attr = None try: if attr == 'autoneg': output = utils.exec_commandl( [utils.ethtool_cmd, ifaceobj.name]) running_attr = self.get_autoneg(ethtool_output=output) elif attr == 'fec': output = utils.exec_command('%s --show-fec %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_fec_encoding(ethtool_output=output) elif attr == 'gro': if not self.feature_cache: self.feature_cache = utils.exec_command( '%s --show-features %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_offload_setting( ethtool_output=self.feature_cache, setting='generic-receive-offload') elif attr == 'lro': if not self.feature_cache: self.feature_cache = utils.exec_command( '%s --show-features %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_offload_setting( ethtool_output=self.feature_cache, setting='large-receive-offload') elif attr == 'gso': if not self.feature_cache: self.feature_cache = utils.exec_command( '%s --show-features %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_offload_setting( ethtool_output=self.feature_cache, setting='generic-segmentation-offload') elif attr == 'tso': if not self.feature_cache: self.feature_cache = utils.exec_command( '%s --show-features %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_offload_setting( ethtool_output=self.feature_cache, setting='tcp-segmentation-offload') elif attr == 'ufo': if not self.feature_cache: self.feature_cache = utils.exec_command( '%s --show-features %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_offload_setting( ethtool_output=self.feature_cache, setting='udp-fragmentation-offload') elif attr == 'rx': if not self.feature_cache: self.feature_cache = utils.exec_command( '%s --show-features %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_offload_setting( ethtool_output=self.feature_cache, setting='rx-checksumming') elif attr == 'tx': if not self.feature_cache: self.feature_cache = utils.exec_command( '%s --show-features %s' % (utils.ethtool_cmd, ifaceobj.name)) running_attr = self.get_offload_setting( ethtool_output=self.feature_cache, setting='tx-checksumming') else: running_attr = self.io.read_file_oneline('/sys/class/net/%s/%s' % \ (ifaceobj.name, attr)) except Exception as e: if not self.ethtool_ignore_errors: # for nonexistent interfaces, we get an error (rc = 256 or 19200) self.logger.debug( 'ethtool: problems calling ethtool or reading' ' /sys/class on iface %s for attr %s: %s' % (ifaceobj.name, attr, str(e))) return running_attr
def _kill_ssh_connections(self, ifacename): try: runningaddrsdict = self.ipcmd.get_running_addrs(None, ifacename) if not runningaddrsdict: return iplist = [i.split('/', 1)[0] for i in runningaddrsdict.keys()] if not iplist: return proc=[] #Example output: #ESTAB 0 0 10.0.1.84:ssh 10.0.1.228:45186 #users:(("sshd",pid=2528,fd=3)) cmdl = [utils.ss_cmd, '-t', '-p'] for line in utils.exec_commandl(cmdl).splitlines(): citems = line.split() addr = None if '%' in citems[3]: addr = citems[3].split('%')[0] elif ':ssh' in citems[3]: addr = citems[3].split(':')[0] if not addr: continue if addr in iplist: if len(citems) == 6: proc.append(citems[5].split(',')[1].split('=')[1]) if not proc: return pid = None # outpt of '/usr/bin/pstree -Aps <pid>': # 'systemd(1)---sshd(990)---sshd(16112)---sshd(16126)---bash(16127)---sudo(16756)---ifreload(16761)---pstree(16842)\n' # get the above output to following format # ['systemd(1)', 'sshd(990)', 'sshd(16112)', 'sshd(16126)', 'bash(16127)', 'sudo(16756)', 'ifreload(16761)', 'pstree(16850)'] pstree = list(reversed(utils.exec_command('%s -Aps %s' % (utils.pstree_cmd, os.getpid())).strip().split('---'))) for index, process in enumerate(pstree): # check the parent of SSH process to make sure # we don't kill SSH server or systemd process if 'sshd' in process and 'sshd' in pstree[index + 1]: pid = filter(lambda x: x.isdigit(), process) break self.logger.info("%s: killing active ssh sessions: %s" %(ifacename, str(proc))) if ifupdownflags.flags.DRYRUN: return for id in proc: if id != pid: try: os.kill(int(id), signal.SIGINT) except OSError as e: continue # Kill current SSH client if pid in proc: try: forkret = os.fork() except OSError, e: self.logger.info("fork error : %s [%d]" % (e.strerror, e.errno)) if (forkret == 0): # The first child. try: os.setsid() self.logger.info("%s: ifreload continuing in the background" %ifacename) except OSError, (err_no, err_message): self.logger.info("os.setsid failed: errno=%d: %s" % (err_no, err_message)) self.logger.info("pid=%d pgid=%d" % (os.getpid(), os.getpgid(0))) try: self.logger.info("%s: killing our session: %s" %(ifacename, str(proc))) os.kill(int(pid), signal.SIGINT) return except OSError as e: return
def _add_vrf_rules(self, vrf_dev_name, vrf_table): pref = 200 ip_rule_out_format = '%s: from all %s %s lookup %s' ip_rule_cmd = '%s %s rule add pref %s %s %s table %s' if self.vrf_fix_local_table: self.vrf_fix_local_table = False rule = '0: from all lookup local' if rule in self.ip_rule_cache: try: utils.exec_command('%s rule del pref 0' %utils.ip_cmd) utils.exec_command('%s rule add pref 32765 table local' %utils.ip_cmd) except Exception as e: self.logger.info('%s: %s' % (vrf_dev_name, str(e))) pass if rule in self.ip6_rule_cache: try: utils.exec_command('%s -6 rule del pref 0' %utils.ip_cmd) utils.exec_command('%s -6 rule add pref 32765 table local' %utils.ip_cmd) except Exception as e: self.logger.info('%s: %s' % (vrf_dev_name, str(e))) pass if not self.l3mdev_checked: self._rule_cache_fill() self.l3mdev_checked = True #Example ip rule #200: from all oif blue lookup blue #200: from all iif blue lookup blue rule = ip_rule_out_format %(pref, 'oif', vrf_dev_name, vrf_dev_name) if not self.l3mdev4_rule and rule not in self.ip_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '', pref, 'oif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd) rule = ip_rule_out_format %(pref, 'iif', vrf_dev_name, vrf_dev_name) if not self.l3mdev4_rule and rule not in self.ip_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '', pref, 'iif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd) rule = ip_rule_out_format %(pref, 'oif', vrf_dev_name, vrf_dev_name) if not self.l3mdev6_rule and rule not in self.ip6_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '-6', pref, 'oif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd) rule = ip_rule_out_format %(pref, 'iif', vrf_dev_name, vrf_dev_name) if not self.l3mdev6_rule and rule not in self.ip6_rule_cache: rule_cmd = ip_rule_cmd %(utils.ip_cmd, '-6', pref, 'iif', vrf_dev_name, vrf_dev_name) utils.exec_command(rule_cmd)
class vrf(moduleBase): """ ifupdown2 addon module to configure vrfs """ _modinfo = { 'mhelp': 'vrf configuration module', 'attrs': { 'vrf-table': { 'help': 'vrf device routing table id. key to ' + 'creating a vrf device. ' + 'Table id is either \'auto\' or ' + '\'valid routing table id\'', 'validvals': ['auto', '<number>'], 'example': ['vrf-table auto', 'vrf-table 1001'] }, 'vrf': { 'help': 'vrf the interface is part of.', 'validvals': ['<text>'], 'example': ['vrf blue'] } } } iproute2_vrf_filename = '/etc/iproute2/rt_tables.d/ifupdown2_vrf_map.conf' iproute2_vrf_filehdr = '# This file is autogenerated by ifupdown2.\n' + \ '# It contains the vrf name to table mapping.\n' + \ '# Reserved table range %s %s\n' VRF_TABLE_START = 1001 VRF_TABLE_END = 5000 system_reserved_rt_tables = { '255': 'local', '254': 'main', '253': 'default', '0': 'unspec' } def __init__(self, *args, **kargs): moduleBase.__init__(self, *args, **kargs) self.ipcmd = None self.bondcmd = None self.dhclientcmd = None self.name = self.__class__.__name__ self.vrf_mgmt_devname = policymanager.policymanager_api.get_module_globals( module_name=self.__class__.__name__, attr='vrf-mgmt-devname') self.user_reserved_vrf_table = [] if (ifupdownflags.flags.PERFMODE and not (self.vrf_mgmt_devname and os.path.exists( '/sys/class/net/%s' % self.vrf_mgmt_devname))): # if perf mode is set (PERFMODE is set at boot), and this is the first # time we are calling ifup at boot (check for mgmt vrf existance at # boot, make sure this is really the first invocation at boot. # ifup is called with PERFMODE at boot multiple times (once for mgmt vrf # and the second time with all auto interfaces). We want to delete # the map file only the first time. This is to avoid accidently # deleting map file with a valid mgmt vrf entry if os.path.exists(self.iproute2_vrf_filename): try: self.logger.info('vrf: removing file %s' % self.iproute2_vrf_filename) os.remove(self.iproute2_vrf_filename) except Exception, e: self.logger.debug('vrf: removing file failed (%s)' % str(e)) try: ip_rules = utils.exec_command('%s rule show' % utils.ip_cmd).splitlines() self.ip_rule_cache = [' '.join(r.split()) for r in ip_rules] except Exception, e: self.ip_rule_cache = [] self.logger.warn('vrf: cache v4: %s' % str(e))