def _get_name(mgmt_ip_addr=None, name=None): """Return a hostname which is generated by mgmt_ip_addr or name""" if not mgmt_ip_addr and not name: raise exception.ValueException( 'Both "mgmt_ip_addr" and "name" cannot be "None"') if mgmt_ip_addr and not re.match('\d+\.\d+\.\d+\.\d+/\d+', mgmt_ip_addr): raise exception.ValueException( '"mgmt_ip_addr" does not have a format x.x.x.x/x') return name if name else test_network.get_hostname(mgmt_ip_addr)
def _get_object(self): try: network_object = powershell.exec_powershell('get-vmswitch', name=self.name) except exception.ExeExitcodeException as err: if 'No switch can be found' in err.output: raise exception.NotFoundException( 'vSwitch "%s" does not exist' % self.name) raise if len(network_object) > 1: if self.id is None: raise exception.ValueException( 'Found more than one switch that has the name %s. Need ' '"switch_id" argument additionally') network_object = [ _no for _no in network_object if _no.Id == self.id ] if not network_object: raise exception.NotFoundException( 'vSwitch "%s" %s does not exist' % (self.name, '' if self.id is None else '(ID: ' + str(self.id) + ')')) return network_object[0]
def __init__(self, name, br_iface, iface, ip_addr, **kwargs): if not br_iface: raise exception.ValueException('"br_iface" argument is required') super(Route, self).__init__( name=name, br_iface=br_iface, forward_mode='route', ip_addr=ip_addr) self._iface = iface
def get_mgmt_ip_addr(cls, vm_name, ip_network): mgmt_ip_network = netaddr.IPNetwork(ip_network) iface_list = powershell.exec_powershell( 'get-vm', name=vm_name, select_clause='networkadapters' )[0].NetworkAdapters mgmt_ip_addr_list = [] for iface in iface_list: for ip_network in iface['IPAddresses'].split(): if netaddr.IPAddress(ip_network) in mgmt_ip_network: mgmt_ip_addr_list.append(ip_network) if len(mgmt_ip_addr_list) == 1: return mgmt_ip_addr_list[0] elif len(mgmt_ip_addr_list) > 1: raise exception.ConfigException( '%s has two management IP addresses (%s) that are belong to ' 'the same subnet. This is likely a configuration error' % ( vm_name, ', '.join(mgmt_ip_addr_list))) else: raise exception.ValueException( 'No management IP addresses are discovered')
def parse_output(self, output): try: json_obj = json.loads(output) except ValueError: raise exception.ValueException('No JSON object could be decoded') if isinstance(json_obj, (dict,)): return [type('ps_json', (object,), json_obj)] elif isinstance(json_obj, (list,)): ret_list = [] for instance in json_obj: ret_list.append(type('ps_json', (object,), instance)) return ret_list raise exception.ValueException( 'json_obj is not list or dict but %s' % type(json_obj))
def __init__( self, name, br_iface, forward_mode=None, ip_addr=None, **kwargs): if not br_iface: raise exception.ValueException('"br_iface" argument is required') bridge = BridgeInterface( br_iface=br_iface, forward_mode=forward_mode or self._mode, ip_addr=ip_addr) super(Bridge, self).__init__(name=name, bridge=bridge)
def create(self): if not self.path: raise exception.ValueException('"path" is None') if not os.access(self.path, 0): log.info('Creating a directory %s ... ' % self.path) os.makedirs(self.path) log.info('"%s" is successfully created' % self.name)
def get_vm_manager(): """A factory function to return an BaseManager or its child class""" _system = platform.system() if _system == 'Linux': vm_module = importlib.import_module('virt.lib.linux.virtual_machine') return vm_module.LibvirtManager() elif _system == 'Windows': vm_module = importlib.import_module('virt.lib.windows.virtual_machine') return vm_module.PowerShellManager() raise exception.ValueException('Unsupported OS type')
def _get_root(self): if not self.iface_list or None in self.iface_list: raise exception.ValueException('"iface_list" is None or has None') root = super(MacVtap, self)._get_root() forward = ElementTree.SubElement( root, 'forward', mode=self.macvtap_mode) for iface in self.iface_list: ElementTree.SubElement(forward, 'interface', dev=iface) return root
def __init__( self, name, iface_list=None, iface=None, macvtap_mode='bridge', **kwargs): if not iface_list and not iface: raise exception.ValueException( 'Both "iface_list" and "iface" arguments cannot be "None"') iface_list = iface_list or [iface] super(MacVtap, self).__init__(name=name) self._iface_list = iface_list self._macvtap_mode = macvtap_mode
def power(cls, name, oper): _domain = domain.Domain(name=name, disk_file=None) if oper == 'on': _domain.start() elif oper == 'off': _domain.stop() elif oper == 'status': raise NotImplementedError('status is not supported yet') else: raise exception.ValueException( 'Invalid operation %s. choices=[on|off]' % oper)
def power(cls, name, oper): mapping = {'on': 'start-vm', 'off': 'stop-vm'} if oper not in mapping: raise exception.ValueException( 'invalid operation %s. choices=[on|off]' % oper) try: if oper == 'off': powershell.exec_powershell(mapping[oper], name=name, force=True) else: powershell.exec_powershell(mapping[oper], name=name) except exception.ValueException: return True
def create(self): if not self.path: raise exception.ValueException('"path" is None') if not os.access(self.path, 0): log.info('Creating a directory %s ... ' % self.path) os.makedirs(self.path) with LibvirtOpen(conn=self._conn, uri=self._uri) as conn: pool = conn.storagePoolDefineXML(self.get_xml()) pool.setAutostart(1) pool.create() log.info('"%s" is successfully created' % self.name)
def _get_root(self, **kwargs): root = ElementTree.Element('network') ElementTree.SubElement(root, 'name').text = self.name if self.bridge: if not self.bridge.br_iface: raise exception.ValueException( 'Bridge name cannot be None for NAT') ElementTree.SubElement(root, 'bridge', name=self.bridge.br_iface) if self.bridge.forward_mode: ElementTree.SubElement( root, 'forward', mode=self.bridge.forward_mode, **kwargs) # Add "ip" element root = self.bridge.get_sub_element_tree(root) return root
def factory(cls, name, mode=None, switch_id=None, **kwargs): _network = BaseHyperVSwitch(name=name, switch_id=switch_id, **kwargs) if not mode: # Expect to get an exisiting switch network_object = _network._get_object() ifdesc = network_object.NetAdapterInterfaceDescription iface = kwargs.pop('iface', None) # remove "iface" argument for _iface in powershell.exec_powershell( 'get-netadapter', select_clause='InterfaceDescription,Name', max_depth=1): if _iface.InterfaceDescription == ifdesc: iface = _iface.Name break for subclass in BaseHyperVSwitch._get_all_subclasses( BaseHyperVSwitch): if subclass.get_mode() == cls._get_mode_by_int( network_object.SwitchType): if network_object.IovEnabled: return SrIov(name=name, switch_id=network_object.Id, iface=iface, **kwargs) return subclass(name=name, switch_id=network_object.Id, iface=iface, **kwargs) raise exception.NotFoundException( 'Failed to detect the vswitch mode %s' % cls._get_mode_by_int(network_object.SwitchType)) for subclass in BaseHyperVSwitch._get_all_subclasses(BaseHyperVSwitch): if subclass.get_mode() == mode: return subclass(name=name, **kwargs) raise exception.ValueException('Invalid mode %s' % mode)
def get_mgmt_ip_addr(cls, vm_name, ip_network): """Return the management IP address of the virtual machine Due to livirtd-python does not provide APIs for guest agent yet, use shell command "virsh" to get the information. Args: vm_name (str): A name of the virtual machine ip_network (str): IP address/prefix (x.x.x.x/x) for network where the management IP address should be be long to """ mgmt_ip_addr_list = [] iface_list = cls._get_network(vm_name) for iface in iface_list: if 'ip-addresses' not in iface: log.debug('No IP addresses detected on %s (%s)' % (iface['name'], iface['hardware-address'])) continue for ip_addr in iface['ip-addresses']: if netaddr.IPAddress( ip_addr['ip-address']) in netaddr.IPNetwork( ip_network): mgmt_ip_addr_list.append(ip_addr['ip-address']) if len(mgmt_ip_addr_list) == 1: return mgmt_ip_addr_list[0] elif len(mgmt_ip_addr_list) > 1: raise exception.ConfigException( '%s has two management IP addresses (%s) that are belong to ' 'the same subnet. This is likely a configuration error' % (vm_name, ', '.join(mgmt_ip_addr_list))) else: raise exception.ValueException( 'No management IP addresses are discovered')
def get_ip_addr(mac_addr): if not re.match(r'([0-9a-f]{2}:){5}([0-9a-f]{2})', mac_addr, re.I): raise exception.ValueException('MAC address "%s" is invalid' % mac_addr) return '.'.join( [str(int(octet, 16)) for octet in mac_addr.split(':')[2:]] ) + '/' + str(int(mac_addr.split(':')[1]))
def __init__(self, name, iface, **kwargs): if not iface: raise exception.ValueException('"iface" argument is required') super(HostDev, self).__init__(name=name) self._iface = iface
def __init__(self, name, br_iface, **kwargs): if not br_iface: raise exception.ValueException('"br_iface" argument is required') super(OVS, self).__init__( name=name, br_iface=br_iface, forward_mode='bridge')
def get_template(name, *args, **kwargs): for subclass in KVMTemplate._get_all_subclasses(KVMTemplate): if subclass.name == name: return subclass(*args, **kwargs) raise exception.ValueException('No such template %s' % name)
def factory(cls, name, mode=None, **kwargs): _network = BaseLinuxVSwitch(name=name) forward_mode = None forward_interface = None ip_addr = None br_iface = None iface_list = None virtual_port = None if not mode: # Expect to get an existing switch if _network.object is None: raise exception.NotFoundException( 'vSwitch "%s" does not exist' % name) vswitch_xml = ElementTree.fromstring(_network.object.XMLDesc()) if vswitch_xml.find('forward') is not None: forward_mode = vswitch_xml.find('forward').get('mode') forward_interface = vswitch_xml.find('forward').get('dev') if vswitch_xml.findall('forward/interface') is not None: iface_list = [ iface.get('dev') for iface in vswitch_xml.findall('forward/interface')] if vswitch_xml.find('ip') is not None: _ip_addr = vswitch_xml.find('ip').get('address') _prefix = vswitch_xml.find('ip').get('prefix') ip_addr = _ip_addr + '/' + _prefix if vswitch_xml.find('bridge') is not None: br_iface = vswitch_xml.find('bridge').get('name') if forward_mode == 'nat': # NAT return NAT(name=name, br_iface=br_iface, ip_addr=ip_addr) elif forward_mode == 'hostdev': # SR-IOV: iface = vswitch_xml.find('forward/pf').get('dev') return HostDev(name=name, iface=iface) if iface_list: # MacVTAP return MacVtap( name=name, iface_list=iface_list, macvtap_mode=forward_mode) if virtual_port: # OVS return OVS(name=name, br_iface=br_iface) if forward_interface: # routed return Route( name=name, br_iface=br_iface, iface=forward_interface) if forward_mode: return Bridge( name=name, br_iface=br_iface, ) raise exception.ValueException( 'Failed to detect the vswitch mode. XML output: %s' % _network.get_xml() ) if _network.object is not None: # vswitch exists. Compare the mode, and if they are same, return # that object otherwise raise exception # _vswitch = cls.factory(name=name, **kwargs) # if _vswitch._mode == mode: # return _vswitch raise exception.ConfigException('vSwitch %s already exists' % name) # Creating a new vswitch for subclass in BaseLinuxVSwitch._get_all_subclasses(BaseLinuxVSwitch): if subclass.get_mode() == mode: return subclass(name, **kwargs) raise exception.ValueException('Invalid mode %s' % mode)
def __init__(self, name, br_iface, ip_addr=None, **kwargs): if not br_iface: raise exception.ValueException('"br_iface" argument is required') super(NAT, self).__init__( name=name, br_iface=br_iface, forward_mode='nat', ip_addr=ip_addr)