def delNetwork(network, vlan=None, bonding=None, nics=None, force=False, configurator=None, implicitBonding=True, _netinfo=None, **options): if _netinfo is None: _netinfo = netinfo.NetInfo() if configurator is None: configurator = Ifcfg() if network not in _netinfo.networks: logging.info("Network %r: doesn't exist in libvirt database", network) _delNonVdsmNetwork(network, vlan, bonding, nics, _netinfo, configurator) return nics, vlan, bonding = _netinfo.getNicsVlanAndBondingForNetwork(network) bridged = _netinfo.networks[network]['bridged'] logging.info("Removing network %s with vlan=%s, bonding=%s, nics=%s," "options=%s" % (network, vlan, bonding, nics, options)) if not utils.tobool(force): _validateDelNetwork(network, vlan, bonding, nics, bridged, _netinfo) netEnt = objectivizeNetwork(bridge=network if bridged else None, vlan=vlan, bonding=bonding, nics=nics, _netinfo=_netinfo, configurator=configurator, implicitBonding=implicitBonding) netEnt.ip.bootproto = netinfo.getBootProtocol(netEnt.name) # We must first remove the libvirt network and then the network entity. # Otherwise if we first remove the network entity while the libvirt # network is still up, the network entity (In some flows) thinks that # it still has users and thus does not allow its removal configurator.removeLibvirtNetwork(network) netEnt.remove() # We need to gather NetInfo again to refresh networks info from libvirt. # The deleted bridge should never be up at this stage. _netinfo = netinfo.NetInfo() if network in _netinfo.networks: raise ConfigNetworkError( ne.ERR_USED_BRIDGE, 'delNetwork: bridge %s ' 'still exists' % network)
def call_and_update(self, *args, **kwargs): ret = func(self, *args, **kwargs) self.netinfo = \ netinfo.NetInfo(self.vdscli.getVdsCapabilities()['info']) if self.config is not None: self.config = RunningConfig() return ret
def testIterNetworkHierarchy(self): _netinfo = { 'networks': {}, 'vlans': {}, 'nics': ['testnic1', 'testnic2'], 'bondings': {}, 'bridges': {} } fakeInfo = netinfo.NetInfo(_netinfo) # Vlanned and bonded VM network nic1 = Nic('testnic1', configurator=None, _netinfo=fakeInfo) nic2 = Nic('testnic2', configurator=None, _netinfo=fakeInfo) bond1 = Bond('bond42', configurator=None, slaves=(nic1, nic2)) vlan1 = Vlan(bond1, 4, configurator=None) bridge1 = Bridge('testbridge', configurator=None, port=vlan1) self.assertEqual([dev for dev in bridge1], [bridge1, vlan1, bond1, nic1, nic2]) self.assertEqual(bond1, hierarchy_backing_device(bridge1)) self.assertEqual(4, hierarchy_vlan_tag(bridge1)) # Nic-less VM net bridge2 = Bridge('testbridge', configurator=None, port=None) self.assertEqual([dev for dev in bridge2], [bridge2]) self.assertEqual(None, hierarchy_backing_device(bridge2)) self.assertEqual(None, hierarchy_vlan_tag(bridge2)) # vlan-less VM net bridge3 = Bridge('testbridge', configurator=None, port=bond1) self.assertEqual([dev for dev in bridge3], [bridge3, bond1, nic1, nic2]) self.assertEqual(bond1, hierarchy_backing_device(bridge3)) self.assertEqual(None, hierarchy_vlan_tag(bridge3)) # Bond-less VM net bridge4 = Bridge('testbridge', configurator=None, port=nic1) self.assertEqual([dev for dev in bridge4], [bridge4, nic1]) self.assertEqual(nic1, hierarchy_backing_device(bridge4)) self.assertEqual(None, hierarchy_vlan_tag(bridge4)) # vlanned and bonded non-VM net self.assertEqual([dev for dev in vlan1], [vlan1, bond1, nic1, nic2]) self.assertEqual(bond1, hierarchy_backing_device(vlan1)) self.assertEqual(4, hierarchy_vlan_tag(vlan1)) # vlanned, bond-less non-VM net vlan2 = Vlan(nic1, 5, configurator=None) self.assertEqual([dev for dev in vlan2], [vlan2, nic1]) self.assertEqual(nic1, hierarchy_backing_device(vlan2)) self.assertEqual(5, hierarchy_vlan_tag(vlan2)) # non-vlanned and bonded non-VM net self.assertEqual([dev for dev in bond1], [bond1, nic1, nic2]) self.assertEqual(bond1, hierarchy_backing_device(bond1)) self.assertEqual(None, hierarchy_vlan_tag(bond1)) # non-vlanned and bond-less non-VM net self.assertEqual([dev for dev in nic2], [nic2]) self.assertEqual(nic2, hierarchy_backing_device(nic2)) self.assertEqual(None, hierarchy_vlan_tag(nic2))
def _delNetwork(network, vlan=None, bonding=None, nics=None, force=False, configurator=None, implicitBonding=True, _netinfo=None, keep_bridge=False, **options): if _netinfo is None: _netinfo = netinfo.NetInfo() if configurator is None: configurator = ConfiguratorClass() if network not in _netinfo.networks: logging.info("Network %r: doesn't exist in libvirt database", network) vlan = _vlanToInternalRepresentation(vlan) _delNonVdsmNetwork(network, vlan, bonding, nics, _netinfo, configurator) return nics, vlan, bonding = _netinfo.getNicsVlanAndBondingForNetwork(network) bridged = _netinfo.networks[network]['bridged'] logging.info("Removing network %s with vlan=%s, bonding=%s, nics=%s," "keep_bridge=%s options=%s", network, vlan, bonding, nics, keep_bridge, options) if not utils.tobool(force): _validateDelNetwork(network, vlan, bonding, nics, bridged, _netinfo) net_ent = _objectivizeNetwork(bridge=network if bridged else None, vlan=vlan, bonding=bonding, nics=nics, _netinfo=_netinfo, configurator=configurator, implicitBonding=implicitBonding) net_ent.ip.bootproto = ('dhcp' if _netinfo.networks[network]['dhcpv4'] else 'none') if bridged and keep_bridge: # we now leave the bridge intact but delete everything underneath it net_ent_to_remove = net_ent.port if net_ent_to_remove is not None: # the configurator will not allow us to remove a bridge interface # (be it vlan, bond or nic) unless it is not used anymore. Since # we are interested to leave the bridge here, we have to disconnect # it from the device so that the configurator will allow its # removal. _disconnect_bridge_port(net_ent.name, net_ent_to_remove.name) else: net_ent_to_remove = net_ent # We must first remove the libvirt network and then the network entity. # Otherwise if we first remove the network entity while the libvirt # network is still up, the network entity (In some flows) thinks that # it still has users and thus does not allow its removal configurator.removeLibvirtNetwork(network) if net_ent_to_remove is not None: logging.info('Removing network entity %s', net_ent_to_remove) net_ent_to_remove.remove() # We must remove the QoS last so that no devices nor networks mark the # QoS as used backing_device = hierarchy_backing_device(net_ent) if (backing_device is not None and os.path.exists(netinfo.NET_PATH + '/' + backing_device.name)): configurator.removeQoS(net_ent)
def _add_missing_networks(configurator, networks, bondings, force, logger, _netinfo=None): # We need to use the newest host info if _netinfo is None: _netinfo = netinfo.NetInfo() else: _netinfo.updateDevices() for network, attrs in networks.iteritems(): if 'remove' in attrs: continue d = dict(attrs) if 'bonding' in d: d.update(_buildBondOptions(d['bonding'], bondings, _netinfo)) else: d['nics'] = [d.pop('nic')] if 'nic' in d else [] d['force'] = force logger.debug("Adding network %r", network) try: _addNetwork(network, configurator=configurator, implicitBonding=True, _netinfo=_netinfo, **d) except ConfigNetworkError as cne: if cne.errCode == ne.ERR_FAILED_IFUP: logger.debug("Adding network %r failed. Running " "orphan-devices cleanup", network) _emergencyNetworkCleanup(network, attrs, configurator) raise _netinfo.updateDevices() # Things like a bond mtu can change
def _handleBondings(bondings, configurator): """ Add/Edit/Remove bond interface """ logger = logging.getLogger("_handleBondings") _netinfo = netinfo.NetInfo() for bondName, bondAttrs in bondings.items(): bond = Bond.objectivize(bondName, configurator, bondAttrs.get('options'), bondAttrs.get('nics'), mtu=None, _netinfo=_netinfo, destroyOnMasterRemoval='remove' in bondAttrs) if 'remove' in bondAttrs: logger.debug("Removing bond %s with attributes %s", bondName, bondAttrs) configurator.removeBond(bond) del bondings[bondName] del _netinfo.bondings[bondName] elif bondName in _netinfo.bondings: logger.debug("Editing bond %s with attributes %s", bondName, bondAttrs) configurator.editBonding(bond, _netinfo) else: logger.debug("Creating bond %s with attributes %s", bondName, bondAttrs) configurator.configureBond(bond)
def addNic(self, nic, **opts): """ Create ifcfg-* file with proper fields for NIC """ conf = '' if ipwrapper.Link._detectType(nic.name) == 'dummy': opts['hotplug'] = 'no' if _hwaddr_required(): _netinfo = netinfo.NetInfo() hwaddr = (_netinfo.nics[nic.name].get('permhwaddr') or _netinfo.nics[nic.name]['hwaddr']) conf += 'HWADDR=%s\n' % pipes.quote(hwaddr) if nic.bridge: conf += 'BRIDGE=%s\n' % pipes.quote(nic.bridge.name) if nic.bond: conf += 'MASTER=%s\nSLAVE=yes\n' % pipes.quote(nic.bond.name) if not self.unifiedPersistence or nic.serving_default_route: conf += 'ONBOOT=%s\n' % 'yes' else: conf += 'ONBOOT=%s\n' % 'no' ethtool_opts = getEthtoolOpts(nic.name) if ethtool_opts: conf += 'ETHTOOL_OPTS=%s\n' % pipes.quote(ethtool_opts) ipconfig, mtu = self._getIfaceConfValues(nic) self._createConfFile(conf, nic.name, ipconfig, mtu, **opts)
def network(caps, device): """Returns a dictionary that describes the network of the device""" info = netinfo.NetInfo(caps) attrs = {} if device in info.vlans: port_info = info.vlans[device] attrs['vlan'] = port_info['vlanid'] iface = port_info['iface'] if iface in info.bondings: attrs['bonding'] = iface else: attrs['nic'] = iface elif device in info.bondings: attrs['bonding'] = device port_info = info.bondings[device] elif device in info.nics: attrs['nic'] = device port_info = info.nics[device] else: raise RuntimeError('The selected device %s is not a supported bridge ' 'port' % device) if 'BOOTPROTO' in port_info['cfg']: attrs['bootproto'] = port_info['cfg']['BOOTPROTO'] if attrs.get('bootproto') == 'dhcp': attrs['blockingdhcp'] = True else: attrs['ipaddr'] = port_info['addr'] attrs['netmask'] = port_info['netmask'] gateway = port_info.get('gateway') if gateway is not None: attrs['gateway'] = gateway elif 'GATEWAY' in port_info['cfg']: attrs['gateway'] = port_info['cfg']['GATEWAY'] return attrs
def _get_netinfo(self): response = self.getVdsCapabilities() try: return netinfo.NetInfo(response[2]) except IndexError: raise Exception('VdsProxy: getVdsCapabilities failed. ' 'code:%s msg:%s' % (response[0], response[1]))
def _handleBondings(bondings, configurator): """ Add/Edit/Remove bond interface """ logger = logging.getLogger("_handleBondings") _netinfo = netinfo.NetInfo() edition = [] addition = [] for name, attrs in bondings.items(): if 'remove' in attrs: bond = Bond.objectivize(name, configurator, attrs.get('options'), attrs.get('nics'), mtu=None, _netinfo=_netinfo, destroyOnMasterRemoval='remove' in attrs) bond.remove() del _netinfo.bondings[name] elif name in _netinfo.bondings: edition.append((name, attrs)) else: addition.append((name, attrs)) for name, attrs in edition: bond = Bond.objectivize(name, configurator, attrs.get('options'), attrs.get('nics'), mtu=None, _netinfo=_netinfo, destroyOnMasterRemoval='remove' in attrs) logger.debug("Editing bond %r with options %s", bond, bond.options) configurator.editBonding(bond, _netinfo) for name, attrs in addition: bond = Bond.objectivize(name, configurator, attrs.get('options'), attrs.get('nics'), mtu=None, _netinfo=_netinfo, destroyOnMasterRemoval='remove' in attrs) logger.debug("Creating bond %r with options %s", bond, bond.options) configurator.configureBond(bond)
def _validateNetworkSetup(networks, bondings): _netinfo = netinfo.NetInfo() for network, networkAttrs in networks.iteritems(): if networkAttrs.get('remove', False): if set(networkAttrs) - set(['remove']): raise ConfigNetworkError( ne.ERR_BAD_PARAMS, 'Cannot specify ' 'any attribute when removing') for bonding, bondingAttrs in bondings.iteritems(): Bond.validateName(bonding) if 'options' in bondingAttrs: Bond.validateOptions(bonding, bondingAttrs['options']) if bondingAttrs.get('remove', False): if bonding not in _netinfo.bondings: raise ConfigNetworkError( ne.ERR_BAD_BONDING, "Cannot remove " "bonding %s: Doesn't exist" % bonding) continue nics = bondingAttrs.get('nics', None) if not nics: raise ConfigNetworkError(ne.ERR_BAD_PARAMS, "Must specify nics for bonding") if not set(nics).issubset(set(_netinfo.nics)): raise ConfigNetworkError(ne.ERR_BAD_NIC, "Unknown nics in: %r" % list(nics))
def start(self): self.vdscli = vdscli.connect() self.netinfo = \ netinfo.NetInfo(self.vdscli.getVdsCapabilities()['info']) if config.get('vars', 'net_persistence') == 'unified': self.config = RunningConfig() else: self.config = None
def removeNic(self, nic): _netinfo = netinfo.NetInfo() to_be_removed = self._ifaceDownAndCleanup(nic, _netinfo) if to_be_removed: self.configApplier.removeNic(nic.name) else: self._setNewMtu(nic, _netinfo.getVlanDevsForIface(nic.name)) ifup(nic.name)
def _delBrokenNetwork(network, netAttr, configurator): '''Adapts the network information of broken networks so that they can be deleted via delNetwork.''' _netinfo = netinfo.NetInfo() _netinfo.networks[network] = netAttr if _netinfo.networks[network]['bridged']: _netinfo.networks[network]['ports'] = ConfigWriter.ifcfgPorts(network) delNetwork(network, configurator=configurator, force=True, implicitBonding=False, _netinfo=_netinfo)
def __init__(self, name, configurator, ipconfig=None, mtu=None, _netinfo=None): if _netinfo is None: _netinfo = netinfo.NetInfo() if name not in _netinfo.nics: raise ConfigNetworkError(ne.ERR_BAD_NIC, 'unknown nic: %s' % name) if _netinfo.ifaceUsers(name): mtu = max(mtu, netinfo.getMtu(name)) super(Nic, self).__init__(name, configurator, ipconfig, mtu=mtu)
def testTextualRepr(self): _netinfo = {'networks': {}, 'vlans': {}, 'nics': ['testnic1', 'testnic2'], 'bondings': {}, 'bridges': {}} fakeInfo = netinfo.NetInfo(_netinfo) nic1 = Nic('testnic1', None, _netinfo=fakeInfo) nic2 = Nic('testnic2', None, _netinfo=fakeInfo) bond1 = Bond('bond42', None, slaves=(nic1, nic2)) vlan1 = Vlan(bond1, '4', None) bridge1 = Bridge('testbridge', None, port=vlan1) self.assertEqual('%r' % bridge1, 'Bridge(testbridge: Vlan(bond42.4: ' 'Bond(bond42: (Nic(testnic1), Nic(testnic2)))))')
def _customization(self): info = netinfo.NetInfo( vds_info.capabilities( self.environment[ohostedcons.VDSMEnv.VDS_CLI])) interfaces = set(info.nics.keys() + info.bondings.keys() + info.vlans.keys()) validValues = [] enslaved = set() inv_bond = set() for bridge in info.bridges.keys(): enslaved.update(set(info.bridges[bridge]['ports'])) for bond in info.bondings.keys(): slaves = set(info.bondings[bond]['slaves']) if slaves: enslaved.update(slaves) else: self.logger.debug('Detected bond device %s without slaves' % bond) inv_bond.update(set([bond])) validValues = list(interfaces - enslaved - inv_bond) self.logger.debug('Nics detected: %s' % ','.join(interfaces)) self.logger.debug('Nics enslaved: %s' % ','.join(enslaved)) self.logger.debug('Nics valid: %s' % ','.join(validValues)) if not validValues: if enslaved: raise RuntimeError( _('The following existing interfaces are not suitable ' 'for vdsm: {enslaved}. You might want to pull out an ' 'interface out of a bridge to be able to use it').format( enslaved=','.join(enslaved))) else: raise RuntimeError(_('A Network interface is required')) interactive = self.environment[ ohostedcons.NetworkEnv.BRIDGE_IF] is None if interactive: default = ohostedcons.Defaults.DEFAULT_BRIDGE_IF if default not in validValues: default = validValues[0] self.environment[ ohostedcons.NetworkEnv.BRIDGE_IF] = self.dialog.queryString( name='ovehosted_bridge_if', note=_( 'Please indicate a nic to set ' '{bridge} bridge on: (@VALUES@) [@DEFAULT@]: ').format( bridge=self.environment[ ohostedcons.NetworkEnv.BRIDGE_NAME]), prompt=True, caseSensitive=True, default=default, validValues=validValues, )
def addBonding(self, bond, **opts): """ Create ifcfg-* file with proper fields for bond """ conf = 'BONDING_OPTS=%s\n' % pipes.quote(bond.options or '') if bond.bridge: conf += 'BRIDGE=%s\n' % pipes.quote(bond.bridge.name) ipaddr, netmask, gateway, bootproto, mtu, defaultRoute = \ self._getIfaceConfValues(bond, netinfo.NetInfo()) self._createConfFile(conf, bond.name, ipaddr, netmask, gateway, bootproto, mtu, defaultRoute, **opts) # create the bonding device to avoid initscripts noise if bond.name not in open(netinfo.BONDING_MASTERS).read().split(): open(netinfo.BONDING_MASTERS, 'w').write('+%s\n' % bond.name)
def _handleBondings(bondings, configurator, in_rollback): """ Add/Edit/Remove bond interface """ logger = logging.getLogger("_handleBondings") _netinfo = netinfo.NetInfo() edition = [] addition = [] for name, attrs in bondings.items(): if 'remove' in attrs: if name not in _netinfo.bondings: if in_rollback: logger.error( 'Cannot remove bonding %s during rollback: ' 'does not exist', name) continue else: raise ConfigNetworkError( ne.ERR_BAD_BONDING, "Cannot remove bonding %s: does not exist" % name) bond = Bond.objectivize(name, configurator, attrs.get('options'), attrs.get('nics'), mtu=None, _netinfo=_netinfo, destroyOnMasterRemoval='remove' in attrs) bond.remove() del _netinfo.bondings[name] elif name in _netinfo.bondings: edition.append((name, attrs)) else: addition.append((name, attrs)) for name, attrs in edition: bond = Bond.objectivize(name, configurator, attrs.get('options'), attrs.get('nics'), mtu=None, _netinfo=_netinfo, destroyOnMasterRemoval='remove' in attrs) if len(bond.slaves) == 0: raise ConfigNetworkError(ne.ERR_BAD_PARAMS, 'Missing required nics' ' for bonding device.') logger.debug("Editing bond %r with options %s", bond, bond.options) configurator.editBonding(bond, _netinfo) for name, attrs in addition: bond = Bond.objectivize(name, configurator, attrs.get('options'), attrs.get('nics'), mtu=None, _netinfo=_netinfo, destroyOnMasterRemoval='remove' in attrs) if len(bond.slaves) == 0: raise ConfigNetworkError(ne.ERR_BAD_PARAMS, 'Missing required nics' ' for bonding device.') logger.debug("Creating bond %r with options %s", bond, bond.options) configurator.configureBond(bond)
def _delBrokenNetwork(network, netAttr, configurator): '''Adapts the network information of broken networks so that they can be deleted via delNetwork.''' _netinfo = netinfo.NetInfo() _netinfo.networks[network] = netAttr if _netinfo.networks[network]['bridged']: _netinfo.networks[network]['ports'] = ConfigWriter.ifcfgPorts(network) elif not os.path.exists('/sys/class/net/' + netAttr['iface']): # Bridgeless broken network without underlying device libvirt.removeNetwork(network) return delNetwork(network, configurator=configurator, force=True, implicitBonding=False, _netinfo=_netinfo)
def removeBond(self, bonding): _netinfo = netinfo.NetInfo() to_be_removed = self._ifaceDownAndCleanup(bonding, _netinfo) if to_be_removed: if bonding.destroyOnMasterRemoval: self.configApplier.removeBonding(bonding.name) for slave in bonding.slaves: slave.remove() else: self.configApplier.setBondingMtu(bonding.name, netinfo.DEFAULT_MTU) ifup(bonding.name) else: self._setNewMtu(bonding, _netinfo.getVlanDevsForIface(bonding.name)) ifup(bonding.name)
def addNic(self, nic, **opts): """ Create ifcfg-* file with proper fields for NIC """ _netinfo = netinfo.NetInfo() hwaddr = (_netinfo.nics[nic.name].get('permhwaddr') or _netinfo.nics[nic.name]['hwaddr']) conf = 'HWADDR=%s\n' % pipes.quote(hwaddr) if nic.bridge: conf += 'BRIDGE=%s\n' % pipes.quote(nic.bridge.name) if nic.bond: conf += 'MASTER=%s\nSLAVE=yes\n' % pipes.quote(nic.bond.name) ipaddr, netmask, gateway, bootproto, mtu, defaultRoute = \ self._getIfaceConfValues(nic, _netinfo) self._createConfFile(conf, nic.name, ipaddr, netmask, gateway, bootproto, mtu, defaultRoute, **opts)
def delNetwork(network, vlan=None, bonding=None, nics=None, force=False, configurator=None, implicitBonding=True, _netinfo=None, **options): if _netinfo is None: _netinfo = netinfo.NetInfo() if configurator is None: configurator = ConfiguratorClass() if network not in _netinfo.networks: logging.info("Network %r: doesn't exist in libvirt database", network) vlan = _vlanToInternalRepresentation(vlan) _delNonVdsmNetwork(network, vlan, bonding, nics, _netinfo, configurator) return nics, vlan, bonding = _netinfo.getNicsVlanAndBondingForNetwork(network) bridged = _netinfo.networks[network]['bridged'] logging.info("Removing network %s with vlan=%s, bonding=%s, nics=%s," "options=%s" % (network, vlan, bonding, nics, options)) if not utils.tobool(force): _validateDelNetwork(network, vlan, bonding, nics, bridged, _netinfo) netEnt = objectivizeNetwork(bridge=network if bridged else None, vlan=vlan, bonding=bonding, nics=nics, _netinfo=_netinfo, configurator=configurator, implicitBonding=implicitBonding) netEnt.ip.bootproto = netinfo.getBootProtocol(netEnt.name) # We must first remove the libvirt network and then the network entity. # Otherwise if we first remove the network entity while the libvirt # network is still up, the network entity (In some flows) thinks that # it still has users and thus does not allow its removal configurator.removeLibvirtNetwork(network) netEnt.remove()
def _delBrokenNetwork(network, netAttr, configurator): '''Adapts the network information of broken networks so that they can be deleted via delNetwork.''' _netinfo = netinfo.NetInfo() _netinfo.networks[network] = netAttr if _netinfo.networks[network]['bridged']: try: nets = configurator.runningConfig.networks except AttributeError: nets = None # ifcfg does not need net definitions _netinfo.networks[network]['ports'] = persistence.configuredPorts( nets, network) elif not os.path.exists('/sys/class/net/' + netAttr['iface']): # Bridgeless broken network without underlying device libvirt.removeNetwork(network) return delNetwork(network, configurator=configurator, force=True, implicitBonding=False, _netinfo=_netinfo)
def addNic(self, nic, **opts): """ Create ifcfg-* file with proper fields for NIC """ conf = '' if _hwaddr_required(): _netinfo = netinfo.NetInfo() hwaddr = (_netinfo.nics[nic.name].get('permhwaddr') or _netinfo.nics[nic.name]['hwaddr']) conf += 'HWADDR=%s\n' % pipes.quote(hwaddr) if nic.bridge: conf += 'BRIDGE=%s\n' % pipes.quote(nic.bridge.name) if nic.bond: conf += 'MASTER=%s\nSLAVE=yes\n' % pipes.quote(nic.bond.name) ethtool_opts = getEthtoolOpts(nic.name) if ethtool_opts: conf += 'ETHTOOL_OPTS=%s\n' % pipes.quote(ethtool_opts) ipconfig, mtu = self._getIfaceConfValues(nic) self._createConfFile(conf, nic.name, ipconfig, mtu, **opts)
def _emergencyNetworkCleanup(network, networkAttrs, configurator): """Remove all leftovers after failed setupNetwork""" _netinfo = netinfo.NetInfo() topNetDev = None if 'bonding' in networkAttrs: if networkAttrs['bonding'] in _netinfo.bondings: topNetDev = Bond.objectivize(networkAttrs['bonding'], configurator, None, None, None, _netinfo, True) elif 'nic' in networkAttrs: if networkAttrs['nic'] in _netinfo.nics: topNetDev = Nic(networkAttrs['nic'], configurator, _netinfo=_netinfo) if 'vlan' in networkAttrs and topNetDev: vlan_name = '%s.%s' % (topNetDev.name, networkAttrs['vlan']) if vlan_name in _netinfo.vlans: topNetDev = Vlan(topNetDev, networkAttrs['vlan'], configurator) if networkAttrs['bridged']: if network in _netinfo.bridges: topNetDev = Bridge(network, configurator, port=topNetDev) if topNetDev: topNetDev.remove()
def showNetwork(network): _netinfo = netinfo.NetInfo() if network not in _netinfo.networks: print "Network %r doesn't exist" % network return bridged = _netinfo.networks[network]['bridged'] print "Network %s(Bridged: %s):" % (network, bridged) nics, vlan, bonding = _netinfo.getNicsVlanAndBondingForNetwork(network) if bridged: ipaddr = _netinfo.networks[network]['addr'] netmask = _netinfo.networks[network]['netmask'] gateway = _netinfo.networks[network]['gateway'] print "ipaddr=%s, netmask=%s, gateway=%s" % (ipaddr, netmask, gateway) else: iface = _netinfo.networks[network]['iface'] ipaddr = _netinfo.nics[iface]['addr'] netmask = _netinfo.nics[iface]['netmask'] print "ipaddr=%s, netmask=%s" % (ipaddr, netmask) print "vlan=%s, bonding=%s, nics=%s" % (vlan, bonding, nics)
def objectivizeNetwork(bridge=None, vlan=None, bonding=None, bondingOptions=None, nics=None, mtu=None, ipaddr=None, netmask=None, gateway=None, bootproto=None, ipv6addr=None, ipv6gateway=None, ipv6autoconf=None, dhcpv6=None, defaultRoute=None, _netinfo=None, configurator=None, blockingdhcp=None, implicitBonding=None, opts=None): """ Constructs an object hierarchy that describes the network configuration that is passed in the parameters. :param bridge: name of the bridge. :param vlan: vlan tag id. :param bonding: name of the bond. :param bondingOptions: bonding options separated by spaces. :param nics: list of nic names. :param mtu: the desired network maximum transmission unit. :param ipaddr: IPv4 address in dotted decimal format. :param netmask: IPv4 mask in dotted decimal format. :param gateway: IPv4 address in dotted decimal format. :param bootproto: protocol for getting IP config for the net, e.g., 'dhcp' :param ipv6addr: IPv6 address in format address[/prefixlen]. :param ipv6gateway: IPv6 address in format address[/prefixlen]. :param ipv6autoconf: whether to use IPv6's stateless autoconfiguration. :param dhcpv6: whether to use DHCPv6. :param _netinfo: network information snapshot. :param configurator: instance to use to apply the network configuration. :param blockingdhcp: whether to acquire dhcp IP config in a synced manner. :param implicitBonding: whether the bond's existance is tied to it's master's. :param defaultRoute: Should this network's gateway be set in the main routing table? :param opts: misc options received by the callee, e.g., {'stp': True}. this function can modify the dictionary. :returns: the top object of the hierarchy. """ if configurator is None: configurator = ConfiguratorClass() if _netinfo is None: _netinfo = netinfo.NetInfo() if opts is None: opts = {} if bondingOptions and not bonding: raise ConfigNetworkError(ne.ERR_BAD_BONDING, 'Bonding options ' 'specified without bonding') topNetDev = None if bonding: topNetDev = Bond.objectivize(bonding, configurator, bondingOptions, nics, mtu, _netinfo, implicitBonding) elif nics: try: nic, = nics except ValueError: raise ConfigNetworkError(ne.ERR_BAD_BONDING, 'Multiple nics ' 'require a bonding device') else: bond = _netinfo.getBondingForNic(nic) if bond: raise ConfigNetworkError(ne.ERR_USED_NIC, 'nic %s already ' 'enslaved to %s' % (nic, bond)) topNetDev = Nic(nic, configurator, mtu=mtu, _netinfo=_netinfo) if vlan is not None: topNetDev = Vlan(topNetDev, vlan, configurator, mtu=mtu) if bridge is not None: stp = None if 'stp' in opts: stp = opts.pop('stp') elif 'STP' in opts: stp = opts.pop('STP') try: stp = _stpBooleanize(stp) except ValueError: raise ConfigNetworkError(ne.ERR_BAD_PARAMS, '"%s" is not a valid ' 'bridge STP value.' % stp) topNetDev = Bridge(bridge, configurator, port=topNetDev, mtu=mtu, stp=stp) if topNetDev is None: raise ConfigNetworkError(ne.ERR_BAD_PARAMS, 'Network defined without ' 'devices.') ipv6 = IPv6(ipv6addr, ipv6gateway, defaultRoute) ipv4 = IPv4(ipaddr, netmask, gateway, defaultRoute) topNetDev.ip = IpConfig( inet4=ipv4, inet6=ipv6, bootproto=bootproto, blocking=(configurator._inRollback or utils.tobool(blockingdhcp)), ipv6autoconf=ipv6autoconf, dhcpv6=dhcpv6) return topNetDev
def setupNetworks(networks, bondings, **options): """Add/Edit/Remove configuration for networks and bondings. Params: networks - dict of key=network, value=attributes where 'attributes' is a dict with the following optional items: vlan=<id> bonding="<name>" | nic="<name>" (bonding and nics are mutually exclusive) ipaddr="<ipv4>" netmask="<ipv4>" gateway="<ipv4>" bootproto="..." ipv6addr="<ipv6>[/<prefixlen>]" ipv6gateway="<ipv6>" ipv6autoconf="0|1" dhcpv6="0|1" defaultRoute=True|False (other options will be passed to the config file AS-IS) -- OR -- remove=True (other attributes can't be specified) bondings - dict of key=bonding, value=attributes where 'attributes' is a dict with the following optional items: nics=["<nic1>" , "<nic2>", ...] options="<bonding-options>" -- OR -- remove=True (other attributes can't be specified) options - dict of options, such as: force=0|1 connectivityCheck=0|1 connectivityTimeout=<int> _inRollback=True|False Notes: When you edit a network that is attached to a bonding, it's not necessary to re-specify the bonding (you need only to note the attachment in the network's attributes). Similarly, if you edit a bonding, it's not necessary to specify its networks. """ logger = logging.getLogger("setupNetworks") libvirt_nets = netinfo.networks() _netinfo = netinfo.NetInfo(_netinfo=netinfo.get( netinfo._libvirtNets2vdsm(libvirt_nets))) networksAdded = set() logger.debug("Setting up network according to configuration: " "networks:%r, bondings:%r, options:%r" % (networks, bondings, options)) force = options.get('force', False) if not utils.tobool(force): logging.debug("Validating configuration") _validateNetworkSetup(dict(networks), dict(bondings)) results = hooks.before_network_setup(_buildSetupHookDict(networks, bondings, options)) # gather any changes that could have been done by the hook scripts networks = results['request']['networks'] bondings = results['request']['bondings'] options = results['request']['options'] logger.debug("Applying...") with ConfiguratorClass(options.get('_inRollback', False)) as configurator: # Remove edited networks and networks with 'remove' attribute for network, networkAttrs in networks.items(): if network in _netinfo.networks: logger.debug("Removing network %r", network) delNetwork(network, configurator=configurator, force=force, implicitBonding=False, _netinfo=_netinfo) if 'remove' in networkAttrs: del networks[network] del libvirt_nets[network] _netinfo.updateDevices() del _netinfo.networks[network] elif network in libvirt_nets: # If the network was not in _netinfo but is in the networks # returned by libvirt, it means that we are dealing with # a broken network. logger.debug('Removing broken network %r', network) _delBrokenNetwork(network, libvirt_nets[network], configurator=configurator) if 'remove' in networkAttrs: del networks[network] del libvirt_nets[network] _netinfo.updateDevices() elif 'remove' in networkAttrs: raise ConfigNetworkError(ne.ERR_BAD_BRIDGE, "Cannot delete " "network %r: It doesn't exist in the " "system" % network) else: networksAdded.add(network) _handleBondings(bondings, configurator) # We need to use the newest host info _netinfo.updateDevices() for network, networkAttrs in networks.iteritems(): d = dict(networkAttrs) if 'bonding' in d: d.update(_buildBondOptions(d['bonding'], bondings, _netinfo)) else: d['nics'] = [d.pop('nic')] if 'nic' in d else [] d['force'] = force logger.debug("Adding network %r", network) try: addNetwork(network, configurator=configurator, implicitBonding=True, _netinfo=_netinfo, **d) except ConfigNetworkError as cne: if cne.errCode == ne.ERR_FAILED_IFUP: logger.debug("Adding network %r failed. Running " "orphan-devices cleanup", network) _emergencyNetworkCleanup(network, networkAttrs, configurator) raise _netinfo.updateDevices() # Things like a bond mtu can change if utils.tobool(options.get('connectivityCheck', True)): logger.debug('Checking connectivity...') if not clientSeen(int(options.get('connectivityTimeout', CONNECTIVITY_TIMEOUT_DEFAULT))): logger.info('Connectivity check failed, rolling back') for network in networksAdded: # If the new added network was created on top of # existing bond, we need to keep the bond on rollback # flow, else we will break the new created bond. delNetwork(network, force=True, implicitBonding=networks[network]. get('bonding') in bondings) raise ConfigNetworkError(ne.ERR_LOST_CONNECTION, 'connectivity check failed') hooks.after_network_setup(_buildSetupHookDict(networks, bondings, options))
def listNetworks(): _netinfo = netinfo.NetInfo() print "Networks:", _netinfo.networks.keys() print "Vlans:", _netinfo.vlans.keys() print "Nics:", _netinfo.nics.keys() print "Bondings:", _netinfo.bondings.keys()